diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000000..a0e39ffd165 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,47 @@ +*.iml +out/ +*.ipr +*.iws +classpath.txt +version.properties +.project +.classpath +lib/* +build/* +generated-files/* +generated-sources/* +generated-code/* +*.swp +*.swo + +/target +/generated-files +/nbactions.xml +*.pyc +__pycache__ +samples/server-generator/scalatra/output +samples/server-generator/node/output/node_modules +samples/server-generator/scalatra/target +samples/server-generator/scalatra/output/.history +samples/client/petstore/qt5cpp/PetStore/moc_* +samples/client/petstore/qt5cpp/PetStore/*.o +samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata +samples/client/petstore/qt5cpp/build-* +samples/client/petstore/qt5cpp/PetStore/PetStore +samples/client/petstore/qt5cpp/PetStore/Makefile +samples/client/petstore/java/hello.txt +samples/client/petstore/android-java/hello.txt +samples/client/petstore/objc/Build +samples/client/petstore/objc/Pods +samples/server/petstore/nodejs/node_modules +target +.idea +.lib +atlassian-ide-plugin.xml +.DS_Store + +samples/client/petstore/php/SwaggerClient-php/composer.lock +samples/client/petstore/php/SwaggerClient-php/vendor/ + +samples/client/petstore/silex/SwaggerServer/composer.lock +samples/client/petstore/silex/SwaggerServer/venodr/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000000..0a3d093290e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM maven:3.3-jdk-7 + +WORKDIR /src +VOLUME /src +VOLUME /root/.m2/repository + +ADD . /opt/swagger-codegen + +RUN cd /opt/swagger-codegen && mvn package + +ENTRYPOINT ["java", "-jar", "/opt/swagger-codegen/modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"] + +CMD ["help"] diff --git a/README.md b/README.md index bcf69d624cb..703adaa7089 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,24 @@ This is the swagger codegen project, which allows generation of client libraries Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more. +## Build and run using docker + +``` +git clone https://github.com/swagger-api/swagger-codegen + +cd swagger-codegen + +./run-in-docker.sh mvn package + ``` + +Build a nodejs server stub: + + ``` +./run-in-docker.sh generate \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l nodejs \ + -o samples/server/petstore/nodejs + ``` ## Compatibility The Swagger Specification has undergone 3 revisions since initial creation in 2010. The swagger-codegen project has the following compatibilies with the swagger specification: @@ -170,6 +188,7 @@ AkkaScalaClientCodegen.java AndroidClientCodegen.java AsyncScalaClientCodegen.java CSharpClientCodegen.java +FlashClientCodegen.java JavaClientCodegen.java JaxRSServerCodegen.java NodeJSServerCodegen.java diff --git a/bin/csharp-dotnet2-petstore.sh b/bin/csharp-dotnet2-petstore.sh new file mode 100755 index 00000000000..fdab8bc413b --- /dev/null +++ b/bin/csharp-dotnet2-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l CsharpDotNet2 -o samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/flash-petstore.sh b/bin/flash-petstore.sh new file mode 100755 index 00000000000..20d75e8a8ac --- /dev/null +++ b/bin/flash-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/flash -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l flash -o samples/client/petstore/flash" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-inflector-petstore-server.sh b/bin/java-inflector-petstore-server.sh new file mode 100755 index 00000000000..5200ab26bb1 --- /dev/null +++ b/bin/java-inflector-petstore-server.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaInflector -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l inflector -o samples/server/petstore/java-inflector" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 26b6fef1135..812be6981d4 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -16,12 +16,14 @@ package io.swagger.codegen.plugin; * limitations under the License. */ +import io.swagger.codegen.CliOption; import io.swagger.codegen.ClientOptInput; import io.swagger.codegen.ClientOpts; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.DefaultGenerator; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; + import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -29,6 +31,9 @@ import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; +import config.Config; +import config.ConfigParser; + import java.io.File; import java.util.ServiceLoader; @@ -66,6 +71,12 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(name = "language", required = true) private String language; + /** + * Path to json configuration file. + */ + @Parameter(name = "configurationFile", required = false) + private String configurationFile; + /** * Add the output directory to the project as a source root, so that the @@ -90,7 +101,20 @@ public class CodeGenMojo extends AbstractMojo { if (null != templateDirectory) { config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory.getAbsolutePath()); } - + + if (null != configurationFile) { + Config genConfig = ConfigParser.read(configurationFile); + if (null != genConfig) { + for (CliOption langCliOption : config.cliOptions()) { + if (genConfig.hasOption(langCliOption.getOpt())) { + config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt())); + } + } + } else { + throw new RuntimeException("Unable to read configuration file"); + } + } + ClientOptInput input = new ClientOptInput().opts(new ClientOpts()).swagger(swagger); input.setConfig(config); new DefaultGenerator().opts(input).generate(); diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index aca706455e2..762aa3a72f2 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -83,9 +83,7 @@ - - incremental - + incremental -Xmx384m @@ -149,14 +147,6 @@ scala-maven-plugin ${scala-maven-plugin-version} - - org.apache.maven.plugins - maven-gpg-plugin - - release - sign - - @@ -180,7 +170,7 @@ - ${scala-version} + ${scala-version} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index c15590b11d2..4ef8bb23e66 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -65,6 +65,8 @@ public interface CodegenConfig { CodegenModel fromModel(String name, Model model); + CodegenModel fromModel(String name, Model model, Map allDefinitions); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions); List fromSecurity(Map schemes); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index db5d11f7002..bf58bd1cc36 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -63,7 +63,7 @@ import java.util.regex.Pattern; public class DefaultCodegen { - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); + protected static final Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); protected String outputFolder = ""; protected Set defaultIncludes = new HashSet(); @@ -80,6 +80,7 @@ public class DefaultCodegen { protected List supportingFiles = new ArrayList(); protected List cliOptions = new ArrayList(); protected boolean skipOverwrite; + protected boolean supportsInheritance = false; public List cliOptions() { return cliOptions; @@ -229,6 +230,11 @@ public class DefaultCodegen { } public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + return operationId; } @@ -426,14 +432,6 @@ public class DefaultCodegen { return dp.getDefault().toString(); } return "null"; - } else if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "new HashMap() "; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "new ArrayList<" + inner + ">() "; } else { return "null"; } @@ -510,6 +508,10 @@ public class DefaultCodegen { } public CodegenModel fromModel(String name, Model model) { + return fromModel(name, model, null); + } + + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { CodegenModel m = CodegenModelFactory.newInstance(CodegenModelType.MODEL); if (reservedWords.contains(name)) { m.name = escapeReservedWord(name); @@ -529,12 +531,59 @@ public class DefaultCodegen { // TODO } else if (model instanceof ComposedModel) { final ComposedModel composed = (ComposedModel) model; + Map properties = new HashMap(); + List required = new ArrayList(); + // parent model final RefModel parent = (RefModel) composed.getParent(); - final String parentModel = toModelName(parent.getSimpleRef()); - m.parent = parentModel; - addImport(m, parentModel); - final ModelImpl child = (ModelImpl) composed.getChild(); - addVars(m, child.getProperties(), child.getRequired()); + if (parent != null) { + final String parentRef = toModelName(parent.getSimpleRef()); + m.parent = parentRef; + addImport(m, parentRef); + if (!supportsInheritance && allDefinitions != null) { + final Model parentModel = allDefinitions.get(parentRef); + if (parentModel instanceof ModelImpl) { + final ModelImpl _parent = (ModelImpl) parentModel; + if (_parent.getProperties() != null) { + properties.putAll(_parent.getProperties()); + } + if (_parent.getRequired() != null) { + required.addAll(_parent.getRequired()); + } + } + } + } + // interfaces (intermediate models) + if (allDefinitions != null) { + for (RefModel _interface : composed.getInterfaces()) { + final String interfaceRef = toModelName(_interface.getSimpleRef()); + final Model interfaceModel = allDefinitions.get(interfaceRef); + if (interfaceModel instanceof ModelImpl) { + final ModelImpl _interfaceModel = (ModelImpl) interfaceModel; + if (_interfaceModel.getProperties() != null) { + properties.putAll(_interfaceModel.getProperties()); + } + if (_interfaceModel.getRequired() != null) { + required.addAll(_interfaceModel.getRequired()); + } + } + } + } + // child model (properties owned by the model itself) + Model child = composed.getChild(); + if (child != null && child instanceof RefModel && allDefinitions != null) { + final String childRef = ((RefModel) child).getSimpleRef(); + child = allDefinitions.get(childRef); + } + if (child != null && child instanceof ModelImpl) { + final ModelImpl _child = (ModelImpl) child; + if (_child.getProperties() != null) { + properties.putAll(_child.getProperties()); + } + if (_child.getRequired() != null) { + required.addAll(_child.getRequired()); + } + } + addVars(m, properties, required); } else { ModelImpl impl = (ModelImpl) model; if (impl.getAdditionalProperties() != null) { @@ -557,7 +606,7 @@ public class DefaultCodegen { public CodegenProperty fromProperty(String name, Property p) { if (p == null) { - LOGGER.error("unexpected missing property for name " + null); + LOGGER.error("unexpected missing property for name " + name); return null; } CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); @@ -1173,7 +1222,9 @@ public class DefaultCodegen { if (mappedType != null) { addImport(m, mappedType); } - } /** + } + + /** * Underscore the given word. * * @param word The word @@ -1235,9 +1286,8 @@ public class DefaultCodegen { } else { m.emptyVars = true; } - } public static String camelize(String word) { - return camelize(word, false); } + /** * Remove characters not suitable for variable or method name from the input and camelize it @@ -1258,7 +1308,13 @@ public class DefaultCodegen { name = name.substring(0, 1).toLowerCase() + name.substring(1); } return name; - } public static String camelize(String word, boolean lowercaseFirstLetter) { + } + + public static String camelize(String word) { + return camelize(word, false); + } + + public static String camelize(String word, boolean lowercaseFirstLetter) { // Replace all slashes with dots (package separator) Pattern p = Pattern.compile("\\/(.?)"); Matcher m = p.matcher(word); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index dd55c35bf9b..5e4566ab374 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -2,6 +2,8 @@ package io.swagger.codegen; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; + +import io.swagger.models.ComposedModel; import io.swagger.models.Contact; import io.swagger.models.Info; import io.swagger.models.License; @@ -11,7 +13,9 @@ import io.swagger.models.Path; import io.swagger.models.Swagger; import io.swagger.models.auth.OAuth2Definition; import io.swagger.models.auth.SecuritySchemeDefinition; +import io.swagger.models.parameters.Parameter; import io.swagger.util.Json; + import org.apache.commons.io.IOUtils; import java.io.File; @@ -21,6 +25,8 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -106,10 +112,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } if (swagger.getBasePath() != null) { hostBuilder.append(swagger.getBasePath()); - } else { - hostBuilder.append("/"); } - String contextPath = swagger.getBasePath() == null ? "/" : swagger.getBasePath(); + String contextPath = swagger.getBasePath() == null ? "" : swagger.getBasePath(); String basePath = hostBuilder.toString(); @@ -119,11 +123,13 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { // models Map definitions = swagger.getDefinitions(); if (definitions != null) { - for (String name : definitions.keySet()) { + List sortedModelKeys = sortModelsByInheritance(definitions); + + for (String name : sortedModelKeys) { Model model = definitions.get(name); Map modelMap = new HashMap(); modelMap.put(name, model); - Map models = processModels(config, modelMap); + Map models = processModels(config, modelMap, definitions); models.putAll(config.additionalProperties()); allModels.add(((List) models.get("models")).get(0)); @@ -327,17 +333,63 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } } + private List sortModelsByInheritance(final Map definitions) { + List sortedModelKeys = new ArrayList(definitions.keySet()); + Comparator cmp = new Comparator() { + @Override + public int compare(String o1, String o2) { + Model model1 = definitions.get(o1); + Model model2 = definitions.get(o2); + + int model1InheritanceDepth = getInheritanceDepth(model1); + int model2InheritanceDepth = getInheritanceDepth(model2); + + if (model1InheritanceDepth == model2InheritanceDepth) { + return 0; + } else if (model1InheritanceDepth > model2InheritanceDepth) { + return 1; + } else { + return -1; + } + } + + private int getInheritanceDepth(Model model) { + int inheritanceDepth = 0; + Model parent = getParent(model); + + while (parent != null) { + inheritanceDepth++; + parent = getParent(parent); + } + + return inheritanceDepth; + } + + private Model getParent(Model model) { + if (model instanceof ComposedModel) { + return definitions.get(((ComposedModel) model).getParent().getReference()); + } + + return null; + } + }; + + Collections.sort(sortedModelKeys, cmp); + + return sortedModelKeys; + } + public Map> processPaths(Map paths) { Map> ops = new HashMap>(); for (String resourcePath : paths.keySet()) { Path path = paths.get(resourcePath); - processOperation(resourcePath, "get", path.getGet(), ops); - processOperation(resourcePath, "put", path.getPut(), ops); - processOperation(resourcePath, "post", path.getPost(), ops); - processOperation(resourcePath, "delete", path.getDelete(), ops); - processOperation(resourcePath, "patch", path.getPatch(), ops); - processOperation(resourcePath, "options", path.getOptions(), ops); + processOperation(resourcePath, "get", path.getGet(), ops, path); + processOperation(resourcePath, "put", path.getPut(), ops, path); + processOperation(resourcePath, "post", path.getPost(), ops, path); + processOperation(resourcePath, "delete", path.getDelete(), ops, path); + processOperation(resourcePath, "patch", path.getPatch(), ops, path); + processOperation(resourcePath, "options", path.getOptions(), ops, path); } return ops; } @@ -350,14 +402,35 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return map.get(name); } - - public void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations) { + public void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations, Path path) { if (operation != null) { List tags = operation.getTags(); if (tags == null) { tags = new ArrayList(); tags.add("default"); } + + /* + build up a set of parameter "ids" defined at the operation level + per the swagger 2.0 spec "A unique parameter is defined by a combination of a name and location" + i'm assuming "location" == "in" + */ + Set operationParameters = new HashSet(); + if (operation.getParameters() != null) { + for (Parameter parameter : operation.getParameters()) { + operationParameters.add(generateParameterId(parameter)); + } + } + + //need to propagate path level down to the operation + if(path.getParameters() != null) { + for (Parameter parameter : path.getParameters()) { + //skip propagation if a parameter with the same name is already defined at the operation level + if (!operationParameters.contains(generateParameterId(parameter))) { + operation.addParameter(parameter); + } + } + } for (String tag : tags) { CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions()); @@ -392,7 +465,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } authMethods.put(securityName, oauth2Operation); } else { - authMethods.put(securityName, securityDefinition); + authMethods.put(securityName, securityDefinition); } } } @@ -403,6 +476,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } } + private String generateParameterId(Parameter parameter) { + return parameter.getName() + ":" + parameter.getIn(); + } + protected String sanitizeTag(String tag) { // remove spaces and make strong case String[] parts = tag.split(" "); @@ -475,14 +552,14 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return operations; } - public Map processModels(CodegenConfig config, Map definitions) { + public Map processModels(CodegenConfig config, Map definitions, Map allDefinitions) { Map objs = new HashMap(); objs.put("package", config.modelPackage()); List models = new ArrayList(); Set allImports = new LinkedHashSet(); for (String key : definitions.keySet()) { Model mm = definitions.get(key); - CodegenModel cm = config.fromModel(key, mm); + CodegenModel cm = config.fromModel(key, mm, allDefinitions); Map mo = new HashMap(); mo.put("model", cm); mo.put("importPath", config.toModelImport(key)); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java new file mode 100644 index 00000000000..38c0c5307ba --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -0,0 +1,144 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public AbstractTypeScriptClientCodegen() { + super(); + supportsInheritance = true; + reservedWords = new HashSet(Arrays.asList("abstract", + "continue", "for", "new", "switch", "assert", "default", "if", + "package", "synchronized", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", + "byte", "else", "import", "public", "throws", "case", "enum", + "instanceof", "return", "transient", "catch", "extends", "int", + "short", "try", "char", "final", "interface", "static", "void", + "class", "finally", "const", "super", "while")); + + languageSpecificPrimitives = new HashSet(Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object")); + instantiationTypes.put("array", "Array"); + + typeMapping = new HashMap(); + typeMapping.put("Array", "Array"); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("int", "number"); + typeMapping.put("float", "number"); + typeMapping.put("number", "number"); + typeMapping.put("long", "number"); + typeMapping.put("short", "number"); + typeMapping.put("char", "string"); + typeMapping.put("double", "number"); + typeMapping.put("object", "any"); + typeMapping.put("integer", "number"); + typeMapping.put("Map", "any"); + typeMapping.put("DateTime", "Date"); + + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) + return name; + + // camelize the variable name + // pet_id => PetId + name = camelize(name, true); + + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) + name = escapeReservedWord(name); + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) + throw new RuntimeException(name + + " (reserved word) cannot be used as a model name"); + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return "{ [key: string]: "+ getTypeDeclaration(inner) + "; }"; + } else if (p instanceof FileProperty) { + return "any"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return type; + } else + type = swaggerType; + return type; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java index efcd771ac10..f9490e3d3dd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -251,6 +251,11 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + return super.toOperationId(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, operationId)); } @@ -396,4 +401,4 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon } } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index e65736a63f0..f570cc42e82 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -13,6 +13,8 @@ import java.io.File; import java.util.Arrays; import java.util.HashSet; +import org.apache.commons.lang.StringUtils; + public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; @@ -168,6 +170,11 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java index c941d8b8d97..53faf2f9e1f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java @@ -21,6 +21,8 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import org.apache.commons.lang.StringUtils; + public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; @@ -204,4 +206,4 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo return "null"; } } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 5833d7287cc..1d7accd3b27 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -14,6 +14,8 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import org.apache.commons.lang.StringUtils; + public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String packageName = "IO.Swagger"; protected String packageVersion = "1.0.0"; @@ -237,6 +239,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java new file mode 100644 index 00000000000..432e7ae3fa2 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java @@ -0,0 +1,255 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.codegen.CliOption; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; + +public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String packageName = "IO.Swagger"; + protected String packageVersion = "1.0.0"; + protected String clientPackage = "IO.Swagger.Client"; + protected String sourceFolder = "src" + File.separator + "main" + File.separator + "CsharpDotNet2"; + + public CsharpDotNet2ClientCodegen() { + super(); + outputFolder = "generated-code" + File.separator + "CsharpDotNet2"; + modelTemplateFiles.put("model.mustache", ".cs"); + apiTemplateFiles.put("api.mustache", ".cs"); + templateDir = "CsharpDotNet2"; + apiPackage = "IO.Swagger.Api"; + modelPackage = "IO.Swagger.Model"; + + reservedWords = new HashSet( + Arrays.asList( + "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while") + ); + + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "string", + "bool?", + "double?", + "int?", + "long?", + "float?", + "byte[]", + "List", + "Dictionary", + "DateTime?", + "String", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Stream", // not really a primitive, we include it to avoid model import + "Object") + ); + instantiationTypes.put("array", "List"); + instantiationTypes.put("map", "Dictionary"); + + typeMapping = new HashMap(); + typeMapping.put("string", "string"); + typeMapping.put("boolean", "bool?"); + typeMapping.put("integer", "int?"); + typeMapping.put("float", "float?"); + typeMapping.put("long", "long?"); + typeMapping.put("double", "double?"); + typeMapping.put("number", "double?"); + typeMapping.put("datetime", "DateTime?"); + typeMapping.put("date", "DateTime?"); + typeMapping.put("file", "Stream"); + typeMapping.put("array", "List"); + typeMapping.put("list", "List"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("object", "Object"); + + cliOptions.clear(); + cliOptions.add(new CliOption("packageName", "C# package name (convention: Camel.Case), default: IO.Swagger")); + cliOptions.add(new CliOption("packageVersion", "C# package version, default: 1.0.0")); + + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey("packageVersion")) { + packageVersion = (String) additionalProperties.get("packageVersion"); + } else { + additionalProperties.put("packageVersion", packageVersion); + } + + if (additionalProperties.containsKey("packageName")) { + packageName = (String) additionalProperties.get("packageName"); + apiPackage = packageName + ".Api"; + modelPackage = packageName + ".Model"; + clientPackage = packageName + ".Client"; + } else { + additionalProperties.put("packageName", packageName); + } + + if (additionalProperties.containsKey("clientPackage")) { + this.setClientPackage((String) additionalProperties.get("clientPackage")); + } else { + additionalProperties.put("clientPackage", clientPackage); + } + + supportingFiles.add(new SupportingFile("Configuration.mustache", + (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "Configuration.cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", + (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiClient.cs")); + supportingFiles.add(new SupportingFile("ApiException.mustache", + (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiException.cs")); + supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", "packages.config")); + supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh")); + supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + + } + + public void setClientPackage(String clientPackage) { + this.clientPackage = clientPackage; + } + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "CsharpDotNet2"; + } + + public String getHelp() { + return "Generates a C# .Net 2.0 client library."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return (outputFolder + File.separator + sourceFolder + File.separator + apiPackage()).replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return (outputFolder + File.separator + sourceFolder + File.separator + modelPackage()).replace('.', File.separatorChar); + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + // camelize the variable name + // pet_id => PetId + name = camelize(name); + + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + // camelize(lower) the variable name + // pet_id => petId + name = camelize(name, true); + + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType.toLowerCase())) { + type = typeMapping.get(swaggerType.toLowerCase()); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = swaggerType; + } + return toModelName(type); + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return camelize(operationId); + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java new file mode 100755 index 00000000000..ca0979fb694 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java @@ -0,0 +1,367 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.AbstractNumericProperty; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BooleanProperty; +import io.swagger.models.properties.DateProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.DecimalProperty; +import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.FloatProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.PropertyBuilder; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; + +import java.io.File; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HashMap; + +import org.apache.commons.lang.StringUtils; + +public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String packageName = "io.swagger"; + protected String packageVersion = null; + + protected String invokerPackage = "io.swagger"; + protected String sourceFolder = "src/main/flex"; + + public FlashClientCodegen() { + super(); + + modelPackage = "io.swagger.client.model"; + apiPackage = "io.swagger.client.api"; + outputFolder = "generated-code" + File.separatorChar + "flash"; + modelTemplateFiles.put("model.mustache", ".as"); + modelTemplateFiles.put("modelList.mustache", "List.as"); + apiTemplateFiles.put("api.mustache", ".as"); + templateDir = "flash"; + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("Number"); + languageSpecificPrimitives.add("Boolean"); + languageSpecificPrimitives.add("String"); + languageSpecificPrimitives.add("Date"); + languageSpecificPrimitives.add("Array"); + languageSpecificPrimitives.add("Dictionary"); + + typeMapping.clear(); + typeMapping.put("integer", "Number"); + typeMapping.put("float", "Number"); + typeMapping.put("long", "Number"); + typeMapping.put("double", "Number"); + typeMapping.put("array", "Array"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("date", "Date"); + typeMapping.put("DateTime", "Date"); + typeMapping.put("object", "Object"); + typeMapping.put("file", "File"); + + importMapping = new HashMap(); + importMapping.put("File", "flash.filesystem.File"); + + // from + reservedWords = new HashSet( + Arrays.asList( +"add", "for", "lt", "tellTarget", "and", "function", "ne", "this", "break", "ge", "new", "typeof", "continue", "gt", "not", "var", "delete", "if", "on", "void", "do", "ifFrameLoaded", "onClipEvent", "while", "else", "in", "or", "with", "eq", "le", "return")); + + cliOptions.clear(); + cliOptions.add(new CliOption("packageName", "flash package name (convention: package.name), default: io.swagger")); + cliOptions.add(new CliOption("packageVersion", "flash package version, default: 1.0.0")); + cliOptions.add(new CliOption("invokerPackage", "root package for generated code")); + cliOptions.add(new CliOption("sourceFolder", "source folder for generated code. e.g. src/main/flex")); + + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey("invokerPackage")) { + this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); + } else { + //not set, use default to be passed to template + additionalProperties.put("invokerPackage", invokerPackage); + } + + if (additionalProperties.containsKey("sourceFolder")) { + this.setSourceFolder((String) additionalProperties.get("sourceFolder")); + } + + if (additionalProperties.containsKey("packageName")) { + setPackageName((String) additionalProperties.get("packageName")); + apiPackage = packageName + ".client.api"; + modelPackage = packageName + ".client.model"; + } + else { + setPackageName("io.swagger"); + } + + if (additionalProperties.containsKey("packageVersion")) { + setPackageVersion((String) additionalProperties.get("packageVersion")); + } + else { + setPackageVersion("1.0.0"); + } + + additionalProperties.put("packageName", packageName); + additionalProperties.put("packageVersion", packageVersion); + + //modelPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + "model"; + //apiPackage = invokerPackage + File.separatorChar + "client" + File.separatorChar + "api"; + + final String invokerFolder = (sourceFolder + File.separator + invokerPackage + File.separator + "swagger" + File.separator).replace(".", File.separator).replace('.', File.separatorChar); + + supportingFiles.add(new SupportingFile("ApiInvoker.as", invokerFolder + "common", "ApiInvoker.as")); + supportingFiles.add(new SupportingFile("ApiUrlHelper.as", invokerFolder + "common", "ApiUrlHelper.as")); + supportingFiles.add(new SupportingFile("ApiUserCredentials.as", invokerFolder + "common", "ApiUserCredentials.as")); + supportingFiles.add(new SupportingFile("ListWrapper.as", invokerFolder + "common", "ListWrapper.as")); + supportingFiles.add(new SupportingFile("SwaggerApi.as", invokerFolder + "common", "SwaggerApi.as")); + supportingFiles.add(new SupportingFile("XMLWriter.as", invokerFolder + "common", "XMLWriter.as")); + supportingFiles.add(new SupportingFile("ApiError.as", invokerFolder + "exception", "ApiErrors.as")); + supportingFiles.add(new SupportingFile("ApiErrorCodes.as", invokerFolder + "exception", "ApiErrorCodes.as")); + supportingFiles.add(new SupportingFile("ApiClientEvent.as", invokerFolder + "event", "ApiClientEvent.as")); + supportingFiles.add(new SupportingFile("Response.as", invokerFolder + "event", "Response.as")); + supportingFiles.add(new SupportingFile("build.properties", sourceFolder, "build.properties")); + supportingFiles.add(new SupportingFile("build.xml", sourceFolder, "build.xml")); + supportingFiles.add(new SupportingFile("AirExecutorApp-app.xml", sourceFolder + File.separatorChar + "bin", "AirExecutorApp-app.xml")); + supportingFiles.add(new SupportingFile("ASAXB-0.1.1.swc", sourceFolder + File.separatorChar + "lib", "ASAXB-0.1.1.swc")); + supportingFiles.add(new SupportingFile("as3corelib.swc", sourceFolder + File.separatorChar + "lib", "as3corelib.swc")); + supportingFiles.add(new SupportingFile("flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc", sourceFolder + File.separator + "lib" + File.separator + "ext", "flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder + File.separator + "lib" + File.separator + "ext", "flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc", sourceFolder + File.separator + "lib" + File.separator + "ext", "flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc")); + supportingFiles.add(new SupportingFile("flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc", sourceFolder + File.separator + "lib" + File.separator + "ext", "flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc")); + } + + private static String dropDots(String str) { + return str.replaceAll("\\.", "_"); + } + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "flash"; + } + + public String getHelp() { + return "Generates a Flash client library."; + } + + @Override + public String escapeReservedWord(String name) { + return name + "_"; + } + + @Override + public String apiFileFolder() { + return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); + } + + public String modelFileFolder() { + return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p); + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p); + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = toModelName(swaggerType); + } + return type; + } + + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + return "null"; + } else if (p instanceof BooleanProperty) { + return "false"; + } else if (p instanceof DateProperty) { + return "null"; + } else if (p instanceof DateTimeProperty) { + return "null"; + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0.0"; + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0.0"; + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0"; + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "0"; + } else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new Dictionary()"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "new Array()"; + } else { + return "null"; + } + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } + + // underscore the variable name + // petId => pet_id + name = camelize(dropDots(name), true); + + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // underscore the model file name + // PhoneNumber => phone_number + return camelize(dropDots(name)); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return camelize(name) + "Api"; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Api"; + } + + @Override + public String toApiVarName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + return camelize(name) + "Api"; + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return underscore(operationId); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + public void setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + +} + + diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index 06b1d90d786..099a9cb9add 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -13,13 +13,15 @@ import java.io.File; import java.util.Arrays; import java.util.HashSet; +import org.apache.commons.lang.StringUtils; + public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-java-client"; protected String artifactVersion = "1.0.0"; protected String sourceFolder = "src/main/java"; - + protected String localVariablePrefix = ""; public JavaClientCodegen() { super(); outputFolder = "generated-code/java"; @@ -59,6 +61,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(new CliOption("artifactId", "artifactId in generated pom.xml")); cliOptions.add(new CliOption("artifactVersion", "artifact version in generated pom.xml")); cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); + cliOptions.add(new CliOption("localVariablePrefix", "prefix for generated code members and local variables")); } public CodegenType getTag() { @@ -109,6 +112,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { this.setSourceFolder((String) additionalProperties.get("sourceFolder")); } + + if (additionalProperties.containsKey("localVariablePrefix")) { + this.setLocalVariablePrefix((String) additionalProperties.get("localVariablePrefix")); + } + final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); @@ -205,6 +213,18 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return super.getTypeDeclaration(p); } + @Override + public String toDefaultValue(Property p) { + if (p instanceof ArrayProperty) { + final ArrayProperty ap = (ArrayProperty) p; + return String.format("new ArrayList<%s>()", getTypeDeclaration(ap.getItems())); + } else if (p instanceof MapProperty) { + final MapProperty ap = (MapProperty) p; + return String.format("new HashMap()", getTypeDeclaration(ap.getAdditionalProperties())); + } + return super.toDefaultValue(p); + } + @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); @@ -222,6 +242,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); @@ -249,4 +274,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { public void setSourceFolder(String sourceFolder) { this.sourceFolder = sourceFolder; } + + public void setLocalVariablePrefix(String localVariablePrefix) { + this.localVariablePrefix = localVariablePrefix; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java new file mode 100644 index 00000000000..168e214aef1 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java @@ -0,0 +1,188 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.util.Json; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +public class JavaInflectorServerCodegen extends JavaClientCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.handler"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-inflector-server"; + protected String artifactVersion = "1.0.0"; + protected String title = "Swagger Inflector"; + + public JavaInflectorServerCodegen() { + super(); + + sourceFolder = "src/main/java"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "JavaInflector"; + + apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler"); + modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("title", title); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float") + ); + } + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "inflector"; + } + + public String getHelp() { + return "Generates a Java Inflector Server application."; + } + + @Override + public void processOpts() { + super.processOpts(); + + supportingFiles.clear(); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("web.mustache", "src/main/webapp/WEB-INF", "web.xml")); + supportingFiles.add(new SupportingFile("inflector.mustache", "", "inflector.yaml")); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getTypeDeclaration(inner); + } + return super.getTypeDeclaration(p); + } + + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + String basePath = resourcePath; + if (basePath.startsWith("/")) { + basePath = basePath.substring(1); + } + int pos = basePath.indexOf("/"); + if (pos > 0) { + basePath = basePath.substring(0, pos); + } + + if (basePath == "") { + basePath = "default"; + } else { + if (co.path.startsWith("/" + basePath)) { + co.path = co.path.substring(("/" + basePath).length()); + } + co.subresourceOperation = !co.path.isEmpty(); + } + List opList = operations.get(basePath); + if (opList == null) { + opList = new ArrayList(); + operations.put(basePath, opList); + } + opList.add(co); + co.baseName = basePath; + } + + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + if (operation.returnType == null) { + operation.returnType = "Void"; + } else if (operation.returnType.startsWith("List")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("List<".length(), end); + operation.returnContainer = "List"; + } + } else if (operation.returnType.startsWith("Map")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("Map<".length(), end); + operation.returnContainer = "Map"; + } + } else if (operation.returnType.startsWith("Set")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if (end > 0) { + operation.returnType = rt.substring("Set<".length(), end); + operation.returnContainer = "Set"; + } + } + } + } + return objs; + } + + @Override + public void processSwagger(Swagger swagger) { + super.processSwagger(swagger); + + try { + File file = new File( outputFolder + "/src/main/swagger/swagger.json" ); + file.getParentFile().mkdirs(); + + FileWriter swaggerFile = new FileWriter(file); + swaggerFile.write( Json.pretty( swagger )); + swaggerFile.flush(); + swaggerFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultController"; + } + name = name.replaceAll("[^a-zA-Z0-9]+", "_"); + return camelize(name)+ "Controller"; + } + + public boolean shouldOverwrite(String filename) { + return super.shouldOverwrite(filename); + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java index 99121f8d297..df320797515 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java @@ -89,21 +89,6 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf } - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getTypeDeclaration(inner); - } - return super.getTypeDeclaration(p); - } - @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { String basePath = resourcePath; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index 28a0abfb6f7..5d0a7034537 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -9,11 +9,19 @@ import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import java.io.File; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Lists; +import com.google.common.collect.Multimap; public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { protected String apiVersion = "1.0.0"; @@ -197,4 +205,50 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig } return objs; } + + @SuppressWarnings("unchecked") + private Map getOperations(Map objs) { + Map apiInfo = (Map) objs.get("apiInfo"); + List> apis = (List>) apiInfo.get("apis"); + Map api = apis.get(0); + return (Map) api.get("operations"); + } + + private List> sortOperationsByPath(List ops) { + Multimap opsByPath = ArrayListMultimap.create(); + + for (CodegenOperation op : ops) { + opsByPath.put(op.path, op); + } + + List> opsByPathList = new ArrayList>(); + for (Entry> entry : opsByPath.asMap().entrySet()) { + Map opsByPathEntry = new HashMap(); + opsByPathList.add(opsByPathEntry); + opsByPathEntry.put("path", entry.getKey()); + opsByPathEntry.put("operation", entry.getValue()); + List operationsForThisPath = Lists.newArrayList(entry.getValue()); + operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = null; + if (opsByPathList.size() < opsByPath.asMap().size()) { + opsByPathEntry.put("hasMore", "true"); + } + } + + return opsByPathList; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + Map operations = getOperations(objs); + + if (operations != null) { + @SuppressWarnings("unchecked") + List ops = (List) operations.get("operation"); + + List> opsByPathList = sortOperationsByPath(ops); + operations.put("operationsByPath", opsByPathList); + } + + return super.postProcessSupportingFileData(objs); + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 0fdb19e806d..cb6ec79a984 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -16,6 +16,8 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Set; +import org.apache.commons.lang.StringUtils; + public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { protected Set foundationClasses = new HashSet(); protected String podName = "SwaggerClient"; @@ -57,7 +59,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.clear(); typeMapping.put("enum", "NSString"); - typeMapping.put("Date", "NSDate"); + typeMapping.put("date", "NSDate"); typeMapping.put("DateTime", "NSDate"); typeMapping.put("boolean", "NSNumber"); typeMapping.put("string", "NSString"); @@ -213,21 +215,22 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { Property inner = ap.getItems(); String innerType = getSwaggerType(inner); - // In this codition, type of property p is array of primitive, - // return container type with pointer, e.g. `NSArray*' - if (languageSpecificPrimitives.contains(innerType)) { - return getSwaggerType(p) + "*"; - } - - // In this codition, type of property p is array of model, - // return container type combine inner type with pointer, e.g. `NSArray*' String innerTypeDeclaration = getTypeDeclaration(inner); if (innerTypeDeclaration.endsWith("*")) { innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); } - return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + // In this codition, type of property p is array of primitive, + // return container type with pointer, e.g. `NSArray* /* NSString */' + if (languageSpecificPrimitives.contains(innerType)) { + return getSwaggerType(p) + "*" + " /* " + innerTypeDeclaration + " */"; + } + // In this codition, type of property p is array of model, + // return container type combine inner type with pointer, e.g. `NSArray*' + else { + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + } } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); @@ -358,6 +361,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index 8c079973a1b..d54c44a9bdd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -9,11 +9,12 @@ import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.codegen.CliOption; - import java.io.File; import java.util.Arrays; import java.util.HashSet; +import org.apache.commons.lang.StringUtils; + public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { protected String moduleName = "SwaggerClient"; protected String moduleVersion = "1.0.0"; @@ -158,15 +159,17 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { + // return the name in underscore style + // PhoneNumber => phone_number + name = underscore(name); + // parameter name starting with number won't compile // need to escape it by appending _ at the beginning - if (name.matches("^[0-9]")) { + if (name.matches("^\\d.*")) { name = "_" + name; } - // return the name in underscore style - // PhoneNumber => phone_number - return underscore(name); + return name; } @Override @@ -213,6 +216,11 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 188e5c76644..eaf758cf1c4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -15,6 +15,8 @@ import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import org.apache.commons.lang.StringUtils; + public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "Swagger\\Client"; protected String composerVendorName = "swagger"; @@ -77,12 +79,12 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "object"); typeMapping.put("DateTime", "\\DateTime"); - cliOptions.add(new CliOption("invokerPackage", "The main namespace to use for all classes.")); - cliOptions.add(new CliOption("packagePath", "The main package name for classes.")); + cliOptions.add(new CliOption("invokerPackage", "The main namespace to use for all classes. e.g. Yay\\Pets")); + cliOptions.add(new CliOption("packagePath", "The main package name for classes. e.g. GeneratedPetstore")); cliOptions.add(new CliOption("srcBasePath", "The directory under packagePath to serve as source root.")); - cliOptions.add(new CliOption("composerVendorName", "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name.")); - cliOptions.add(new CliOption("composerProjectName", "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name.")); - cliOptions.add(new CliOption("artifactVersion", "The version to use in the composer package version field.")); + cliOptions.add(new CliOption("composerVendorName", "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets")); + cliOptions.add(new CliOption("composerProjectName", "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client")); + cliOptions.add(new CliOption("artifactVersion", "The version to use in the composer package version field. e.g. 1.2.3")); } public String getPackagePath() { @@ -282,15 +284,17 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { + // return the name in underscore style + // PhoneNumber => phone_number + name = underscore(name); + // parameter name starting with number won't compile // need to escape it by appending _ at the beginning - if (name.matches("^[0-9]")) { + if (name.matches("^\\d.*")) { name = "_" + name; } - // return the name in underscore style - // PhoneNumber => phone_number - return underscore(name); + return name; } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java index 71562e6ba37..70c090cd7a3 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java @@ -12,6 +12,8 @@ import java.io.File; import java.util.Arrays; import java.util.HashSet; +import org.apache.commons.lang.StringUtils; + public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfig { String module = "client"; @@ -201,6 +203,11 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index c0430515201..e0e1bdc07f8 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -13,6 +13,8 @@ import java.io.File; import java.util.Arrays; import java.util.HashSet; +import org.apache.commons.lang.StringUtils; + public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { protected String packageName = null; protected String packageVersion = null; @@ -117,7 +119,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String escapeReservedWord(String name) { - return "_" + name; + return name + "_"; } @Override @@ -160,8 +162,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig } public String toDefaultValue(Property p) { - // TODO: Support Python def value - return "null"; + return "None"; } @Override @@ -183,6 +184,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig name = escapeReservedWord(name); } + // remove leading underscore + name = name.replaceAll("^_*", ""); + return name; } @@ -244,6 +248,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java index e043c68baf9..66d3f19f948 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java @@ -15,6 +15,8 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import org.apache.commons.lang.StringUtils; + public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; @@ -171,6 +173,11 @@ public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConf @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index c82b5f7b6ce..42b824ad8b2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -13,6 +13,8 @@ import java.io.File; import java.util.Arrays; import java.util.HashSet; +import org.apache.commons.lang.StringUtils; + public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { protected String gemName = null; protected String moduleName = null; @@ -263,6 +265,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index 6ad296a0210..5d8ae4b89b6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -24,6 +24,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import org.apache.commons.lang.StringUtils; + public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; @@ -209,6 +211,11 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java index fb5005566c6..8bd4d627d56 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java @@ -88,11 +88,11 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig } public CodegenType getTag() { - return CodegenType.CLIENT; + return CodegenType.SERVER; } public String getName() { - return "silex"; + return "silex-PHP"; } public String getHelp() { @@ -154,15 +154,17 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig @Override public String toVarName(String name) { + // return the name in underscore style + // PhoneNumber => phone_number + name = underscore(name); + // parameter name starting with number won't compile // need to escape it by appending _ at the beginning - if (name.matches("^[0-9]")) { + if (name.matches("^\\d.*")) { name = "_" + name; } - // return the name in underscore style - // PhoneNumber => phone_number - return underscore(name); + return name; } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java index 44cf978eb1d..5bc402fe0c4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java @@ -13,6 +13,8 @@ import java.io.File; import java.util.Arrays; import java.util.HashSet; +import org.apache.commons.lang.StringUtils; + public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfig { protected String gemName = null; protected String moduleName = null; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java index 62642183906..8ee34768b5e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java @@ -1,10 +1,6 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.CodegenResponse; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.*; import io.swagger.models.Operation; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; @@ -28,7 +24,7 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen protected String configPackage = ""; public SpringMVCServerCodegen() { - super.processOpts(); + super(); outputFolder = "generated-code/javaSpringMVC"; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); @@ -56,6 +52,9 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen "Long", "Float") ); + + cliOptions.add(new CliOption("configPackage", "configuration package for generated code")); + } public CodegenType getTag() { @@ -74,6 +73,10 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen public void processOpts() { super.processOpts(); + if (additionalProperties.containsKey("configPackage")) { + this.setConfigPackage((String) additionalProperties.get("configPackage")); + } + supportingFiles.clear(); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); @@ -183,5 +186,9 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen } return objs; } + + public void setConfigPackage(String configPackage) { + this.configPackage = configPackage; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 5d4f5f341a7..55c3864adb7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -100,7 +100,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("number", "Double"); typeMapping.put("double", "Double"); typeMapping.put("object", "String"); - typeMapping.put("file", "NSData"); + typeMapping.put("file", "NSURL"); importMapping = new HashMap(); @@ -109,6 +109,17 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available.")); cliOptions.add(new CliOption("unwrapRequired", "Treat 'required' properties in response as non-optional " + "(which would crash the app if api returns null as opposed to required option specified in json schema")); + cliOptions.add(new CliOption("podSource", "Source information used for Podspec")); + cliOptions.add(new CliOption("podVersion", "Version used for Podspec")); + cliOptions.add(new CliOption("podAuthors", "Authors used for Podspec")); + cliOptions.add(new CliOption("podSocialMediaURL", "Social Media URL used for Podspec")); + cliOptions.add(new CliOption("podDocsetURL", "Docset URL used for Podspec")); + cliOptions.add(new CliOption("podLicense", "License used for Podspec")); + cliOptions.add(new CliOption("podHomepage", "Homepage used for Podspec")); + cliOptions.add(new CliOption("podSummary", "Summary used for Podspec")); + cliOptions.add(new CliOption("podDescription", "Description used for Podspec")); + cliOptions.add(new CliOption("podScreenshots", "Screenshots used for Podspec")); + cliOptions.add(new CliOption("podDocumentationURL", "Documentation URL used for Podspec")); } @Override @@ -143,6 +154,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("usePromiseKit", true); } + supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec")); supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, @@ -283,4 +295,4 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { return builder.toString(); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java index 34305d7c56f..7dc0b8ec3bd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java @@ -25,6 +25,8 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; +import org.apache.commons.lang.StringUtils; + public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig { protected static String PREFIX = "Sami"; protected Set foundationClasses = new HashSet(); @@ -265,6 +267,11 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return$ if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index 11cae0de0ef..8eec2b8772e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -1,25 +1,28 @@ package io.swagger.codegen.languages; -import java.io.File; - import io.swagger.codegen.SupportingFile; -public class TypeScriptAngularClientCodegen extends TypeScriptNodeClientCodegen { +import java.io.File; + +public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen { @Override public String getName() { return "typescript-angular"; } - + + public String getHelp() { + return "Generates a TypeScript AngurlarJS client library."; + } + public TypeScriptAngularClientCodegen() { super(); outputFolder = "generated-code/typescript-angular"; modelTemplateFiles.put("model.mustache", ".ts"); apiTemplateFiles.put("api.mustache", ".ts"); templateDir = "TypeScript-Angular"; - apiPackage = "api"; - modelPackage = "model"; - - supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage + File.separator, "api.d.ts")); + apiPackage = "API.Client"; + modelPackage = "API.Client"; + supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts")); } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index 0ea33f21709..b92598b1fb6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -1,171 +1,24 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.*; -import io.swagger.models.properties.*; +import io.swagger.codegen.SupportingFile; -import java.util.*; -import java.io.File; +public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen { -public class TypeScriptNodeClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-typescript-node-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/typescript"; + @Override + public String getName() { + return "typescript-node"; + } - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } + @Override + public String getHelp() { + return "Generates a TypeScript nodejs client library."; + } - @Override - public String getName() { - return "typescript-node"; - } + public TypeScriptNodeClientCodegen() { + super(); + outputFolder = "generated-code/typescript-node"; + templateDir = "TypeScript-node"; + supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); + } - @Override - public String getHelp() { - return "Generates a TypeScript nodejs client library."; - } - - public TypeScriptNodeClientCodegen() { - super(); - outputFolder = "generated-code/typescript-node"; - modelTemplateFiles.put("model.mustache", ".ts"); - apiTemplateFiles.put("api.mustache", ".ts"); - templateDir = "TypeScript-node"; - apiPackage = "api"; - modelPackage = "model"; - - reservedWords = new HashSet(Arrays.asList("abstract", - "continue", "for", "new", "switch", "assert", "default", "if", - "package", "synchronized", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", - "byte", "else", "import", "public", "throws", "case", "enum", - "instanceof", "return", "transient", "catch", "extends", "int", - "short", "try", "char", "final", "interface", "static", "void", - "class", "finally", "const", "super", "while")); - - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - languageSpecificPrimitives = new HashSet(Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object")); - instantiationTypes.put("array", "Array"); - - typeMapping = new HashMap(); - typeMapping.put("Array", "Array"); - typeMapping.put("array", "Array"); - typeMapping.put("List", "Array"); - typeMapping.put("boolean", "boolean"); - typeMapping.put("string", "string"); - typeMapping.put("int", "number"); - typeMapping.put("float", "number"); - typeMapping.put("number", "number"); - typeMapping.put("long", "number"); - typeMapping.put("short", "number"); - typeMapping.put("char", "string"); - typeMapping.put("double", "number"); - typeMapping.put("object", "any"); - typeMapping.put("integer", "number"); - typeMapping.put("Map", "any"); - typeMapping.put("DateTime", "Date"); - - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) - return name; - - // camelize the variable name - // pet_id => PetId - name = camelize(name, true); - - // for reserved word or word starting with number, append _ - if (reservedWords.contains(name) || name.matches("^\\d.*")) - name = escapeReservedWord(name); - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if (reservedWords.contains(name)) - throw new RuntimeException(name - + " (reserved word) cannot be used as a model name"); - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + ""; - } - return super.getTypeDeclaration(p); - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) - return type; - } else - type = swaggerType; - return type; - } } diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache new file mode 100644 index 00000000000..8e64db5af31 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache @@ -0,0 +1,291 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; +using System.IO; +using System.Web; +using System.Linq; +using System.Net; +using System.Text; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Extensions; + +namespace {{packageName}}.Client +{ + /// + /// API client is mainly responible for making the HTTP call to the API backend. + /// + public class ApiClient + { + private readonly Dictionary _defaultHeaderMap = new Dictionary(); + + /// + /// Initializes a new instance of the class. + /// + /// The base path. + public ApiClient(String basePath="{{basePath}}") + { + BasePath = basePath; + RestClient = new RestClient(BasePath); + } + + /// + /// Gets or sets the base path. + /// + /// The base path + public string BasePath { get; set; } + + /// + /// Gets or sets the RestClient. + /// + /// An instance of the RestClient + public RestClient RestClient { get; set; } + + /// + /// Gets the default header. + /// + public Dictionary DefaultHeader + { + get { return _defaultHeaderMap; } + } + + /// + /// Makes the HTTP request (Sync). + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// HTTP body (POST request). + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Authentication settings. + /// Object + public Object CallApi(String path, RestSharp.Method method, Dictionary queryParams, String postBody, + Dictionary headerParams, Dictionary formParams, + Dictionary fileParams, String[] authSettings) + { + + var request = new RestRequest(path, method); + + UpdateParamsForAuth(queryParams, headerParams, authSettings); + + // add default header, if any + foreach(var defaultHeader in _defaultHeaderMap) + request.AddHeader(defaultHeader.Key, defaultHeader.Value); + + // add header parameter, if any + foreach(var param in headerParams) + request.AddHeader(param.Key, param.Value); + + // add query parameter, if any + foreach(var param in queryParams) + request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost); + + // add form parameter, if any + foreach(var param in formParams) + request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost); + + // add file parameter, if any + foreach(var param in fileParams) + request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); + + if (postBody != null) // http body (model) parameter + request.AddParameter("application/json", postBody, ParameterType.RequestBody); + + return (Object)RestClient.Execute(request); + + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + public void AddDefaultHeader(string key, string value) + { + _defaultHeaderMap.Add(key, value); + } + + /// + /// Escape string (url-encoded). + /// + /// String to be escaped. + /// Escaped string. + public string EscapeString(string str) + { + return RestSharp.Contrib.HttpUtility.UrlEncode(str); + } + + /// + /// Create FileParameter based on Stream. + /// + /// Parameter name. + /// Input stream. + /// FileParameter. + public FileParameter ParameterToFile(string name, Stream stream) + { + if (stream is FileStream) + return FileParameter.Create(name, stream.ReadAsBytes(), Path.GetFileName(((FileStream)stream).Name)); + else + return FileParameter.Create(name, stream.ReadAsBytes(), "no_file_name_provided"); + } + + /// + /// If parameter is DateTime, output in ISO8601 format. + /// If parameter is a list of string, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// Formatted string. + public string ParameterToString(object obj) + { + if (obj is DateTime) + return ((DateTime)obj).ToString ("u"); + else if (obj is List) + return String.Join(",", (obj as List).ToArray()); + else + return Convert.ToString (obj); + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// HTTP body (e.g. string, JSON). + /// Object type. + /// Object representation of the JSON string. + public object Deserialize(string content, Type type, IList headers=null) + { + if (type == typeof(Object)) // return an object + { + return content; + } + + if (type == typeof(Stream)) + { + var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) + ? Path.GetTempPath() + : Configuration.TempFolderPath; + + var fileName = filePath + Guid.NewGuid(); + if (headers != null) + { + var regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$"); + var match = regex.Match(headers.ToString()); + if (match.Success) + fileName = filePath + match.Value.Replace("\"", "").Replace("'", ""); + } + File.WriteAllText(fileName, content); + return new FileStream(fileName, FileMode.Open); + + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(content, null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return ConvertType(content, type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(content, type); + } + catch (IOException e) + { + throw new ApiException(500, e.Message); + } + } + + /// + /// Serialize an object into JSON string. + /// + /// Object. + /// JSON string. + public string Serialize(object obj) + { + try + { + return obj != null ? JsonConvert.SerializeObject(obj) : null; + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + /// + /// Get the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix (string apiKeyIdentifier) + { + var apiKeyValue = ""; + Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); + var apiKeyPrefix = ""; + if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) + return apiKeyPrefix + " " + apiKeyValue; + else + return apiKeyValue; + } + + /// + /// Update parameters based on authentication. + /// + /// Query parameters. + /// Header parameters. + /// Authentication settings. + public void UpdateParamsForAuth(Dictionary queryParams, Dictionary headerParams, string[] authSettings) + { + if (authSettings == null || authSettings.Length == 0) + return; + + foreach (string auth in authSettings) + { + // determine which one to use + switch(auth) + { + {{#authMethods}} + case "{{name}}": + {{#isApiKey}}{{#isKeyInHeader}}headerParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}queryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}headerParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password);{{/isBasic}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + break; + {{/authMethods}} + default: + //TODO show warning about security definition not found + break; + } + } + } + + /// + /// Encode string in base64 format. + /// + /// String to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + var textByte = System.Text.Encoding.UTF8.GetBytes(text); + return System.Convert.ToBase64String(textByte); + } + + /// + /// Dynamically cast the object into target type. + /// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast + /// + /// Object to be casted + /// Target type + /// Casted object + public static Object ConvertType(Object source, Type dest) { + return Convert.ChangeType(source, dest); + } + + } +} diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiException.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiException.mustache new file mode 100644 index 00000000000..71d0243d729 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiException.mustache @@ -0,0 +1,48 @@ +using System; + +namespace {{packageName}}.Client { + /// + /// API Exception + /// + public class ApiException : Exception { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public Object ErrorContent { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The base path. + public ApiException() {} + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + public ApiException(int errorCode, string message, Object errorContent = null) : base(message) { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + } + + } + +} diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/Configuration.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/Configuration.mustache new file mode 100644 index 00000000000..67b07069e2f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/Configuration.mustache @@ -0,0 +1,99 @@ +using System; +using System.Reflection; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace {{packageName}}.Client +{ + /// + /// Represents a set of configuration settings + /// + public class Configuration + { + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "{{packageVersion}}"; + + /// + /// Gets or sets the default API client for making HTTP calls. + /// + /// The API client. + public static ApiClient DefaultApiClient = new ApiClient(); + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public static String Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public static String Password { get; set; } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public static Dictionary ApiKey = new Dictionary(); + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + public static Dictionary ApiKeyPrefix = new Dictionary(); + + private static string _tempFolderPath = Path.GetTempPath(); + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public static String TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (String.IsNullOrEmpty(value)) + { + _tempFolderPath = value; + return; + } + + // create the directory if it does not exist + if (!Directory.Exists(value)) + Directory.CreateDirectory(value); + + // check if the path contains directory separator at the end + if (value[value.Length - 1] == Path.DirectorySeparatorChar) + _tempFolderPath = value; + else + _tempFolderPath = value + Path.DirectorySeparatorChar; + } + } + + /// + /// Returns a string with essential information for debugging. + /// + public static String ToDebugReport() + { + String report = "C# SDK ({{packageName}}) Debug Report:\n"; + report += " OS: " + Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + Assembly + .GetExecutingAssembly() + .GetReferencedAssemblies() + .Where(x => x.Name == "System.Core").First().Version.ToString() + "\n"; + report += " Version of the API: {{version}}\n"; + report += " SDK Package Version: {{packageVersion}}\n"; + + return report; + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/README.md b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/README.md new file mode 100644 index 00000000000..5fe03fcb316 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/README.md @@ -0,0 +1,10 @@ +# Csharp-DotNet2 + +This generator creates C# code targeting the .Net 2.0 framework. The resulting DLLs can be used in places where .Net 2.0 is the maximum supported version, such as in the Unity3d. + +## Dependencies +- Mono compiler +- Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator. + + + diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api.mustache new file mode 100644 index 00000000000..2e51c913c30 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api.mustache @@ -0,0 +1,127 @@ +using System; +using System.IO; +using System.Collections.Generic; +using RestSharp; +using {{packageName}}.Client; +{{#hasImport}}using {{packageName}}.Model; +{{/hasImport}} + +namespace {{packageName}}.Api +{ + {{#operations}} + public interface I{{classname}} + { + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + {{#allParams}}/// {{description}} + {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/operation}} + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class {{classname}} : I{{classname}} + { + /// + /// Initializes a new instance of the class. + /// + /// an instance of ApiClient (optional) + /// + public {{classname}}(ApiClient apiClient = null) + { + if (apiClient == null) // use the default one in Configuration + this.ApiClient = Configuration.DefaultApiClient; + else + this.ApiClient = apiClient; + } + + /// + /// Initializes a new instance of the class. + /// + /// + public {{classname}}(String basePath) + { + this.ApiClient = new ApiClient(basePath); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + /// The base path + public void SetBasePath(String basePath) + { + this.ApiClient.BasePath = basePath; + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + /// The base path + public String GetBasePath(String basePath) + { + return this.ApiClient.BasePath; + } + + /// + /// Gets or sets the API client. + /// + /// An instance of the ApiClient + public ApiClient ApiClient {get; set;} + + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + {{#allParams}}/// {{description}} + {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + { + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); + {{/required}}{{/allParams}} + + var path = "{{path}}"; + path = path.Replace("{format}", "json"); + {{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", ApiClient.ParameterToString({{{paramName}}})); + {{/pathParams}} + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter + {{/queryParams}} + {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // header parameter + {{/headerParams}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} + {{/formParams}} + {{#bodyParam}}postBody = ApiClient.Serialize({{paramName}}); // http body (model) parameter + {{/bodyParam}} + + // authentication setting, if any + String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.ErrorMessage, response.ErrorMessage); + + {{#returnType}}return ({{{returnType}}}) ApiClient.Deserialize(response.Content, typeof({{{returnType}}}), response.Headers);{{/returnType}}{{^returnType}}return;{{/returnType}} + } + + {{/operation}} + } + {{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/compile-mono.sh.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/compile-mono.sh.mustache new file mode 100644 index 00000000000..73add75a69a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/compile-mono.sh.mustache @@ -0,0 +1,12 @@ +wget -nc https://nuget.org/nuget.exe; +mozroots --import --sync +mono nuget.exe install vendor/packages.config -o vendor; +mkdir -p bin; +mcs -sdk:2 -r:vendor/Newtonsoft.Json.7.0.1/lib/net20/Newtonsoft.Json.dll,\ +vendor/RestSharp.Net2.1.1.11/lib/net20/RestSharp.Net2.dll,\ +System.Runtime.Serialization.dll \ +-target:library \ +-out:bin/{{packageName}}.dll \ +-recurse:src/*.cs \ +-doc:bin/{{packageName}}.xml \ +-platform:anycpu \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/model.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/model.mustache new file mode 100644 index 00000000000..3e6e32320e7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/model.mustache @@ -0,0 +1,53 @@ +using System; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.Serialization; +using Newtonsoft.Json; + +{{#models}} +{{#model}} +namespace {{packageName}}.Model { + + /// + /// {{description}} + /// + [DataContract] + public class {{classname}}{{#parent}} : {{{parent}}}{{/parent}} { + {{#vars}} + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{#description}} + /// {{{description}}}{{/description}} + [DataMember(Name="{{baseName}}", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "{{baseName}}")] + public {{{datatype}}} {{name}} { get; set; } + + {{/vars}} + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + {{#vars}} + sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{/vars}} + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public {{#parent}} new {{/parent}}string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} +{{/model}} +{{/models}} +} diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/packages.config.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/packages.config.mustache new file mode 100644 index 00000000000..7b9cf186303 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/packages.config.mustache @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index fb4351d444d..79b44594816 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -356,7 +356,7 @@ public class ApiClient { } else if(String.class.equals(cls)) { if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) - return json.substring(1, json.length() - 2); + return json.substring(1, json.length() - 1); else return json; } diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 39b71dbff9a..c48c0503f5c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -23,22 +23,22 @@ import java.util.HashMap; {{#operations}} public class {{classname}} { - private ApiClient apiClient; + private ApiClient {{localVariablePrefix}}apiClient; public {{classname}}() { this(Configuration.getDefaultApiClient()); } public {{classname}}(ApiClient apiClient) { - this.apiClient = apiClient; + this.{{localVariablePrefix}}apiClient = apiClient; } public ApiClient getApiClient() { - return apiClient; + return {{localVariablePrefix}}apiClient; } public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; + this.{{localVariablePrefix}}apiClient = apiClient; } {{#operation}} @@ -49,7 +49,7 @@ public class {{classname}} { {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == null) { @@ -58,61 +58,61 @@ public class {{classname}} { {{/required}}{{/allParams}} // create path and map variables - String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} - .replaceAll("\\{" + "{{baseName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + String {{localVariablePrefix}}path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} + .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + List {{localVariablePrefix}}queryParams = new ArrayList(); + Map {{localVariablePrefix}}headerParams = new HashMap(); + Map {{localVariablePrefix}}formParams = new HashMap(); {{#queryParams}} - queryParams.addAll(apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); {{/queryParams}} {{#headerParams}}if ({{paramName}} != null) - headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); + {{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}})); {{/headerParams}} - final String[] accepts = { + final String[] {{localVariablePrefix}}accepts = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }; - final String accept = apiClient.selectHeaderAccept(accepts); + final String {{localVariablePrefix}}accept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}accepts); - final String[] contentTypes = { + final String[] {{localVariablePrefix}}contentTypes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); + final String {{localVariablePrefix}}contentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}contentTypes); - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); + if({{localVariablePrefix}}contentType.startsWith("multipart/form-data")) { + boolean {{localVariablePrefix}}hasFields = false; + FormDataMultiPart {{localVariablePrefix}}mp = new FormDataMultiPart(); {{#formParams}}{{#notFile}} if ({{paramName}} != null) { - hasFields = true; - mp.field("{{baseName}}", apiClient.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); + {{localVariablePrefix}}hasFields = true; + {{localVariablePrefix}}mp.field("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); } {{/notFile}}{{#isFile}} if ({{paramName}} != null) { - hasFields = true; - mp.field("{{baseName}}", {{paramName}}.getName()); - mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)); + {{localVariablePrefix}}hasFields = true; + {{localVariablePrefix}}mp.field("{{baseName}}", {{paramName}}.getName()); + {{localVariablePrefix}}mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)); } {{/isFile}}{{/formParams}} - if(hasFields) - postBody = mp; + if({{localVariablePrefix}}hasFields) + {{localVariablePrefix}}postBody = {{localVariablePrefix}}mp; } else { {{#formParams}}{{#notFile}}if ({{paramName}} != null) - formParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));{{/notFile}} + {{localVariablePrefix}}formParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/notFile}} {{/formParams}} } try { - String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - String response = apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return {{#returnType}}({{{returnType}}}) apiClient.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; + String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + String {{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames); + if({{localVariablePrefix}}response != null){ + return {{#returnType}}({{{returnType}}}) {{localVariablePrefix}}apiClient.deserialize({{localVariablePrefix}}response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; } else { return {{#returnType}}null{{/returnType}}; diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/README.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/README.mustache new file mode 100644 index 00000000000..c1309670c5a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/README.mustache @@ -0,0 +1,8 @@ +# Swagger Inflector + +Run with + +``` +mvn package jetty:run +`` + diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache new file mode 100644 index 00000000000..5f5b5b1df9a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache @@ -0,0 +1,27 @@ +package {{invokerPackage}}; + +import io.swagger.inflector.models.RequestContext; +import io.swagger.inflector.models.ResponseContext; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import java.io.File; +import java.util.List; + +import {{modelPackage}}.*; + +{{#imports}}import {{import}}; +{{/imports}} + +{{#operations}} +public class {{classname}} { + +{{#operation}} + public ResponseContext {{nickname}}(RequestContext request {{#allParams}},{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{/allParams}}) + { + return new ResponseContext().status(Status.INTERNAL_SERVER_ERROR).entity( "Not implemented" ); + } +{{/operation}} +} +{{/operations}} + diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/bodyParams.mustache new file mode 100644 index 00000000000..c7d1abfe527 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/formParams.mustache new file mode 100644 index 00000000000..e44ab167e8f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/headerParams.mustache new file mode 100644 index 00000000000..bd03573d196 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}{{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache new file mode 100644 index 00000000000..d9d02ea93a8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache @@ -0,0 +1,6 @@ +controllerPackage: {{invokerPackage}} +modelPackage: {{modelPackage}} +swaggerUrl: ./src/main/swagger/swagger.json +modelMappings: + {{#models}}{{#model}}{{classname}} : {{modelPackage}}.{{classname}}{{/model}} + {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache new file mode 100644 index 00000000000..300d5e61dd9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache @@ -0,0 +1,51 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@ApiModel(description = "{{{description}}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { + {{#vars}}{{#isEnum}} + public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} + }; + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + @JsonProperty("{{name}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); + {{/vars}}sb.append("}\n"); + return sb.toString(); + } +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pathParams.mustache new file mode 100644 index 00000000000..6829cf8c7a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache new file mode 100644 index 00000000000..09477f95052 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache @@ -0,0 +1,174 @@ + + + org.sonatype.oss + oss-parent + 5 + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + 2.2.0 + + + + install + target + ${project.artifactId}-${project.version} + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + **/logback.xml + + + + development + ${project.url} + ${project.version} + io.swagger + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + . + + inflector.yaml + src/main/swagger/swagger.yaml + + 1 + + / + + + 8080 + 60000 + + + + + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + 2.4.0 + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + + + org.glassfish.jersey.containers + jersey-container-servlet-core + ${jersey2-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey2-version} + + + org.glassfish.jersey.core + jersey-client + ${jersey2-version} + + + javax.servlet + servlet-api + ${servlet-api-version} + provided + + + + ch.qos.logback + logback-classic + ${logback-version} + + + ch.qos.logback + logback-core + ${logback-version} + + + org.slf4j + slf4j-ext + ${slf4j-version} + + + org.slf4j + slf4j-api + ${slf4j-version} + + + + + commons-lang + commons-lang + ${commons-lang-version} + + + + + io.swagger + swagger-inflector + 1.0.0-SNAPSHOT + + + + + 1.0.0 + 1.5.0 + 1.0.8 + 2.4.2 + 2.2 + 1.2 + 9.2.9.v20150224 + 2.6 + 2.5 + 2.4 + 2.4 + 1.1 + 1.0.1 + 4.8.2 + 1.6.3 + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/queryParams.mustache new file mode 100644 index 00000000000..ff79730471d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/web.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/web.mustache new file mode 100644 index 00000000000..34a2eea6bcf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/web.mustache @@ -0,0 +1,24 @@ + + + + swagger-inflector + org.glassfish.jersey.servlet.ServletContainer + + javax.ws.rs.Application + io.swagger.inflector.SwaggerInflector + + 1 + + + swagger-inflector + /* + + + CORSFilter + io.swagger.inflector.utils.CORSFilter + + + CORSFilter + /* + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 29c7ed0f729..e98ac462230 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -1,8 +1,10 @@ io.swagger.codegen.languages.AndroidClientCodegen io.swagger.codegen.languages.AsyncScalaClientCodegen io.swagger.codegen.languages.CSharpClientCodegen +io.swagger.codegen.languages.FlashClientCodegen io.swagger.codegen.languages.JavaClientCodegen io.swagger.codegen.languages.JaxRSServerCodegen +io.swagger.codegen.languages.JavaInflectorServerCodegen io.swagger.codegen.languages.NodeJSServerCodegen io.swagger.codegen.languages.ObjcClientCodegen io.swagger.codegen.languages.PerlClientCodegen @@ -26,3 +28,4 @@ io.swagger.codegen.languages.TizenClientCodegen io.swagger.codegen.languages.TypeScriptAngularClientCodegen io.swagger.codegen.languages.TypeScriptNodeClientCodegen io.swagger.codegen.languages.AkkaScalaClientCodegen +io.swagger.codegen.languages.CsharpDotNet2ClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index bd5eaaef87a..427d847663b 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -6,11 +6,11 @@ module {{package}} { 'use strict'; - {{#description}} +{{#description}} /** * {{&description}} */ - {{/description}} +{{/description}} export class {{classname}} { private basePath = '{{contextPath}}'; @@ -21,24 +21,37 @@ module {{package}} { this.basePath = basePath; } } - {{#operation}} +{{#operation}} + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { var path = this.basePath + '{{path}}'; - {{#pathParams}} + +{{#pathParams}} path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); - {{/pathParams}} + +{{/pathParams}} var queryParameters: any = {}; var headerParams: any = {}; - {{#allParams}}{{#required}} + +{{#allParams}} +{{#required}} // verify required parameter '{{paramName}}' is set if (!{{paramName}}) { throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); } - {{/required}}{{/allParams}} - {{#queryParams}}if ({{paramName}} !== undefined) { + +{{/required}} +{{/allParams}} +{{#queryParams}} + if ({{paramName}} !== undefined) { queryParameters['{{paramName}}'] = {{paramName}}; - }{{/queryParams}} - {{#headerParams}}headerParams['{{paramName}}'] = {{paramName}};{{/headerParams}} + } + +{{/queryParams}} +{{#headerParams}} + headerParams['{{paramName}}'] = {{paramName}}; + +{{/headerParams}} var httpRequestParams: any = { method: '{{httpMethod}}', url: path, @@ -59,7 +72,7 @@ module {{package}} { return this.$http(httpRequestParams); } - {{/operation}} +{{/operation}} } } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index debeed69515..f8d4577ee7a 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -1,73 +1,245 @@ +import request = require('request'); +import promise = require('bluebird'); +import http = require('http'); + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + /* tslint:disable:no-unused-variable */ -{{#operations}} +{{#models}} +{{#model}} +{{#description}} +/** +* {{{description}}} +*/ +{{/description}} +export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ +{{#vars}} {{#description}} /** - * {{&description}} + * {{{description}}} */ +{{/description}} + {{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; +{{/vars}} +} + +{{#hasEnums}} +export module {{classname}} { +{{#vars}} +{{#isEnum}} + export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} + {{.}} = '{{.}}',{{/values}}{{/allowableValues}} + } +{{/isEnum}} +{{/vars}} +} +{{/hasEnums}} +{{/model}} +{{/models}} + +interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: request.Options): void; +} + +class HttpBasicAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + requestOptions.auth = { + username: this.username, password: this.password + } + } +} + +class ApiKeyAuth implements Authentication { + public apiKey: string; + + constructor(private location: string, private paramName: string) { + } + + applyToRequest(requestOptions: request.Options): void { + if (this.location == "query") { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + } +} + +class OAuth implements Authentication { + applyToRequest(requestOptions: request.Options): void { + // TODO: support oauth + } +} + +class VoidAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + // Do nothing + } +} + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#description}} +/** +* {{&description}} +*/ {{/description}} export class {{classname}} { private basePath = '{{contextPath}}'; - - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; - } + public authentications = { + 'default': new VoidAuth(), +{{#authMethods}} +{{#isBasic}} + '{{name}}': new HttpBasicAuth(), +{{/isBasic}} +{{#isApiKey}} + '{{name}}': new ApiKeyAuth({{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{^isKeyInHeader}}'query'{{/isKeyInHeader}}, '{{keyParamName}}'), +{{/isApiKey}} +{{#isOAuth}} + '{{name}}': new OAuth(), +{{/isOAuth}} +{{/authMethods}} } - {{#operation}} - public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { - var path = this.url + this.basePath + '{{path}}'; - - {{#pathParams}} - path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); - {{/pathParams}} - - var queryParameters: any = {}; - var headerParams: any = {}; - - {{#allParams}}{{#required}} - // verify required parameter '{{paramName}}' is set - if (!{{paramName}}) { - throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); - } - {{/required}}{{/allParams}} - - {{#queryParams}}if ({{paramName}} !== undefined) { - queryParameters['{{paramName}}'] = {{paramName}}; - } - {{/queryParams}} - - {{#headerParams}}headerParams['{{paramName}}'] = {{paramName}}; - {{/headerParams}} - - var deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); - - request({ - method: '{{httpMethod}}', - qs: queryParameters, - uri: path, - json: true, - {{#bodyParam}}body: {{paramName}}, - {{/bodyParam}} - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); + constructor(url: string, basePath?: string); +{{#authMethods}} +{{#isBasic}} + constructor(url: string, username: string, password: string, basePath?: string); +{{/isBasic}} +{{/authMethods}} + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { +{{#authMethods}} +{{#isBasic}} + this.username = basePathOrUsername; + this.password = password +{{/isBasic}} +{{/authMethods}} + if (basePath) { + this.basePath = basePath; + } } else { - deferred.reject({ response: response, body: body }); + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } } - } - }); + } +{{#authMethods}} +{{#isBasic}} - return deferred.promise; - } + set username(username: string) { + this.authentications.{{name}}.username = username; + } - {{/operation}} + set password(password: string) { + this.authentications.{{name}}.password = password; + } +{{/isBasic}} +{{#isApiKey}} + + set apiKey(key: string) { + this.authentications.{{name}}.apiKey = key; + } +{{/isApiKey}} +{{#isOAuth}} +{{/isOAuth}} +{{/authMethods}} +{{#operation}} + + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { + var path = this.url + this.basePath + '{{path}}'; + +{{#pathParams}} + path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); + +{{/pathParams}} + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + +{{#allParams}} +{{#required}} + // verify required parameter '{{paramName}}' is set + if (!{{paramName}}) { + throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); + } + +{{/required}} +{{/allParams}} +{{#queryParams}} + if ({{paramName}} !== undefined) { + queryParameters['{{paramName}}'] = {{paramName}}; + } + +{{/queryParams}} +{{#headerParams}} + headerParams['{{paramName}}'] = {{paramName}}; + +{{/headerParams}} + var useFormData = false; + +{{#formParams}} + if ({{paramName}} !== undefined) { + formParams['{{paramName}}'] = {{paramName}}; + } +{{#isFile}} + useFormData = true; +{{/isFile}} + +{{/formParams}} + var deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); + + var requestOptions: request.Options = { + method: '{{httpMethod}}', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, +{{#bodyParam}} + body: {{paramName}}, +{{/bodyParam}} + } + +{{#authMethods}} + this.authentications.{{name}}.applyToRequest(requestOptions); + +{{/authMethods}} + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +{{/operation}} } {{/operations}} +{{/apis}} +{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache deleted file mode 100644 index 55c8997e1bc..00000000000 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache +++ /dev/null @@ -1,33 +0,0 @@ -{{#models}} -{{#model}} -{{#description}} -/** - * {{{description}}} - */ -{{/description}} -export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ -{{#vars}} - -{{#description}} - /** - * {{{description}}} - */ -{{/description}} - {{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; -{{/vars}} -} - -{{#hasEnums}} -export module {{classname}} { -{{#vars}} -{{#isEnum}} - - export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} - {{.}} = '{{.}}',{{/values}}{{/allowableValues}} - } -{{/isEnum}} -{{/vars}} -} -{{/hasEnums}} -{{/model}} -{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache index 5aabd2458e8..ac24335df18 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache @@ -216,7 +216,7 @@ public class ApiInvoker { } else if(String.class.equals(cls)) { if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) - return json.substring(1, json.length() - 2); + return json.substring(1, json.length() - 1); else return json; } diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index c3757603cce..c93537a740d 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -154,7 +154,7 @@ namespace {{packageName}}.Client /// Escaped string. public string EscapeString(string str) { - return HttpUtility.UrlEncode(str); + return RestSharp.Contrib.HttpUtility.UrlEncode(str); } /// @@ -235,7 +235,7 @@ namespace {{packageName}}.Client { return JsonConvert.DeserializeObject(content, type); } - catch (IOException e) + catch (Exception e) { throw new ApiException(500, e.Message); } diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index e6215d3e21a..24c65f85ba8 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -104,11 +104,11 @@ namespace {{packageName}}.Api String postBody = null; pathParams.Add("format", "json"); - {{#pathParams}} if ({{paramName}} != null) pathParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // path parameter + {{#pathParams}}if ({{paramName}} != null) pathParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // path parameter {{/pathParams}} - {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter + {{#queryParams}}if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter {{/queryParams}} - {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // header parameter + {{#headerParams}}if ({{paramName}} != null) headerParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // header parameter {{/headerParams}} {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} @@ -150,11 +150,11 @@ namespace {{packageName}}.Api String postBody = null; pathParams.Add("format", "json"); - {{#pathParams}} if ({{paramName}} != null) pathParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // path parameter + {{#pathParams}}if ({{paramName}} != null) pathParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // path parameter {{/pathParams}} - {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter + {{#queryParams}}if ({{paramName}} != null) queryParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // query parameter {{/queryParams}} - {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // header parameter + {{#headerParams}}if ({{paramName}} != null) headerParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // header parameter {{/headerParams}} {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} diff --git a/modules/swagger-codegen/src/main/resources/flash/api.mustache b/modules/swagger-codegen/src/main/resources/flash/api.mustache index b1f11e92438..7fa8cb03d0a 100644 --- a/modules/swagger-codegen/src/main/resources/flash/api.mustache +++ b/modules/swagger-codegen/src/main/resources/flash/api.mustache @@ -56,7 +56,7 @@ public class {{classname}} extends SwaggerApi { {{#headerParams}}headerParams["{{paramName}}"] = toPathValue({{paramName}}); {{/headerParams}} - var token:AsyncToken = getApiInvoker().invokeAPI(path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{bodyParam}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams); + var token:AsyncToken = getApiInvoker().invokeAPI(path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams); var requestId: String = getUniqueId(); @@ -70,4 +70,4 @@ public class {{classname}} extends SwaggerApi { {{/operation}} } {{/operations}} -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/flash/model.mustache b/modules/swagger-codegen/src/main/resources/flash/model.mustache index c3369514e80..a365a99f2cf 100644 --- a/modules/swagger-codegen/src/main/resources/flash/model.mustache +++ b/modules/swagger-codegen/src/main/resources/flash/model.mustache @@ -7,34 +7,30 @@ package {{package}} { {{#model}} [XmlRootNode(name="{{classname}}")] public class {{classname}} { - {{#vars}} - - {{#description}}/* {{description}} */ - {{/description}} - - {{#isList}} + {{#vars}} + {{#description}}/* {{description}} */ + {{/description}} + {{#isContainer}} // This declaration below of _{{name}}_obj_class is to force flash compiler to include this class private var _{{name}}_obj_class: {{baseType}} = null; - [XmlElementWrapper(name="{{name}}")] - [XmlElements(name="{{nameSingular}}", type="{{baseType}}")] - {{/isList}} - {{#isNotContainer}}[XmlElement(name="{{name}}")] - {{/isNotContainer}} + [XmlElementWrapper(name="{{baseName}}")] + [XmlElements(name="{{name}}", type="{{baseType}}")] + {{/isContainer}} + {{^isContainer}}[XmlElement(name="{{baseName}}")] + {{/isContainer}} public var {{name}}: {{{datatype}}} = {{{defaultValue}}}; - {{/vars}} - public function toString(): String { - var str: String = "{{classname}}: "; - {{#vars}} - str += " ({{name}}: " + {{name}} + ")"; - {{/vars}} - return str; - } - + public function toString(): String { + var str: String = "{{classname}}: "; + {{#vars}} + str += " ({{name}}: " + {{name}} + ")"; + {{/vars}} + return str; + } } {{/model}} - {{/models}} +{{/models}} } diff --git a/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache index e4254fd0aa4..59940f08b15 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache @@ -12,8 +12,9 @@ "paths": { {{#apis}} {{#operations}} - {{#operation}} + {{#operationsByPath}} "{{{path}}}": { + {{#operation}} "{{httpMethod}}": { "summary": "{{summary}}", "description":"{{notes}}", @@ -29,9 +30,10 @@ {{#hasMore}},{{/hasMore}} {{/responses}} } - } + } {{#hasMore}},{{/hasMore}} + {{/operation}} } {{#hasMore}},{{/hasMore}} - {{/operation}} + {{/operationsByPath}} {{#hasMore}},{{/hasMore}} {{/operations}} {{/apis}} diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 569eade5db5..a7d290022f6 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -1,7 +1,5 @@ #import "{{classPrefix}}ApiClient.h" -@implementation {{classPrefix}}ApiClient - NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; static long requestId = 0; @@ -9,41 +7,75 @@ static bool offlineState = false; static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; -static NSOperationQueue* sharedQueue; static void (^reachabilityChangeBlock)(int); +@implementation {{classPrefix}}ApiClient + +- (instancetype)init { + NSString *baseUrl = [[{{classPrefix}}Configuration sharedConfig] host]; + return [self initWithBaseURL:[NSURL URLWithString:baseUrl]]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + self = [super initWithBaseURL:url]; + if (self) { + self.requestSerializer = [AFJSONRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + // configure reachability + [self configureCacheReachibility]; + } + return self; +} + ++ (void)initialize { + if (self == [{{classPrefix}}ApiClient class]) { + queuedRequests = [[NSMutableSet alloc] init]; + // initialize URL cache + [self configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; + } +} + +#pragma mark - Setter Methods + ++ (void) setOfflineState:(BOOL) state { + offlineState = state; +} + ++ (void) setCacheEnabled:(BOOL)enabled { + cacheEnabled = enabled; +} + +- (void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey { + [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; +} + #pragma mark - Log Methods - (void)logResponse:(AFHTTPRequestOperation *)operation forRequest:(NSURLRequest *)request error:(NSError*)error { {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; - + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] Request body \n~BEGIN~\n %@\n~END~\n"\ "[DEBUG] HTTP Response body \n~BEGIN~\n %@\n~END~\n", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], operation.responseString]; - + if (config.loggingFileHanlder) { [config.loggingFileHanlder seekToEndOfFile]; [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; } - + NSLog(@"%@", message); } #pragma mark - Cache Methods -+ (void) setCacheEnabled:(BOOL)enabled { - cacheEnabled = enabled; -} - +(void)clearCache { [[NSURLCache sharedURLCache] removeAllCachedResponses]; } -#pragma mark - - +(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize diskSize: (unsigned long) diskSize { NSAssert(memorySize > 0, @"invalid in-memory cache size"); @@ -58,43 +90,7 @@ static void (^reachabilityChangeBlock)(int); [NSURLCache setSharedURLCache:cache]; } -+(NSOperationQueue*) sharedQueue { - return sharedQueue; -} - -+({{classPrefix}}ApiClient *)sharedClientFromPool:(NSString *)baseUrl { - static NSMutableDictionary *_pool = nil; - if (queuedRequests == nil) { - queuedRequests = [[NSMutableSet alloc]init]; - } - if(_pool == nil) { - // setup static vars - // create queue - sharedQueue = [[NSOperationQueue alloc] init]; - - // create pool - _pool = [[NSMutableDictionary alloc] init]; - - // initialize URL cache - [{{classPrefix}}ApiClient configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; - - // configure reachability - [{{classPrefix}}ApiClient configureCacheReachibilityForHost:baseUrl]; - } - - @synchronized(self) { - {{classPrefix}}ApiClient * client = [_pool objectForKey:baseUrl]; - if (client == nil) { - client = [[{{classPrefix}}ApiClient alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]]; - [_pool setValue:client forKey:baseUrl ]; - if([[{{classPrefix}}Configuration sharedConfig] debug]) - NSLog(@"new client for path %@", baseUrl); - } - if([[{{classPrefix}}Configuration sharedConfig] debug]) - NSLog(@"returning client for path %@", baseUrl); - return client; - } -} +#pragma mark - Utility Methods /* * Detect `Accept` from accepts @@ -104,13 +100,13 @@ static void (^reachabilityChangeBlock)(int); if (accepts == nil || [accepts count] == 0) { return @""; } - + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; [accepts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [lowerAccepts addObject:[obj lowercaseString]]; }]; - + if ([lowerAccepts containsObject:@"application/json"]) { return @"application/json"; } @@ -127,7 +123,7 @@ static void (^reachabilityChangeBlock)(int); if (contentTypes == nil || [contentTypes count] == 0) { return @"application/json"; } - + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [lowerContentTypes addObject:[obj lowercaseString]]; @@ -141,11 +137,23 @@ static void (^reachabilityChangeBlock)(int); } } --(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey { - [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; ++ (NSString*)escape:(id)unescaped { + if([unescaped isKindOfClass:[NSString class]]){ + return (NSString *)CFBridgingRelease + (CFURLCreateStringByAddingPercentEscapes( + NULL, + (__bridge CFStringRef) unescaped, + NULL, + (CFStringRef)@"!*'();:@&=+$,/?%#[]", + kCFStringEncodingUTF8)); + } + else { + return [NSString stringWithFormat:@"%@", unescaped]; + } } +#pragma mark - Request Methods + +(unsigned long)requestQueueSize { return [queuedRequests count]; } @@ -171,46 +179,28 @@ static void (^reachabilityChangeBlock)(int); [queuedRequests removeObject:requestId]; } -+(NSString*) escape:(id)unescaped { - if([unescaped isKindOfClass:[NSString class]]){ - return (NSString *)CFBridgingRelease - (CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); - } - else { - return [NSString stringWithFormat:@"%@", unescaped]; - } -} - -(Boolean) executeRequestWithId:(NSNumber*) requestId { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - if([obj intValue] == [requestId intValue]) - return TRUE; - else return FALSE; + if([obj intValue] == [requestId intValue]) { + return YES; + } + else { + return NO; + } }]; if(matchingItems.count == 1) { if([[{{classPrefix}}Configuration sharedConfig] debug]) NSLog(@"removing request id %@", requestId); [queuedRequests removeObject:requestId]; - return true; + return YES; + } + else { + return NO; } - else - return false; } --(id)initWithBaseURL:(NSURL *)url { - self = [super initWithBaseURL:url]; - self.requestSerializer = [AFJSONRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - if (!self) - return nil; - return self; -} +#pragma mark - Reachability Methods +(AFNetworkReachabilityStatus) getReachabilityStatus { return reachabilityStatus; @@ -220,12 +210,8 @@ static void (^reachabilityChangeBlock)(int); reachabilityChangeBlock = changeBlock; } -+(void) setOfflineState:(BOOL) state { - offlineState = state; -} - -+(void) configureCacheReachibilityForHost:(NSString*)host { - [[{{classPrefix}}ApiClient sharedClientFromPool:host].reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { +- (void) configureCacheReachibility { + [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { reachabilityStatus = status; switch (status) { case AFNetworkReachabilityStatusUnknown: @@ -254,16 +240,352 @@ static void (^reachabilityChangeBlock)(int); default: break; } + // call the reachability block, if configured if(reachabilityChangeBlock != nil) { reachabilityChangeBlock(status); } }]; - [[{{classPrefix}}ApiClient sharedClientFromPool:host].reachabilityManager startMonitoring]; + + [self.reachabilityManager startMonitoring]; } --(NSString*) pathWithQueryParamsToString:(NSString*) path - queryParams:(NSDictionary*) queryParams { +#pragma mark - Deserialize methods + +- (id) deserialize:(id) data class:(NSString *) class { + NSRegularExpression *regexp = nil; + NSTextCheckingResult *match = nil; + NSMutableArray *resultArray = nil; + NSMutableDictionary *resultDict = nil; + NSString *innerType = nil; + + // return nil if data is nil or class is nil + if (!data || !class) { + return nil; + } + + // remove "*" from class, if ends with "*" + if ([class hasSuffix:@"*"]) { + class = [class substringToIndex:[class length] - 1]; + } + + // pure object + if ([class isEqualToString:@"NSObject"]) { + return [[NSObject alloc] init]; + } + + // list of models + NSString *arrayOfModelsPat = @"NSArray<(.+)>"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + innerType = [class substringWithRange:[match rangeAtIndex:1]]; + + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:innerType]]; + } + ]; + + return resultArray; + } + + // list of primitives + NSString *arrayOfPrimitivesPat = @"NSArray\\* /\\* (.+) \\*/"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + innerType = [class substringWithRange:[match rangeAtIndex:1]]; + + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:innerType]]; + }]; + + return resultArray; + } + + // map + NSString *dictPat = @"NSDictionary\\* /\\* (.+?), (.+) \\*/"; + regexp = [NSRegularExpression regularExpressionWithPattern:dictPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; + + resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; + }]; + + return resultDict; + } + + // primitives + NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; + + if ([primitiveTypes containsObject:class]) { + if ([class isEqualToString:@"NSString"]) { + return [NSString stringWithString:data]; + } + else if ([class isEqualToString:@"NSDate"]) { + return [NSDate dateWithISO8601String:data]; + } + else if ([class isEqualToString:@"NSNumber"]) { + // NSNumber from NSNumber + if ([data isKindOfClass:[NSNumber class]]) { + return data; + } + else if ([data isKindOfClass:[NSString class]]) { + // NSNumber (NSCFBoolean) from NSString + if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { + return [NSNumber numberWithBool:[data boolValue]]; + // NSNumber from NSString + } else { + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + formatter.numberStyle = NSNumberFormatterDecimalStyle; + return [formatter numberFromString:data]; + } + } + } + } + + // model + Class ModelClass = NSClassFromString(class); + if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { + return [[ModelClass alloc] initWithDictionary:data error:nil]; + } + + return nil; +} + +#pragma mark - Operation Methods + +- (void) operationWithCompletionBlock: (NSURLRequest *)request + requestId: (NSNumber *) requestId + completionBlock: (void (^)(id, NSError *))completionBlock { + AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request + success:^(AFHTTPRequestOperation *operation, id response) { + if([self executeRequestWithId:requestId]) { + if([[{{classPrefix}}Configuration sharedConfig] debug]) { + [self logResponse:operation forRequest:request error:nil]; + } + completionBlock(response, nil); + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if([self executeRequestWithId:requestId]) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if(operation.responseObject) { + // Add in the (parsed) response body. + userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + + if([[{{classPrefix}}Configuration sharedConfig] debug]) + [self logResponse:nil forRequest:request error:augmentedError]; + completionBlock(nil, augmentedError); + } + }]; + + [self.operationQueue addOperation:op]; +} + +- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request + requestId: (NSNumber *) requestId + completionBlock: (void (^)(id, NSError *))completionBlock { + AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request + success:^(AFHTTPRequestOperation *operation, id responseObject) { + {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + NSString *directory = nil; + if (config.tempFolderPath) { + directory = config.tempFolderPath; + } + else { + directory = NSTemporaryDirectory(); + } + + NSDictionary *headers = operation.response.allHeaderFields; + NSString *filename = nil; + if ([headers objectForKey:@"Content-Disposition"]) { + + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; + } + else { + filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; + + [operation.responseData writeToURL:file atomically:YES]; + completionBlock(file, nil); + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + + if ([self executeRequestWithId:requestId]) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (operation.responseObject) { + userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; + } + + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + + if ([[{{classPrefix}}Configuration sharedConfig] debug]) { + [self logResponse:nil forRequest:request error:augmentedError]; + } + + completionBlock(nil, augmentedError); + } + }]; + + [self.operationQueue addOperation:op]; +} + +#pragma mark - Perform Request Methods + +-(NSNumber*) requestWithCompletionBlock: (NSString*) path + method: (NSString*) method + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock { + // setting request serializer + if ([requestContentType isEqualToString:@"application/json"]) { + self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"multipart/form-data"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else { + NSAssert(false, @"unsupport request type %@", requestContentType); + } + + // setting response serializer + if ([responseContentType isEqualToString:@"application/json"]) { + self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; + } + else { + self.responseSerializer = [AFHTTPResponseSerializer serializer]; + } + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + + NSMutableURLRequest * request = nil; + + NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; + if ([pathWithQueryParams hasPrefix:@"/"]) { + pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; + } + + NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + if (files.count > 0) { + request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" + URLString:urlString + parameters:nil + constructingBodyWithBlock:^(id formData) { + [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSData *data = [obj dataUsingEncoding:NSUTF8StringEncoding]; + [formData appendPartWithFormData:data name:key]; + }]; + [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSURL *filePath = (NSURL *)obj; + [formData appendPartWithFileURL:filePath name:key error:nil]; + }]; + } error:nil]; + } + else { + if (formParams) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:formParams + error:nil]; + } + if (body) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:body + error:nil]; + } + } + + BOOL hasHeaderParams = false; + if(headerParams != nil && [headerParams count] > 0) { + hasHeaderParams = true; + } + if(offlineState) { + NSLog(@"%@ cache forced", path); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + NSLog(@"%@ cache enabled", path); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + NSLog(@"%@ cache disabled", path); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + if(hasHeaderParams){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + + + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; + + NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; + if ([responseType isEqualToString:@"NSURL*"]) { + [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + completionBlock(data, error); + }]; + } + else { + [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + completionBlock([self deserialize:data class:responseType], error); + }]; + } + return requestId; +} + +#pragma mark - + +- (NSString*) pathWithQueryParamsToString:(NSString*) path + queryParams:(NSDictionary*) queryParams { NSString * separator = nil; int counter = 0; @@ -323,18 +645,18 @@ static void (^reachabilityChangeBlock)(int); - (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers queryParams:(NSDictionary *__autoreleasing *)querys WithAuthSettings:(NSArray *)authSettings { - + if (!authSettings || [authSettings count] == 0) { return; } - + NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - + {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; for (NSString *auth in authSettings) { NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; - + if (authSetting) { if ([authSetting[@"in"] isEqualToString:@"header"]) { [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; @@ -344,338 +666,9 @@ static void (^reachabilityChangeBlock)(int); } } } - + *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -#pragma mark - Deserialize methods - -- (id) deserialize:(id) data class:(NSString *) class { - NSRegularExpression *regexp = nil; - NSTextCheckingResult *match = nil; - NSMutableArray *resultArray = nil; - NSMutableDictionary *resultDict = nil; - - // return nil if data is nil or class is nil - if (!data || !class) { - return nil; - } - - // remove "*" from class, if ends with "*" - if ([class hasSuffix:@"*"]) { - class = [class substringToIndex:[class length] - 1]; - } - - // pure object - if ([class isEqualToString:@"NSObject"]) { - return [[NSObject alloc] init]; - } - - // list of models - NSString *arrayOfModelsPat = @"NSArray<(.+)>"; - regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - NSString *innerType = [class substringWithRange:[match rangeAtIndex:1]]; - - resultArray = [NSMutableArray arrayWithCapacity:[data count]]; - [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [resultArray addObject:[self deserialize:obj class:innerType]]; - } - ]; - - return resultArray; - } - - // list of primitives - NSString *arrayOfPrimitivesPet = @"NSArray"; - regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPet - options:NSRegularExpressionCaseInsensitive - error:nil]; - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - resultArray = [NSMutableArray arrayWithCapacity:[data count]]; - [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [resultArray addObject:[self deserialize:obj class:NSStringFromClass([obj class])]]; - }]; - - return resultArray; - } - - // map - NSString *dictPat = @"NSDictionary\\* /\\* (.+), (.+) \\*/"; - regexp = [NSRegularExpression regularExpressionWithPattern:dictPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; - - resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; - [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; - }]; - - return resultDict; - } - - // primitives - NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"BOOL", @"NSNumber"]; - - if ([primitiveTypes containsObject:class]) { - if ([class isEqualToString:@"NSString"]) { - return [NSString stringWithString:data]; - } - else if ([class isEqualToString:@"NSDate"]) { - return [NSDate dateWithISO8601String:data]; - } - else if ([class isEqualToString:@"BOOL"]) { - // Returns YES on encountering one of "Y", "y", "T", "t", or a - // digit 1-9—the method ignores any trailing characters - // NSString => BOOL => NSNumber - return [NSNumber numberWithBool:[data boolValue]]; - } - else if ([class isEqualToString:@"NSNumber"]) { - // NSNumber from NSNumber - if ([data isKindOfClass:[NSNumber class]]) { - return data; - } - // NSNumber from NSString - else { - NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; - formatter.numberStyle = NSNumberFormatterDecimalStyle; - return [formatter numberFromString:data]; - } - } - } - - // model - Class ModelClass = NSClassFromString(class); - if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { - return [[ModelClass alloc] initWithDictionary:data error:nil]; - } - - return nil; -} - -#pragma mark - Operation Methods - -- (void) operationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id response) { - if([self executeRequestWithId:requestId]) { - if([[{{classPrefix}}Configuration sharedConfig] debug]) { - [self logResponse:operation forRequest:request error:nil]; - } - completionBlock(response, nil); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if(operation.responseObject) { - // Add in the (parsed) response body. - userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - if([[{{classPrefix}}Configuration sharedConfig] debug]) - [self logResponse:nil forRequest:request error:augmentedError]; - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; -} - -- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id responseObject) { - {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; - NSString *directory = nil; - if (config.tempFolderPath) { - directory = config.tempFolderPath; - } - else { - directory = NSTemporaryDirectory(); - } - - NSDictionary *headers = operation.response.allHeaderFields; - NSString *filename = nil; - if ([headers objectForKey:@"Content-Disposition"]) { - - NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; - filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; - } - else { - filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; - } - - NSString *filepath = [directory stringByAppendingPathComponent:filename]; - NSURL *file = [NSURL fileURLWithPath:filepath]; - - [operation.responseData writeToURL:file atomically:YES]; - completionBlock(file, nil); - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - - if ([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (operation.responseObject) { - userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; - } - - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - if ([[{{classPrefix}}Configuration sharedConfig] debug]) { - [self logResponse:nil forRequest:request error:augmentedError]; - } - - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; -} - -#pragma mark - Perform Request Methods - --(NSNumber*) requestWithCompletionBlock: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock { - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"multipart/form-data"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else { - NSAssert(false, @"unsupport request type %@", requestContentType); - } - - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; - } - else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - } - - // auth setting - [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; - - NSMutableURLRequest * request = nil; - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; - NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - if (files.count > 0) { - request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" - URLString:urlString - parameters:nil - constructingBodyWithBlock:^(id formData) { - [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSData *data = [obj dataUsingEncoding:NSUTF8StringEncoding]; - [formData appendPartWithFormData:data name:key]; - }]; - [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSURL *filePath = (NSURL *)obj; - [formData appendPartWithFileURL:filePath name:key error:nil]; - }]; - } error:nil]; - } - else { - if (formParams) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:formParams - error:nil]; - } - if (body) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:body - error:nil]; - } - } - - BOOL hasHeaderParams = false; - if(headerParams != nil && [headerParams count] > 0) { - hasHeaderParams = true; - } - if(offlineState) { - NSLog(@"%@ cache forced", path); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - NSLog(@"%@ cache enabled", path); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - NSLog(@"%@ cache disabled", path); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; - } - - if(hasHeaderParams){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; - - NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; - if ([responseType isEqualToString:@"NSURL*"]) { - [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { - completionBlock(data, error); - }]; - } - else { - [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { - completionBlock([self deserialize:data class:responseType], error); - }]; - } - return requestId; -} - @end - - - - diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 0edab7414f1..46d424d735f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -5,11 +5,18 @@ #import "{{classPrefix}}JSONRequestSerializer.h" #import "{{classPrefix}}QueryParamCollection.h" #import "{{classPrefix}}Configuration.h" - -{{#models}}{{#model}}#import "{{classname}}.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +{{#models}}{{#model}}#import "{{classname}}.h" {{/model}}{{/models}} +@class {{classPrefix}}Configuration; + /** * A key for `NSError` user info dictionaries. * @@ -25,77 +32,61 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; @property(nonatomic, readonly) NSOperationQueue* queue; /** - * Get the Api Client instance from pool - * - * @param baseUrl The base url of api client. - * - * @return The {{classPrefix}}ApiClient instance. - */ -+({{classPrefix}}ApiClient *)sharedClientFromPool:(NSString *)baseUrl; - -/** - * Get the operations queue - * - * @return The `shardQueue` static variable. - */ -+(NSOperationQueue*) sharedQueue; - -/** - * Clear Cache + * Clears Cache */ +(void)clearCache; /** - * Turn on cache + * Turns on cache * * @param enabled If the cached is enable, must be `YES` or `NO` */ +(void)setCacheEnabled:(BOOL) enabled; /** - * Get the request queue size + * Gets the request queue size * * @return The size of `queuedRequests` static variable. */ +(unsigned long)requestQueueSize; /** - * Set the client unreachable + * Sets the client unreachable * - * @param state off line state, must be `YES` or `NO` + * @param state off line state, must be `YES` or `NO` */ +(void) setOfflineState:(BOOL) state; /** - * Get the client reachability + * Gets the client reachability * * @return The client reachability. */ +(AFNetworkReachabilityStatus) getReachabilityStatus; /** - * Get the next request id + * Gets the next request id * * @return The next executed request id. */ +(NSNumber*) nextRequestId; /** - * Generate request id and add it to the queue + * Generates request id and add it to the queue * * @return The next executed request id. */ +(NSNumber*) queueRequest; /** - * Remove request id from the queue + * Removes request id from the queue * * @param requestId The request which will be removed. */ +(void) cancelRequest:(NSNumber*)requestId; /** - * URL encode NSString + * Gets URL encoded NSString * * @param unescaped The string which will be escaped. * @@ -104,21 +95,19 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +(NSString*) escape:(id)unescaped; /** - * Customize the behavior when the reachability changed + * Customizes the behavior when the reachability changed * * @param changeBlock The block will be executed when the reachability changed. */ +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; /** - * Set the client reachability strategy - * - * @param host The host of {{classPrefix}}ApiClient. + * Sets the api client reachability strategy */ -+(void) configureCacheReachibilityForHost:(NSString*)host; +- (void)configureCacheReachibility; /** - * Detect Accept header from accepts NSArray + * Detects Accept header from accepts NSArray * * @param accepts NSArray of header * @@ -127,7 +116,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +(NSString *) selectHeaderAccept:(NSArray *)accepts; /** - * Detect Content-Type header from contentTypes NSArray + * Detects Content-Type header from contentTypes NSArray * * @param contentTypes NSArray of header * @@ -136,7 +125,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +(NSString *) selectHeaderContentType:(NSArray *)contentTypes; /** - * Set header for request + * Sets header for request * * @param value The header value * @param forKey The header key @@ -145,7 +134,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; forKey:(NSString*) forKey; /** - * Update header parameters and query parameters for authentication + * Updates header parameters and query parameters for authentication * * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. @@ -156,7 +145,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; WithAuthSettings:(NSArray *)authSettings; /** - * Deserialize the given data to Objective-C object. + * Deserializes the given data to Objective-C object. * * @param data The data will be deserialized. * @param class The type of objective-c object. @@ -164,7 +153,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; - (id) deserialize:(id) data class:(NSString *) class; /** - * Logging request and response + * Logs request and response * * @param operation AFHTTPRequestOperation for the HTTP request. * @param request The HTTP request. @@ -175,7 +164,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; error:(NSError *)error; /** - * Perform request + * Performs request * * @param path Request url. * @param method Request method. @@ -185,7 +174,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * @param authSettings Request authentication names. * @param requestContentType Request content-type. * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. + * @param completionBlock The block will be executed when the request completed. * * @return The request id. */ diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache index 832c69f417e..9c941b107a0 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache @@ -25,6 +25,8 @@ - (instancetype) init { self = [super init]; if (self) { + self.apiClient = nil; + self.host = @"{{basePath}}"; self.username = @""; self.password = @""; self.tempFolderPath = nil; @@ -54,18 +56,26 @@ NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - + return basicAuthCredentials; } #pragma mark - Setter Methods -- (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { - [self.mutableApiKey setValue:value forKey:field]; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { + [self.mutableApiKey setValue:apiKey forKey:identifier]; } -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field { - [self.mutableApiKeyPrefix setValue:value forKey:field]; +- (void) removeApiKey:(NSString *)identifier { + [self.mutableApiKey removeObjectForKey:identifier]; +} + +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { + [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; +} + +- (void) removeApiKeyPrefix:(NSString *)identifier { + [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } - (void) setLoggingFile:(NSString *)loggingFile { @@ -73,12 +83,12 @@ if ([self.loggingFileHanlder isKindOfClass:[NSFileHandle class]]) { [self.loggingFileHanlder closeFile]; } - + _loggingFile = loggingFile; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (self.loggingFileHanlder == nil) { + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHanlder == nil) { [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; } } @@ -95,15 +105,28 @@ #pragma mark - - (NSDictionary *) authSettings { - return @{ - @"api_key": @{ - @"type": @"api_key", - @"in": @"header", - @"key": @"api_key", - @"value": [self getApiKeyWithPrefix:@"api_key"] - }, - - }; + return @{ +{{#authMethods}} +{{#isApiKey}} + @"{{name}}": + @{ + @"type": @"api_key", + @"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}}, + @"key": @"{{keyParamName}}", + @"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"] + }, +{{/isApiKey}} +{{#isBasic}} + @"{{name}}": + @{ + @"type": @"basic", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getBasicAuthToken] + }, +{{/isBasic}} +{{/authMethods}} + }; } @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index 4f9518ea9d1..c9bac508bbb 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -1,26 +1,49 @@ #import +#import "{{classPrefix}}ApiClient.h" + +/** The `{{classPrefix}}Configuration` class manages the configurations for the sdk. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ +@class {{classPrefix}}ApiClient; + @interface {{classPrefix}}Configuration : NSObject +/** + * Default api client + */ +@property (nonatomic) {{classPrefix}}ApiClient *apiClient; + +/** + * Default base url + */ +@property (nonatomic) NSString *host; /** * Api key values for Api Key type Authentication * - * To add or remove api key, use `setValue:forApiKeyField:`. + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKey; /** * Api key prefix values to be prepend to the respective api key * - * To add or remove prefix, use `setValue:forApiKeyPrefixField:`. + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename and Password for Basic type Authentication + * Usename for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication */ -@property (nonatomic) NSString *username; @property (nonatomic) NSString *password; /** @@ -31,37 +54,74 @@ /** * Logging Settings */ -@property (nonatomic) BOOL debug; -@property (nonatomic) NSString *loggingFile; -@property (nonatomic) NSFileHandle *loggingFileHanlder; /** - * Get configuration singleton instance + * Debug switch, default false + */ +@property (nonatomic) BOOL debug; + +/** + * Debug file location, default log in console + */ +@property (nonatomic) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; + +/** + * Gets configuration singleton instance */ + (instancetype) sharedConfig; /** - * Sets field in `apiKey` + * Sets API key + * + * To remove a apiKey for an identifier, just set the apiKey to nil. + * + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). + * */ -- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; /** - * Sets field in `apiKeyPrefix` + * Removes api key + * + * @param identifier API key identifier. */ -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; +- (void) removeApiKey:(NSString *)identifier; /** - * Get API key (with prefix if set) + * Sets the prefix for API key + * + * To remove a apiKeyPrefix for an identifier, just set the apiKeyPrefix to nil. + * + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. + */ +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Removes api key prefix + * + * @param identifier API key identifier. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; + +/** + * Gets API key (with prefix if set) */ - (NSString *) getApiKeyWithPrefix:(NSString *) key; /** - * Get Basic Auth token + * Gets Basic Auth token */ - (NSString *) getBasicAuthToken; /** - * Get Authentication Setings + * Gets Authentication Setings */ - (NSDictionary *) authSettings; diff --git a/modules/swagger-codegen/src/main/resources/objc/README.mustache b/modules/swagger-codegen/src/main/resources/objc/README.mustache index db2b1e5b31e..30a8927c41a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/README.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/README.mustache @@ -12,6 +12,10 @@ To install it, put the API client library in your project and then simply add th pod "{{podName}}", :path => "/path/to/lib" ``` +## Recommendation + +It's recommended to create an instance of ApiClient per thread in a multithreaded environment to avoid any potential issue. + ## Author {{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index fa9fa3e29a9..198c5a89fdf 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -11,14 +11,16 @@ @implementation {{classname}} -static NSString * basePath = @"{{basePath}}"; - #pragma mark - Initialize methods - (id) init { self = [super init]; if (self) { - self.apiClient = [{{classPrefix}}ApiClient sharedClientFromPool:basePath]; + {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + if (config.apiClient == nil) { + config.apiClient = [[{{classPrefix}}ApiClient alloc] init]; + } + self.apiClient = config.apiClient; self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -27,12 +29,7 @@ static NSString * basePath = @"{{basePath}}"; - (id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient { self = [super init]; if (self) { - if (apiClient) { - self.apiClient = apiClient; - } - else { - self.apiClient = [{{classPrefix}}ApiClient sharedClientFromPool:basePath]; - } + self.apiClient = apiClient; self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -50,14 +47,6 @@ static NSString * basePath = @"{{basePath}}"; return singletonAPI; } -+(void) setBasePath:(NSString*)path { - basePath = path; -} - -+(NSString*) getBasePath { - return basePath; -} - -(void) addHeader:(NSString*)value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } @@ -93,13 +82,14 @@ static NSString * basePath = @"{{basePath}}"; } {{/required}}{{/allParams}} - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@{{path}}", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - {{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [{{classPrefix}}ApiClient escape:{{paramName}}]]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + {{#pathParams}}[resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [{{classPrefix}}ApiClient escape:{{paramName}}]]; {{/pathParams}} NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -175,7 +165,7 @@ static NSString * basePath = @"{{basePath}}"; } {{/requiredParams}} {{/requiredParamCount}} - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"{{httpMethod}}" queryParams: queryParams formParams: formParams diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 263c213dd6f..d9f691f7227 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -5,6 +5,12 @@ #import "{{classPrefix}}ApiClient.h" {{newline}} +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + {{#operations}} @interface {{classname}}: NSObject @@ -14,8 +20,6 @@ -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; -+(void) setBasePath:(NSString*)basePath; -+(NSString*) getBasePath; {{#operation}} /// /// diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index b728e6bb06c..33c0f8cf42b 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -3,12 +3,21 @@ #import "{{classname}}.h" @implementation {{classname}} - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; @@ -21,6 +30,14 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + {{/model}} @end {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache index 4afaec31a24..c3f3c865424 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache @@ -1,5 +1,12 @@ #import #import "{{classPrefix}}Object.h" + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + {{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} @@ -8,7 +15,7 @@ @protocol {{classname}} @end - + @interface {{classname}} : {{classPrefix}}Object {{#vars}} diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 73d4000d950..981085c6378 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -89,7 +89,7 @@ class Configuration * * @var string */ - protected $host = 'http://localhost'; + protected $host = '{{basePath}}'; /** * Timeout (second) of the HTTP request, by default set to 0, no timeout @@ -103,7 +103,7 @@ class Configuration * * @var string */ - protected $userAgent = "PHP-Swagger"; + protected $userAgent = "PHP-Swagger/{{artifactVersion}}"; /** * Debug switch (default set to false) diff --git a/modules/swagger-codegen/src/main/resources/python/__init__api.mustache b/modules/swagger-codegen/src/main/resources/python/__init__api.mustache index b4442b736ff..989a5ea8382 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__api.mustache @@ -1,5 +1,8 @@ from __future__ import absolute_import # import apis into api package -{{#apiInfo}}{{#apis}}from .{{classVarName}} import {{classname}} -{{/apis}}{{/apiInfo}} +{{#apiInfo}} +{{#apis}} +from .{{classVarName}} import {{classname}} +{{/apis}} +{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/python/__init__model.mustache b/modules/swagger-codegen/src/main/resources/python/__init__model.mustache index 7a3f1866ea7..734e0692350 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__model.mustache @@ -1,5 +1,5 @@ from __future__ import absolute_import # import models into model package -{{#models}}{{#model}}from .{{classVarName}} import {{classname}} -{{/model}}{{/models}} +{{#models}}{{#model}}from .{{classVarName}} import {{classname}}{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 11c96b5b622..3620e9fb9ee 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -1,4 +1,3 @@ -#!/usr/bin/env python # coding: utf-8 """ @@ -16,9 +15,8 @@ Copyright 2015 SmartBear Software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ + from __future__ import absolute_import import sys @@ -30,8 +28,13 @@ from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient + {{#operations}} class {{classname}}(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ def __init__(self, api_client=None): config = Configuration() @@ -41,38 +44,48 @@ class {{classname}}(object): if not config.api_client: config.api_client = ApiClient('{{basePath}}') self.api_client = config.api_client - - {{#operation}} +{{#operation}} + def {{nickname}}(self, {{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}**kwargs): """ {{{summary}}} {{{notes}}} - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - {{#allParams}}:param {{dataType}} {{paramName}}: {{{description}}} {{#required}}(required){{/required}}{{#optional}}(optional){{/optional}} - {{/allParams}} + :param callback function: The callback function + for asynchronous request. (optional) +{{#allParams}} + :param {{dataType}} {{paramName}}: {{{description}}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} +{{/allParams}} :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - {{#allParams}}{{#required}} +{{#allParams}} +{{#required}} # verify the required parameter '{{paramName}}' is set if {{paramName}} is None: raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{nickname}}`") - {{/required}}{{/allParams}} +{{/required}} +{{/allParams}} + all_params = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method {{nickname}}" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method {{nickname}}" % key + ) params[key] = val del params['kwargs'] @@ -80,45 +93,59 @@ class {{classname}}(object): method = '{{httpMethod}}' path_params = {} - {{#pathParams}} +{{#pathParams}} if '{{paramName}}' in params: - path_params['{{baseName}}'] = params['{{paramName}}'] - {{/pathParams}} + path_params['{{baseName}}'] = params['{{paramName}}'] +{{/pathParams}} + query_params = {} - {{#queryParams}} +{{#queryParams}} if '{{paramName}}' in params: query_params['{{baseName}}'] = params['{{paramName}}'] - {{/queryParams}} +{{/queryParams}} + header_params = {} - {{#headerParams}} +{{#headerParams}} if '{{paramName}}' in params: header_params['{{baseName}}'] = params['{{paramName}}'] - {{/headerParams}} +{{/headerParams}} + form_params = {} files = {} - {{#formParams}} +{{#formParams}} if '{{paramName}}' in params: {{#notFile}}form_params['{{baseName}}'] = params['{{paramName}}']{{/notFile}}{{#isFile}}files['{{baseName}}'] = params['{{paramName}}']{{/isFile}} - {{/formParams}} +{{/formParams}} + body_params = None - {{#bodyParam}} +{{#bodyParam}} if '{{paramName}}' in params: body_params = params['{{paramName}}'] - {{/bodyParam}} +{{/bodyParam}} + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept([{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) + header_params['Accept'] = self.api_client.\ + select_header_accept([{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) # Authentication setting auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, + auth_settings=auth_settings, + callback=params.get('callback')) return response - {{/operation}} +{{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 924201c9a4a..ca9a3c05104 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -1,10 +1,20 @@ -#!/usr/bin/env python # coding: utf-8 -"""Swagger generic API client. This client handles the client- -server communication, and is invariant across implementations. Specifics of -the methods and models for each application are generated from the Swagger -templates.""" +""" +Copyright 2015 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" from __future__ import absolute_import from . import models @@ -27,415 +37,523 @@ from datetime import date from six import iteritems try: - # for python3 - from urllib.parse import quote + # for python3 + from urllib.parse import quote except ImportError: - # for python2 - from urllib import quote + # for python2 + from urllib import quote from .configuration import Configuration + class ApiClient(object): - """ - Generic API client for Swagger client library builds - - :param host: The base path for the server to call - :param header_name: a header to pass when making calls to the API - :param header_value: a header value to pass when making calls to the API - """ - def __init__(self, host=Configuration().host, header_name=None, header_value=None): - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.host = host - self.cookie = None - # Set default User-Agent. - self.user_agent = 'Python-Swagger' - - @property - def user_agent(self): - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None): - - # headers parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - for k, v in iteritems(path_params): - replacement = quote(str(self.to_path_value(v))) - resource_path = resource_path.replace('{' + k + '}', replacement) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} - - # post parameters - if post_params: - post_params = self.prepare_post_parameters(post_params, files) - post_params = self.sanitize_for_serialization(post_params) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - url = self.host + resource_path - - # perform request and return response - response_data = self.request(method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body) - - self.last_response = response_data - - # deserialize response data - if response_type: - deserialized_data = self.deserialize(response_data, response_type) - else: - deserialized_data = None - - if callback: - callback(deserialized_data) - else: - return deserialized_data - - def to_path_value(self, obj): """ - Convert a string or object to a path-friendly value + Generic API client for Swagger client library builds. - :param obj: object or string value + Swagger generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the Swagger + templates. - :return string: quoted value + NOTE: This class is auto generated by the swagger code generator program. + https://github.com/swagger-api/swagger-codegen + Do not edit the class manually. + + :param host: The base path for the server to call. + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to the API. """ - if type(obj) == list: - return ','.join(obj) - else: - return str(obj) + def __init__(self, host=Configuration().host, + header_name=None, header_value=None, cookie=None): - def sanitize_for_serialization(self, obj): - """ - Sanitize an object for Request. + """ + Constructor of the class. + """ + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.host = host + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'Python-Swagger' - If obj is None, return None. - If obj is str, int, float, bool, return directly. - If obj is datetime.datetime, datetime.date convert to string in iso8601 format. - If obj is list, santize each element in the list. - If obj is dict, return the dict. - If obj is swagger model, return the properties dict. - """ - if isinstance(obj, type(None)): - return None - elif isinstance(obj, (str, int, float, bool, tuple)): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] - elif isinstance(obj, (datetime, date)): - return obj.isoformat() - else: - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in model definition for request. - obj_dict = {obj.attribute_map[key]: val - for key, val in iteritems(obj.__dict__) - if key != 'swagger_types' and key != 'attribute_map' and val is not None} - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + @property + def user_agent(self): + """ + Gets user agent. + """ + return self.default_headers['User-Agent'] - def deserialize(self, response, response_type): - """ - Derialize response into an object. + @user_agent.setter + def user_agent(self, value): + """ + Sets user agent. + """ + self.default_headers['User-Agent'] = value - :param response: RESTResponse object to be deserialized - :param response_type: class literal for deserialzied object, or string of class name + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value - :return: deserialized object - """ - # handle file downloading - save response body into a tmp file and return the instance - if "file" == response_type: - return self.__deserialize_file(response) + def __call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_type=None, auth_settings=None, callback=None): - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data + # headers parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) - return self.__deserialize(data, response_type) + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + for k, v in iteritems(path_params): + replacement = quote(str(self.to_path_value(v))) + resource_path = resource_path.\ + replace('{' + k + '}', replacement) - def __deserialize(self, data, klass): - """ - :param data: dict, list or str - :param klass: class literal, or string of class name + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + query_params = {k: self.to_path_value(v) + for k, v in iteritems(query_params)} - :return: object - """ - if data is None: - return None + # post parameters + if post_params: + post_params = self.prepare_post_parameters(post_params, files) + post_params = self.sanitize_for_serialization(post_params) - if type(klass) == str: - if 'list[' in klass: - sub_kls = re.match('list\[(.*)\]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) for sub_data in data] + # auth setting + self.update_params_for_auth(header_params, query_params, auth_settings) - if 'dict(' in klass: - sub_kls = re.match('dict\((.*), (.*)\)', klass).group(2) - return {k: self.__deserialize(v, sub_kls) for k, v in iteritems(data)} + # body + if body: + body = self.sanitize_for_serialization(body) - # convert str to class - # for native types - if klass in ['int', 'float', 'str', 'bool', "date", 'datetime', "object"]: - klass = eval(klass) - # for model types - else: - klass = eval('models.' + klass) + # request url + url = self.host + resource_path - if klass in [int, float, str, bool]: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object() - elif klass == date: - return self.__deserialize_date(data) - elif klass == datetime: - return self.__deserialize_datatime(data) - else: - return self.__deserialize_model(data, klass) + # perform request and return response + response_data = self.request(method, url, + query_params=query_params, + headers=header_params, + post_params=post_params, body=body) - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None): - """ - Perform http request and return deserialized data + self.last_response = response_data - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. - :param callback function: Callback function for asynchronous request. - If provide this parameter, the request will be called asynchronously. - :return: - If provide parameter callback, the request will be called asynchronously. - The method will return the request thread. - If parameter callback is None, then the method will return the response directly. - """ - if callback is None: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, callback) - else: - thread = threading.Thread(target=self.__call_api, - args=(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, callback)) - thread.start() - return thread - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None): - """ - Perform http request using RESTClient. - """ - if method == "GET": - return RESTClient.GET(url, query_params=query_params, headers=headers) - elif method == "HEAD": - return RESTClient.HEAD(url, query_params=query_params, headers=headers) - elif method == "POST": - return RESTClient.POST(url, headers=headers, post_params=post_params, body=body) - elif method == "PUT": - return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body) - elif method == "PATCH": - return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body) - elif method == "DELETE": - return RESTClient.DELETE(url, query_params=query_params, headers=headers) - else: - raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`") - - def prepare_post_parameters(self, post_params=None, files=None): - params = {} - - if post_params: - params.update(post_params) - - if files: - for k, v in iteritems(files): - if v: - with open(v, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - params[k] = tuple([filename, filedata, mimetype]) - - return params - - def select_header_accept(self, accepts): - """ - Return `Accept` based on an array of accepts provided - """ - if not accepts: - return - - accepts = list(map(lambda x: x.lower(), accepts)) - - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) - - def select_header_content_type(self, content_types): - """ - Return `Content-Type` baseed on an array of content_types provided - """ - if not content_types: - return 'application/json' - - content_types = list(map(lambda x: x.lower(), content_types)) - - if 'application/json' in content_types: - return 'application/json' - else: - return content_types[0] - - def update_params_for_auth(self, headers, querys, auth_settings): - """ - Update header and query params based on authentication setting - """ - config = Configuration() - - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = config.auth_settings().get(auth) - if auth_setting: - if auth_setting['in'] == 'header': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - querys[auth_setting['key']] = auth_setting['value'] + # deserialize response data + if response_type: + deserialized_data = self.deserialize(response_data, response_type) else: - raise ValueError('Authentication token must be in `query` or `header`') + deserialized_data = None - def __deserialize_file(self, response): - """ - Save response body into a file in (the defined) temporary folder, using the filename - from the `Content-Disposition` header if provided, otherwise a random filename. + if callback: + callback(deserialized_data) + else: + return deserialized_data - :param response: RESTResponse - :return: file path - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) + def to_path_value(self, obj): + """ + Takes value and turn it into a string suitable for inclusion in + the path, by url-encoding. - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) + :param obj: object or string value. - with open(path, "w") as f: - f.write(response.data) + :return string: quoted value. + """ + if type(obj) == list: + return ','.join(obj) + else: + return str(obj) - return path + def sanitize_for_serialization(self, obj): + """ + Builds a JSON POST object. - def __deserialize_primitive(self, data, klass): - """ - Deserialize string to primitive type + If obj is None, return None. + If obj is str, int, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is list, santize each element in the list. + If obj is dict, return the dict. + If obj is swagger model, return the properties dict. - :param data: str - :param klass: class literal + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if isinstance(obj, type(None)): + return None + elif isinstance(obj, (str, int, float, bool, tuple)): + return obj + elif isinstance(obj, list): + return [self.sanitize_for_serialization(sub_obj) + for sub_obj in obj] + elif isinstance(obj, (datetime, date)): + return obj.isoformat() + else: + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `swagger_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = {obj.attribute_map[key[1:]]: val + for key, val in iteritems(obj.__dict__) + if key != 'swagger_types' + and key != 'attribute_map' + and val is not None} - :return: int, float, str, bool - """ - try: - value = klass(data) - except UnicodeEncodeError: - value = unicode(data) - except TypeError: - value = data - return value + return {key: self.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} - def __deserialize_object(self): - """ - Deserialize empty object - """ - return object() + def deserialize(self, response, response_type): + """ + Deserializes response into an object. - def __deserialize_date(self, string): - """ - Deserialize string to date + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialzied object, or string of class name. - :param string: str - :return: date - """ - try: - from dateutil.parser import parse - return parse(string).date() - except ImportError: - return string - except ValueError: - raise ApiException(status=0, reason="Failed to parse `{0}` into a date object".format(string)) - - def __deserialize_datatime(self, string): - """ - Deserialize string to datetime. + :return: deserialized object. + """ + # handle file downloading + # save response body into a tmp file and return the instance + if "file" == response_type: + return self.__deserialize_file(response) - The string should be in iso8601 datetime format. + # fetch data from response object + try: + data = json.loads(response.data) + except ValueError: + data = response.data - :param string: str - :return: datetime - """ - try: - from dateutil.parser import parse - return parse(string) - except ImportError: - return string - except ValueError: - raise ApiException(status=0, reason="Failed to parse `{0}` into a datetime object".format(string)) + return self.__deserialize(data, response_type) - def __deserialize_model(self, data, klass): - """ - Deserialize list or dict to model + def __deserialize(self, data, klass): + """ + Deserializes dict, list, str into an object. - :param data: dict, list - :param klass: class literal - """ - instance = klass() + :param data: dict, list or str. + :param klass: class literal, or string of class name. - for attr, attr_type in iteritems(instance.swagger_types): - if data is not None \ - and instance.attribute_map[attr] in data\ - and isinstance(data, (list, dict)): - value = data[instance.attribute_map[attr]] - setattr(instance, attr, self.__deserialize(value, attr_type)) + :return: object. + """ + if data is None: + return None - return instance + if type(klass) == str: + if klass.startswith('list['): + sub_kls = re.match('list\[(.*)\]', klass).group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] + + if klass.startswith('dict('): + sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in iteritems(data)} + + # convert str to class + # for native types + if klass in ['int', 'float', 'str', 'bool', + "date", 'datetime', "object"]: + klass = eval(klass) + # for model types + else: + klass = eval('models.' + klass) + + if klass in [int, float, str, bool]: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object() + elif klass == date: + return self.__deserialize_date(data) + elif klass == datetime: + return self.__deserialize_datatime(data) + else: + return self.__deserialize_model(data, klass) + + def call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_type=None, auth_settings=None, callback=None): + """ + Makes the HTTP request and return the deserialized data. + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param response: Response data type. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param callback function: Callback function for asynchronous request. + If provide this parameter, + the request will be called asynchronously. + :return: + If provide parameter callback, + the request will be called asynchronously. + The method will return the request thread. + If parameter callback is None, + then the method will return the response directly. + """ + if callback is None: + return self.__call_api(resource_path, method, + path_params, query_params, header_params, + body, post_params, files, + response_type, auth_settings, callback) + else: + thread = threading.Thread(target=self.__call_api, + args=(resource_path, method, + path_params, query_params, + header_params, body, + post_params, files, + response_type, auth_settings, + callback)) + thread.start() + return thread + + def request(self, method, url, query_params=None, headers=None, + post_params=None, body=None): + """ + Makes the HTTP request using RESTClient. + """ + if method == "GET": + return RESTClient.GET(url, + query_params=query_params, + headers=headers) + elif method == "HEAD": + return RESTClient.HEAD(url, + query_params=query_params, + headers=headers) + elif method == "POST": + return RESTClient.POST(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "PUT": + return RESTClient.PUT(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "PATCH": + return RESTClient.PATCH(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "DELETE": + return RESTClient.DELETE(url, + query_params=query_params, + headers=headers) + else: + raise ValueError( + "http method must be `GET`, `HEAD`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def prepare_post_parameters(self, post_params=None, files=None): + """ + Builds form parameters. + + :param post_params: Normal form parameters. + :param files: File parameters. + :return: Form parameters with files. + """ + params = {} + + if post_params: + params.update(post_params) + + if files: + for k, v in iteritems(files): + if not v: + continue + + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.\ + guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) + + return params + + def select_header_accept(self, accepts): + """ + Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return + + accepts = list(map(lambda x: x.lower(), accepts)) + + if 'application/json' in accepts: + return 'application/json' + else: + return ', '.join(accepts) + + def select_header_content_type(self, content_types): + """ + Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return 'application/json' + + content_types = list(map(lambda x: x.lower(), content_types)) + + if 'application/json' in content_types: + return 'application/json' + else: + return content_types[0] + + def update_params_for_auth(self, headers, querys, auth_settings): + """ + Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param querys: Query parameters dict to be updated. + :param auth_settings: Authentication setting identifiers list. + """ + config = Configuration() + + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = config.auth_settings().get(auth) + if auth_setting: + if auth_setting['in'] == 'header': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + querys[auth_setting['key']] = auth_setting['value'] + else: + raise ValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """ + Saves response body into a file in (the defined) temporary folder, + using the filename from the `Content-Disposition` header if provided, + otherwise a random filename. + + :param response: RESTResponse. + :return: file path. + """ + config = Configuration() + + fd, path = tempfile.mkstemp(dir=config.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + filename = re.\ + search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).\ + group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "w") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """ + Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, float, str, bool. + """ + try: + value = klass(data) + except UnicodeEncodeError: + value = unicode(data) + except TypeError: + value = data + return value + + def __deserialize_object(self): + """ + Deserializes empty object. + + :return: object. + """ + return object() + + def __deserialize_date(self, string): + """ + Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + from dateutil.parser import parse + return parse(string).date() + except ImportError: + return string + except ValueError: + raise ApiException( + status=0, + reason="Failed to parse `{0}` into a date object" + .format(string) + ) + + def __deserialize_datatime(self, string): + """ + Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + from dateutil.parser import parse + return parse(string) + except ImportError: + return string + except ValueError: + raise ApiException( + status=0, + reason="Failed to parse `{0}` into a datetime object". + format(string) + ) + + def __deserialize_model(self, data, klass): + """ + Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + instance = klass() + + for attr, attr_type in iteritems(instance.swagger_types): + if data is not None \ + and instance.attribute_map[attr] in data\ + and isinstance(data, (list, dict)): + value = data[instance.attribute_map[attr]] + setattr(instance, attr, self.__deserialize(value, attr_type)) + + return instance diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 0feb7af5d59..62633cdc4a1 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -1,10 +1,35 @@ +# coding: utf-8 + +""" +Copyright 2015 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + from __future__ import absolute_import import base64 import urllib3 -import httplib + +try: + import httplib +except ImportError: + # python3 + import http.client as httplib + import sys import logging + def singleton(cls, *args, **kw): instances = {} @@ -17,24 +42,45 @@ def singleton(cls, *args, **kw): @singleton class Configuration(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + https://github.com/swagger-api/swagger-codegen + Do not edit the class manually. + """ def __init__(self): + """ + Constructor + """ # Default Base url self.host = "{{basePath}}" # Default api client self.api_client = None + # Temp file folder for download + self.temp_folder_path = None + # Authentication Settings + # dict to store API key(s) self.api_key = {} + # dict to store API prefix (e.g. Bearer) self.api_key_prefix = {} + # Username for HTTP basic authentication self.username = "" + # Password for HTTP basic authentication self.password = "" + # Logging Settings self.logging_format = '%(asctime)s %(levelname)s %(message)s' + # Debug file location self.__logging_file = None + # Debug switch self.__debug = False self.init_logger() def init_logger(self): + """ + Initializes logger settings. + """ self.logger = logging.getLogger() formatter = logging.Formatter(self.logging_format) stream_handler = logging.StreamHandler() @@ -79,43 +125,65 @@ class Configuration(object): # setting log level to default `logging.WARNING` self.logger.setLevel(logging.WARNING) - def get_api_key_with_prefix(self, key): - """ Return api key prepend prefix for key """ - if self.api_key.get(key) and self.api_key_prefix.get(key): - return self.api_key_prefix[key] + ' ' + self.api_key[key] - elif self.api_key.get(key): - return self.api_key[key] + def get_api_key_with_prefix(self, identifier): + """ + Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :return: The token for api key authentication. + """ + if self.api_key.get(identifier) and self.api_key_prefix.get(identifier): + return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] + elif self.api_key.get(identifier): + return self.api_key[identifier] def get_basic_auth_token(self): - """ Return basic auth header string """ + """ + Gets basic auth header string. + + :return: The token for basic HTTP authentication. + """ return urllib3.util.make_headers(basic_auth=self.username + ':' + self.password)\ .get('authorization') def auth_settings(self): - """ Return Auth Settings for api client """ - return { {{#authMethods}}{{#isApiKey}} - '{{name}}': { - 'type': 'api_key', - 'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, - 'key': '{{keyParamName}}', - 'value': self.get_api_key_with_prefix('{{keyParamName}}') - }, - {{/isApiKey}}{{#isBasic}} - '{{name}}': { - 'type': 'basic', - 'in': 'header', - 'key': 'Authorization', - 'value': self.get_basic_auth_token() - }, - {{/isBasic}}{{/authMethods}} - } + """ + Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + return { +{{#authMethods}} +{{#isApiKey}} + '{{name}}': + { + 'type': 'api_key', + 'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, + 'key': '{{keyParamName}}', + 'value': self.get_api_key_with_prefix('{{keyParamName}}') + }, +{{/isApiKey}} +{{#isBasic}} + '{{name}}': + { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_basic_auth_token() + }, +{{/isBasic}} +{{/authMethods}} + } def to_debug_report(self): + """ + Gets the essential information for debugging. + + :return: The report for debugging. + """ return "Python SDK Debug Report:\n"\ "OS: {env}\n"\ "Python Version: {pyversion}\n"\ "Version of the API: {{version}}\n"\ - "SDK Package Version: {{packageVersion}}".format(env=sys.platform, pyversion=sys.version) - - - + "SDK Package Version: {{packageVersion}}".\ + format(env=sys.platform, pyversion=sys.version) diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 429eac33ec5..c810655e382 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -1,4 +1,3 @@ -#!/usr/bin/env python # coding: utf-8 """ @@ -16,21 +15,26 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ + {{#models}} {{#model}} +from pprint import pformat +from six import iteritems + class {{classname}}(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { {{#vars}}'{{name}}': '{{{datatype}}}'{{#hasMore}}, @@ -41,19 +45,72 @@ class {{classname}}(object): {{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} } - {{#vars}} - {{#description}}# {{description}}{{/description}} - self.{{name}} = None # {{{datatype}}} - {{/vars}} + +{{#vars}} + self._{{name}} = None +{{/vars}} + +{{#vars}} + @property + def {{name}}(self): + """ + Gets the {{name}} of this {{classname}}. +{{#description}} {{{description}}}{{/description}} + + :return: The {{name}} of this {{classname}}. + :rtype: {{datatype}} + """ + return self._{{name}} + + @{{name}}.setter + def {{name}}(self, {{name}}): + """ + Sets the {{name}} of this {{classname}}. +{{#description}} {{{description}}}{{/description}} + + :param {{name}}: The {{name}} of this {{classname}}. + :type: {{datatype}} + """ + {{#isEnum}}allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] + if {{name}} not in allowed_values: + raise ValueError( + "Invalid value for `{{name}}`, must be one of {0}" + .format(allowed_values) + ) + {{/isEnum}}self._{{name}} = {{name}} + +{{/vars}} + def to_dict(self): + """ + Return model properties dict + """ + result = {} + + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) - - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) + """ + For `print` and `pprint` + """ + return self.to_str() {{/model}} {{/models}} - - diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 7cf08f50429..8a8e55eb3d1 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -1,6 +1,20 @@ # coding: utf-8 """ +Copyright 2015 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + Credit: this file (rest.py) is modified based on rest.py in Dropbox Python SDK: https://www.dropbox.com/developers/core/sdks/python """ @@ -51,6 +65,7 @@ class RESTResponse(io.IOBase): """ return self.urllib3_response.getheader(name, default) + class RESTClientObject(object): def __init__(self, pools_size=4): @@ -87,14 +102,17 @@ class RESTClientObject(object): :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` - :param post_params: request post parameters, `application/x-www-form-urlencode` + :param post_params: request post parameters, + `application/x-www-form-urlencode` and `multipart/form-data` """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] if post_params and body: - raise ValueError("body parameter cannot be used with post_params parameter.") + raise ValueError( + "body parameter cannot be used with post_params parameter." + ) post_params = post_params or {} headers = headers or {} @@ -144,22 +162,37 @@ class RESTClientObject(object): return r def GET(self, url, headers=None, query_params=None): - return self.request("GET", url, headers=headers, query_params=query_params) + return self.request("GET", url, + headers=headers, + query_params=query_params) def HEAD(self, url, headers=None, query_params=None): - return self.request("HEAD", url, headers=headers, query_params=query_params) + return self.request("HEAD", url, + headers=headers, + query_params=query_params) def DELETE(self, url, headers=None, query_params=None): - return self.request("DELETE", url, headers=headers, query_params=query_params) + return self.request("DELETE", url, + headers=headers, + query_params=query_params) def POST(self, url, headers=None, post_params=None, body=None): - return self.request("POST", url, headers=headers, post_params=post_params, body=body) + return self.request("POST", url, + headers=headers, + post_params=post_params, + body=body) def PUT(self, url, headers=None, post_params=None, body=None): - return self.request("PUT", url, headers=headers, post_params=post_params, body=body) + return self.request("PUT", url, + headers=headers, + post_params=post_params, + body=body) def PATCH(self, url, headers=None, post_params=None, body=None): - return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) + return self.request("PATCH", url, + headers=headers, + post_params=post_params, + body=body) class ApiException(Exception): @@ -183,13 +216,14 @@ class ApiException(Exception): error_message = "({0})\n"\ "Reason: {1}\n".format(self.status, self.reason) if self.headers: - error_message += "HTTP response headers: {0}".format(self.headers) + error_message += "HTTP response headers: {0}\n".format(self.headers) if self.body: - error_message += "HTTP response body: {0}".format(self.body) + error_message += "HTTP response body: {0}\n".format(self.body) return error_message + class RESTClient(object): """ A class with all class methods to perform JSON requests. diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index 9adc4e00f62..a939ce01958 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -1,3 +1,5 @@ +# coding: utf-8 + import sys from setuptools import setup, find_packages @@ -33,11 +35,3 @@ setup( ) {{/hasMore}}{{/apis}}{{/apiInfo}} - - - - - - - - diff --git a/modules/swagger-codegen/src/main/resources/python3/swagger.mustache b/modules/swagger-codegen/src/main/resources/python3/swagger.mustache index f99f0d4d250..57f959c380b 100644 --- a/modules/swagger-codegen/src/main/resources/python3/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python3/swagger.mustache @@ -18,13 +18,13 @@ from .models import * class ApiClient: """Generic API client for Swagger client library builds""" - def __init__(self, apiKey=None, apiServer=None): + def __init__(self, apiKey=None, apiServer=None, cookie=None): if apiKey == None: raise Exception('You must pass an apiKey when instantiating the ' 'APIClient') self.apiKey = apiKey self.apiServer = apiServer - self.cookie = None + self.cookie = cookie def callAPI(self, resourcePath, method, queryParams, postData, headerParams=None): diff --git a/modules/swagger-codegen/src/main/resources/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/retrofit/api.mustache index a916f363ff5..1f49b4a7cba 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/api.mustache @@ -22,7 +22,7 @@ public interface {{classname}} { {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{nickname}}({{^allParams}});{{/allParams}} - {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} );{{/hasMore}}{{/allParams}} {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/retrofit/formParams.mustache b/modules/swagger-codegen/src/main/resources/retrofit/formParams.mustache index 9853bc0bf11..be9a3ca9b26 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{paramName}}") TypedFile {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") TypedFile {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/retrofit/service.mustache b/modules/swagger-codegen/src/main/resources/retrofit/service.mustache index 218a9304071..df6d61b7ab8 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/service.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/service.mustache @@ -2,8 +2,20 @@ package {{invokerPackage}}; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.IOException; +import java.lang.reflect.Type; + import retrofit.RestAdapter; +import retrofit.converter.ConversionException; +import retrofit.converter.Converter; import retrofit.converter.GsonConverter; +import retrofit.mime.TypedByteArray; +import retrofit.mime.TypedInput; +import retrofit.mime.TypedOutput; public class ServiceGenerator { // No need to instantiate this class. @@ -15,9 +27,63 @@ public class ServiceGenerator { .create(); RestAdapter adapter = new RestAdapter.Builder() .setEndpoint("{{basePath}}") - .setConverter(new GsonConverter(gson)) + .setConverter(new GsonConverterWrapper(gson)) .build(); return adapter.create(serviceClass); } } + +/** + * This wrapper is to take care of this case: + * when the deserialization fails due to JsonParseException and the + * expected type is String, then just return the body string. + */ +class GsonConverterWrapper implements Converter { + private GsonConverter converter; + + public GsonConverterWrapper(Gson gson) { + converter = new GsonConverter(gson); + } + + @Override public Object fromBody(TypedInput body, Type type) throws ConversionException { + byte[] bodyBytes = readInBytes(body); + TypedByteArray newBody = new TypedByteArray(body.mimeType(), bodyBytes); + try { + return converter.fromBody(newBody, type); + } catch (ConversionException e) { + if (e.getCause() instanceof JsonParseException && type.equals(String.class)) { + return new String(bodyBytes); + } else { + throw e; + } + } + } + + @Override public TypedOutput toBody(Object object) { + return converter.toBody(object); + } + + private byte[] readInBytes(TypedInput body) throws ConversionException { + InputStream in = null; + try { + in = body.in(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + byte[] buffer = new byte[0xFFFF]; + for (int len; (len = in.read(buffer)) != -1;) + os.write(buffer, 0, len); + os.flush(); + return os.toByteArray(); + } catch (IOException e) { + throw new ConversionException(e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException ignored) { + } + } + } + + } +} diff --git a/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache index 9c2e9c073cd..2300341d6d9 100644 --- a/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache @@ -59,7 +59,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, if (cls == classOf[String]) { json match { case s: String => { - if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 2) + if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 1) else s } case _ => null diff --git a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache index c5ec8da35f1..25d063fd543 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache @@ -6,13 +6,13 @@ import Foundation -class {{projectName}}API { +public class {{projectName}}API { static let basePath = "{{basePath}}" static var credential: NSURLCredential? static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() } -class APIBase { +public class APIBase { func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? { let encoded: AnyObject? = encodable?.encodeToJSON() @@ -28,7 +28,7 @@ class APIBase { } } -class RequestBuilder { +public class RequestBuilder { var credential: NSURLCredential? var headers: [String:String] = [:] let parameters: [String:AnyObject]? @@ -36,24 +36,24 @@ class RequestBuilder { let method: String let URLString: String - required init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody } - func execute(completion: (response: Response?, erorr: NSError?) -> Void) { } + public func execute(completion: (response: Response?, erorr: NSError?) -> Void) { } - func addHeader(#name: String, value: String) -> Self { + public func addHeader(#name: String, value: String) -> Self { if !value.isEmpty { headers[name] = value } return self } - func addCredential() -> Self { - self.credential = OneteamAPI.credential + public func addCredential() -> Self { + self.credential = {{projectName}}API.credential return self } } diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 61e2bf2886d..c1718cb6780 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -29,7 +29,47 @@ class AlamofireRequestBuilder: RequestBuilder { managerStore[managerId] = manager let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL - let request = manager.request(Alamofire.Method(rawValue: method)!, URLString, parameters: parameters, encoding: encoding) + let xMethod = Alamofire.Method(rawValue: method) + let fileKeys = parameters == nil ? [] : map(filter(parameters!) { $1.isKindOfClass(NSURL) }) { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + self.processRequest(upload, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, erorr: encodingError) + } + } + ) + } else { + processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, erorr: NSError?) -> Void) { if let credential = self.credential { request.authenticate(usingCredential: credential) } @@ -66,7 +106,7 @@ class AlamofireRequestBuilder: RequestBuilder { completion(response: response, erorr: nil) return } - + completion(response: nil, erorr: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) } } diff --git a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache index af74617bcf2..f7838edf7ca 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache @@ -1,2 +1,2 @@ -github "Alamofire/Alamofire" >= 1.2 +github "Alamofire/Alamofire" >= 1.3 github "mxcl/PromiseKit" >=1.5.3 diff --git a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache index 801e90514ff..0d367cb8be3 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache @@ -65,7 +65,7 @@ extension NSDate: JSONEncodable { } {{#usePromiseKit}}extension RequestBuilder { - func execute() -> Promise> { + public func execute() -> Promise> { let deferred = Promise>.defer() self.execute { (response: Response?, error: NSError?) in if let response = response { diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index f832cdab9a4..5cc3f3eb774 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -10,18 +10,18 @@ protocol JSONEncodable { func encodeToJSON() -> AnyObject } -class Response { - let statusCode: Int - let header: [String: String] - let body: T +public class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T - init(statusCode: Int, header: [String: String], body: T) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - convenience init(response: NSHTTPURLResponse, body: T) { + public convenience init(response: NSHTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String:String]() for (key, value) in rawHeader { diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache new file mode 100644 index 00000000000..7b1ed59de8b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -0,0 +1,20 @@ +Pod::Spec.new do |s| + s.name = '{{projectName}}'{{#projectDescription}} + s.summary = '{{projectDescription}}'{{/projectDescription}} + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}' + s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}{{#podAuthors}} + s.authors = {{& podAuthors}}{{/podAuthors}}{{#podSocialMediaURL}} + s.social_media_url = '{{podSocialMediaURL}}'{{/podSocialMediaURL}}{{#podDocsetURL}} + s.docset_url = '{{podDocsetURL}}'{{/podDocsetURL}} + s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}}{{#podHomepage}} + s.homepage = '{{podHomepage}}'{{/podHomepage}}{{#podSummary}} + s.summary = '{{podSummary}}'{{/podSummary}}{{#podDescription}} + s.description = '{{podDescription}}'{{/podDescription}}{{#podScreenshots}} + s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}} + s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} + s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift' + s.dependency 'PromiseKit', '~> 2.1' + s.dependency 'Alamofire', '~> 1.3' +end diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 3caec601879..7595a1fa81d 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -11,7 +11,7 @@ import PromiseKit extension {{projectName}}API { {{#description}} /** {{description}} */{{/description}} - class {{classname}}: APIBase { + public class {{classname}}: APIBase { {{#operation}} /** {{#summary}} @@ -32,20 +32,22 @@ extension {{projectName}}API { :returns: Promise> {{description}} */ - func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + public class func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}} path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}} - let url = {{projectName}}API.basePath + path + let URLString = {{projectName}}API.basePath + path {{#bodyParam}} let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} - let nillableParameters: [String:AnyObject?] = {{^queryParams}}[:]{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} + let nillableParameters: [String:AnyObject?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}} + "{{paramName}}": {{paramName}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + ]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} "{{paramName}}": {{paramName}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/queryParams}} let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder(method: "{{httpMethod}}", URLString: url, parameters: parameters, isBody: {{^queryParams}}true{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}) + return requestBuilder(method: "{{httpMethod}}", URLString: URLString, parameters: parameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/swift/model.mustache b/modules/swagger-codegen/src/main/resources/swift/model.mustache index bcd4702fb3b..a2510a26dd0 100644 --- a/modules/swagger-codegen/src/main/resources/swift/model.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/model.mustache @@ -10,15 +10,15 @@ import Foundation {{#description}} /** {{description}} */{{/description}} -class {{classname}}: JSONEncodable { +public class {{classname}}: JSONEncodable { {{#vars}}{{#isEnum}} - enum {{datatypeWithEnum}}: String { {{#allowableValues}}{{#values}} + public enum {{datatypeWithEnum}}: String { {{#allowableValues}}{{#values}} case {{enum}} = "{{raw}}"{{/values}}{{/allowableValues}} } {{/isEnum}}{{/vars}} {{#vars}}{{#isEnum}}{{#description}}/** {{description}} */ - {{/description}}var {{name}}: {{{datatypeWithEnum}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}}{{^isEnum}}{{#description}}/** {{description}} */ - {{/description}}var {{name}}: {{{datatype}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}} + {{/description}}public var {{name}}: {{{datatypeWithEnum}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}}{{^isEnum}}{{#description}}/** {{description}} */ + {{/description}}public var {{name}}: {{{datatype}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}} {{/vars}} // MARK: JSONEncodable diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala index 0df82fce377..81e252aa117 100644 --- a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala @@ -86,7 +86,7 @@ class JavaModelTest extends FlatSpec with Matchers { vars.get(1).setter should be("setUrls") vars.get(1).datatype should be("List") vars.get(1).name should be("urls") - vars.get(1).defaultValue should be("new ArrayList() ") + vars.get(1).defaultValue should be("new ArrayList()") vars.get(1).baseType should be("List") vars.get(1).containerType should be("array") vars.get(1).required should equal(null) @@ -114,7 +114,7 @@ class JavaModelTest extends FlatSpec with Matchers { vars.get(0).setter should be("setTranslations") vars.get(0).datatype should be("Map") vars.get(0).name should be("translations") - vars.get(0).defaultValue should be("new HashMap() ") + vars.get(0).defaultValue should be("new HashMap()") vars.get(0).baseType should be("Map") vars.get(0).containerType should be("map") vars.get(0).required should equal(null) @@ -122,7 +122,7 @@ class JavaModelTest extends FlatSpec with Matchers { } - ignore should "convert a model with a map with complex list property" in { + it should "convert a model with a map with complex list property" in { val model = new ModelImpl() .description("a sample model") .property("translations", new MapProperty() @@ -145,13 +145,33 @@ class JavaModelTest extends FlatSpec with Matchers { vars.get(0).setter should be("setTranslations") vars.get(0).datatype should be("Map>") vars.get(0).name should be("translations") - vars.get(0).defaultValue should be("new HashMap>() ") + vars.get(0).defaultValue should be("new HashMap>()") vars.get(0).baseType should be("Map") vars.get(0).containerType should be("map") vars.get(0).required should equal(null) vars.get(0).isContainer should equal(true) } + it should "convert a model with a 2D list property" in { + val model = new ModelImpl().name("sample").property("list2D", new ArrayProperty().items( + new ArrayProperty().items(new RefProperty("Pet")))) + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + val vars = cm.vars + vars.size should be (1) + val list = vars.get(0) + list.baseName should be("list2D") + list.getter should be("getList2D") + list.setter should be("setList2D") + list.datatype should be("List>") + list.name should be("list2D") + list.defaultValue should be ("new ArrayList>()") + list.baseType should be("List") + list.containerType should be("array") + list.required should equal(null) + list.isContainer should equal(true) + } + it should "convert a model with complex properties" in { val model = new ModelImpl() .description("a sample model") @@ -198,7 +218,7 @@ class JavaModelTest extends FlatSpec with Matchers { vars.get(0).setter should be("setChildren") vars.get(0).datatype should be("List") vars.get(0).name should be("children") - vars.get(0).defaultValue should be("new ArrayList() ") + vars.get(0).defaultValue should be("new ArrayList()") vars.get(0).baseType should be("List") vars.get(0).containerType should be("array") vars.get(0).required should equal(null) @@ -227,7 +247,7 @@ class JavaModelTest extends FlatSpec with Matchers { vars.get(0).setter should be("setChildren") vars.get(0).datatype should be("Map") vars.get(0).name should be("children") - vars.get(0).defaultValue should be("new HashMap() ") + vars.get(0).defaultValue should be("new HashMap()") vars.get(0).baseType should be("Map") vars.get(0).containerType should be("map") vars.get(0).required should equal(null) diff --git a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala index 6747b94d4f8..3d509ca1a2d 100644 --- a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala @@ -90,7 +90,7 @@ class ObjcModelTest extends FlatSpec with Matchers { vars.get(0).isNotContainer should equal(true) vars.get(1).baseName should be("urls") - vars.get(1).datatype should be("NSArray*") + vars.get(1).datatype should be("NSArray* /* NSString */") vars.get(1).name should be("urls") // vars.get(1).defaultValue should be ("null") vars.get(1).baseType should be("NSArray") diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java index d59060f39ef..2faef30744b 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java @@ -37,7 +37,7 @@ public class Generator { throw new BadRequestException(400, "No swagger specification was supplied"); } } else { - swagger = new SwaggerParser().read(node); + swagger = new SwaggerParser().read(node, true); } if (swagger == null) { throw new BadRequestException(400, "The swagger specification supplied was not valid"); @@ -97,7 +97,7 @@ public class Generator { throw new BadRequestException(400, "No swagger specification was supplied"); } } else { - swagger = new SwaggerParser().read(node); + swagger = new SwaggerParser().read(node, true); } if (swagger == null) { throw new BadRequestException(400, "The swagger specification supplied was not valid"); diff --git a/pom.xml b/pom.xml index 10bd7340167..ca4a2219ba7 100644 --- a/pom.xml +++ b/pom.xml @@ -161,14 +161,6 @@ scala-maven-plugin ${scala-maven-plugin-version} - - org.apache.maven.plugins - maven-gpg-plugin - - release - sign - - org.apache.maven.plugins maven-javadoc-plugin @@ -464,10 +456,10 @@ - 1.0.8 + 1.0.10 2.11.1 2.3.4 - 1.5.0 + 1.5.4-SNAPSHOT 2.1.4 2.3 1.2 @@ -475,7 +467,7 @@ 1.0.0 2.4 1.6.3 - 3.1.5 + 3.2.1 1.9 diff --git a/run-in-docker.sh b/run-in-docker.sh new file mode 100755 index 00000000000..39a7601dd03 --- /dev/null +++ b/run-in-docker.sh @@ -0,0 +1,34 @@ +#!/bin/bash +set -e +cd "$(dirname $BASH_SOURCE)" + +maven_cache_repo="$HOME/.m2/repository" +myname="$(basename $BASH_SOURCE)" + +if [ "$1" = "mvn" ]; then + cmd="$1" + shift + args="$@" +else + jar="modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + + # Check if project is built + if [ ! -f "$jar" ]; then + echo "ERROR File not found: $jar" + echo "ERROR Did you forget to './$myname mvn package'?" + exit 1 + fi + + cmd="java -jar /gen/$jar" + args="$@" +fi + +mkdir -p "$maven_cache_repo" + +set -x + +docker run -it \ + -w /gen \ + -v "${PWD}:/gen" \ + -v "${maven_cache_repo}:/root/.m2/repository" \ + maven:3-jdk-7 $cmd $args diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index 0ccc3713958..eabb47e818d 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -216,7 +216,7 @@ public class ApiInvoker { } else if(String.class.equals(cls)) { if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) - return json.substring(1, json.length() - 2); + return json.substring(1, json.length() - 1); else return json; } diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md new file mode 100644 index 00000000000..5fe03fcb316 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md @@ -0,0 +1,10 @@ +# Csharp-DotNet2 + +This generator creates C# code targeting the .Net 2.0 framework. The resulting DLLs can be used in places where .Net 2.0 is the maximum supported version, such as in the Unity3d. + +## Dependencies +- Mono compiler +- Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator. + + + diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh new file mode 100644 index 00000000000..bc4e0989945 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh @@ -0,0 +1,12 @@ +wget -nc https://nuget.org/nuget.exe; +mozroots --import --sync +mono nuget.exe install vendor/packages.config -o vendor; +mkdir -p bin; +mcs -sdk:2 -r:vendor/Newtonsoft.Json.7.0.1/lib/net20/Newtonsoft.Json.dll,\ +vendor/RestSharp.Net2.1.1.11/lib/net20/RestSharp.Net2.dll,\ +System.Runtime.Serialization.dll \ +-target:library \ +-out:bin/IO.Swagger.dll \ +-recurse:src/*.cs \ +-doc:bin/IO.Swagger.xml \ +-platform:anycpu \ No newline at end of file diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs new file mode 100644 index 00000000000..238f7bf75e7 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs @@ -0,0 +1,475 @@ +using System; +using System.IO; +using System.Collections.Generic; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace IO.Swagger.Api +{ + + public interface IPetApi + { + + /// + /// Update an existing pet + /// + /// Pet object that needs to be added to the store + /// + void UpdatePet (Pet body); + + /// + /// Add a new pet to the store + /// + /// Pet object that needs to be added to the store + /// + void AddPet (Pet body); + + /// + /// Finds Pets by status Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// List + List FindPetsByStatus (List status); + + /// + /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// List + List FindPetsByTags (List tags); + + /// + /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// Pet + Pet GetPetById (long? petId); + + /// + /// Updates a pet in the store with form data + /// + /// ID of pet that needs to be updated + /// Updated name of the pet + /// Updated status of the pet + /// + void UpdatePetWithForm (string petId, string name, string status); + + /// + /// Deletes a pet + /// + /// Pet id to delete + /// + /// + void DeletePet (long? petId, string apiKey); + + /// + /// uploads an image + /// + /// ID of pet to update + /// Additional data to pass to server + /// file to upload + /// + void UploadFile (long? petId, string additionalMetadata, Stream file); + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class PetApi : IPetApi + { + /// + /// Initializes a new instance of the class. + /// + /// an instance of ApiClient (optional) + /// + public PetApi(ApiClient apiClient = null) + { + if (apiClient == null) // use the default one in Configuration + this.ApiClient = Configuration.DefaultApiClient; + else + this.ApiClient = apiClient; + } + + /// + /// Initializes a new instance of the class. + /// + /// + public PetApi(String basePath) + { + this.ApiClient = new ApiClient(basePath); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + /// The base path + public void SetBasePath(String basePath) + { + this.ApiClient.BasePath = basePath; + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + /// The base path + public String GetBasePath(String basePath) + { + return this.ApiClient.BasePath; + } + + /// + /// Gets or sets the API client. + /// + /// An instance of the ApiClient + public ApiClient ApiClient {get; set;} + + + /// + /// Update an existing pet + /// + /// Pet object that needs to be added to the store + /// + public void UpdatePet (Pet body) + { + + + var path = "/pet"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = ApiClient.Serialize(body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + /// + /// Add a new pet to the store + /// + /// Pet object that needs to be added to the store + /// + public void AddPet (Pet body) + { + + + var path = "/pet"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = ApiClient.Serialize(body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + /// + /// Finds Pets by status Multiple status values can be provided with comma seperated strings + /// + /// Status values that need to be considered for filter + /// List + public List FindPetsByStatus (List status) + { + + + var path = "/pet/findByStatus"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (status != null) queryParams.Add("status", ApiClient.ParameterToString(status)); // query parameter + + + + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.ErrorMessage, response.ErrorMessage); + + return (List) ApiClient.Deserialize(response.Content, typeof(List), response.Headers); + } + + + /// + /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// + /// Tags to filter by + /// List + public List FindPetsByTags (List tags) + { + + + var path = "/pet/findByTags"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (tags != null) queryParams.Add("tags", ApiClient.ParameterToString(tags)); // query parameter + + + + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.ErrorMessage, response.ErrorMessage); + + return (List) ApiClient.Deserialize(response.Content, typeof(List), response.Headers); + } + + + /// + /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// + /// ID of pet that needs to be fetched + /// Pet + public Pet GetPetById (long? petId) + { + + // verify the required parameter 'petId' is set + if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetById"); + + + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + + + // authentication setting, if any + String[] authSettings = new String[] { "api_key", "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.ErrorMessage, response.ErrorMessage); + + return (Pet) ApiClient.Deserialize(response.Content, typeof(Pet), response.Headers); + } + + + /// + /// Updates a pet in the store with form data + /// + /// ID of pet that needs to be updated + /// Updated name of the pet + /// Updated status of the pet + /// + public void UpdatePetWithForm (string petId, string name, string status) + { + + // verify the required parameter 'petId' is set + if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UpdatePetWithForm"); + + + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + if (name != null) formParams.Add("name", ApiClient.ParameterToString(name)); // form parameter + if (status != null) formParams.Add("status", ApiClient.ParameterToString(status)); // form parameter + + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + /// + /// Deletes a pet + /// + /// Pet id to delete + /// + /// + public void DeletePet (long? petId, string apiKey) + { + + // verify the required parameter 'petId' is set + if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling DeletePet"); + + + var path = "/pet/{petId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + if (apiKey != null) headerParams.Add("api_key", ApiClient.ParameterToString(apiKey)); // header parameter + + + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + /// + /// uploads an image + /// + /// ID of pet to update + /// Additional data to pass to server + /// file to upload + /// + public void UploadFile (long? petId, string additionalMetadata, Stream file) + { + + // verify the required parameter 'petId' is set + if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UploadFile"); + + + var path = "/pet/{petId}/uploadImage"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + if (additionalMetadata != null) formParams.Add("additionalMetadata", ApiClient.ParameterToString(additionalMetadata)); // form parameter + if (file != null) fileParams.Add("file", ApiClient.ParameterToFile("file", file)); + + + + // authentication setting, if any + String[] authSettings = new String[] { "petstore_auth" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + } + +} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs new file mode 100644 index 00000000000..c6c90631bef --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs @@ -0,0 +1,263 @@ +using System; +using System.IO; +using System.Collections.Generic; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace IO.Swagger.Api +{ + + public interface IStoreApi + { + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Dictionary + Dictionary GetInventory (); + + /// + /// Place an order for a pet + /// + /// order placed for purchasing the pet + /// Order + Order PlaceOrder (Order body); + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// ID of pet that needs to be fetched + /// Order + Order GetOrderById (string orderId); + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + /// + void DeleteOrder (string orderId); + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class StoreApi : IStoreApi + { + /// + /// Initializes a new instance of the class. + /// + /// an instance of ApiClient (optional) + /// + public StoreApi(ApiClient apiClient = null) + { + if (apiClient == null) // use the default one in Configuration + this.ApiClient = Configuration.DefaultApiClient; + else + this.ApiClient = apiClient; + } + + /// + /// Initializes a new instance of the class. + /// + /// + public StoreApi(String basePath) + { + this.ApiClient = new ApiClient(basePath); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + /// The base path + public void SetBasePath(String basePath) + { + this.ApiClient.BasePath = basePath; + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + /// The base path + public String GetBasePath(String basePath) + { + return this.ApiClient.BasePath; + } + + /// + /// Gets or sets the API client. + /// + /// An instance of the ApiClient + public ApiClient ApiClient {get; set;} + + + /// + /// Returns pet inventories by status Returns a map of status codes to quantities + /// + /// Dictionary + public Dictionary GetInventory () + { + + + var path = "/store/inventory"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + + + // authentication setting, if any + String[] authSettings = new String[] { "api_key" }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.ErrorMessage, response.ErrorMessage); + + return (Dictionary) ApiClient.Deserialize(response.Content, typeof(Dictionary), response.Headers); + } + + + /// + /// Place an order for a pet + /// + /// order placed for purchasing the pet + /// Order + public Order PlaceOrder (Order body) + { + + + var path = "/store/order"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = ApiClient.Serialize(body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.ErrorMessage, response.ErrorMessage); + + return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers); + } + + + /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// + /// ID of pet that needs to be fetched + /// Order + public Order GetOrderById (string orderId) + { + + // verify the required parameter 'orderId' is set + if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling GetOrderById"); + + + var path = "/store/order/{orderId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.ErrorMessage, response.ErrorMessage); + + return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers); + } + + + /// + /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + /// + public void DeleteOrder (string orderId) + { + + // verify the required parameter 'orderId' is set + if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder"); + + + var path = "/store/order/{orderId}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + } + +} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs new file mode 100644 index 00000000000..ae43e29ceaf --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs @@ -0,0 +1,460 @@ +using System; +using System.IO; +using System.Collections.Generic; +using RestSharp; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace IO.Swagger.Api +{ + + public interface IUserApi + { + + /// + /// Create user This can only be done by the logged in user. + /// + /// Created user object + /// + void CreateUser (User body); + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + void CreateUsersWithArrayInput (List body); + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + void CreateUsersWithListInput (List body); + + /// + /// Logs user into the system + /// + /// The user name for login + /// The password for login in clear text + /// string + string LoginUser (string username, string password); + + /// + /// Logs out current logged in user session + /// + /// + void LogoutUser (); + + /// + /// Get user by user name + /// + /// The name that needs to be fetched. Use user1 for testing. + /// User + User GetUserByName (string username); + + /// + /// Updated user This can only be done by the logged in user. + /// + /// name that need to be deleted + /// Updated user object + /// + void UpdateUser (string username, User body); + + /// + /// Delete user This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// + void DeleteUser (string username); + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class UserApi : IUserApi + { + /// + /// Initializes a new instance of the class. + /// + /// an instance of ApiClient (optional) + /// + public UserApi(ApiClient apiClient = null) + { + if (apiClient == null) // use the default one in Configuration + this.ApiClient = Configuration.DefaultApiClient; + else + this.ApiClient = apiClient; + } + + /// + /// Initializes a new instance of the class. + /// + /// + public UserApi(String basePath) + { + this.ApiClient = new ApiClient(basePath); + } + + /// + /// Sets the base path of the API client. + /// + /// The base path + /// The base path + public void SetBasePath(String basePath) + { + this.ApiClient.BasePath = basePath; + } + + /// + /// Gets the base path of the API client. + /// + /// The base path + /// The base path + public String GetBasePath(String basePath) + { + return this.ApiClient.BasePath; + } + + /// + /// Gets or sets the API client. + /// + /// An instance of the ApiClient + public ApiClient ApiClient {get; set;} + + + /// + /// Create user This can only be done by the logged in user. + /// + /// Created user object + /// + public void CreateUser (User body) + { + + + var path = "/user"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = ApiClient.Serialize(body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + public void CreateUsersWithArrayInput (List body) + { + + + var path = "/user/createWithArray"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = ApiClient.Serialize(body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + /// + /// Creates list of users with given input array + /// + /// List of user object + /// + public void CreateUsersWithListInput (List body) + { + + + var path = "/user/createWithList"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = ApiClient.Serialize(body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + /// + /// Logs user into the system + /// + /// The user name for login + /// The password for login in clear text + /// string + public string LoginUser (string username, string password) + { + + + var path = "/user/login"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + if (username != null) queryParams.Add("username", ApiClient.ParameterToString(username)); // query parameter + if (password != null) queryParams.Add("password", ApiClient.ParameterToString(password)); // query parameter + + + + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.ErrorMessage, response.ErrorMessage); + + return (string) ApiClient.Deserialize(response.Content, typeof(string), response.Headers); + } + + + /// + /// Logs out current logged in user session + /// + /// + public void LogoutUser () + { + + + var path = "/user/logout"; + path = path.Replace("{format}", "json"); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + /// + /// Get user by user name + /// + /// The name that needs to be fetched. Use user1 for testing. + /// User + public User GetUserByName (string username) + { + + // verify the required parameter 'username' is set + if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling GetUserByName"); + + + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", ApiClient.ParameterToString(username)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.ErrorMessage, response.ErrorMessage); + + return (User) ApiClient.Deserialize(response.Content, typeof(User), response.Headers); + } + + + /// + /// Updated user This can only be done by the logged in user. + /// + /// name that need to be deleted + /// Updated user object + /// + public void UpdateUser (string username, User body) + { + + // verify the required parameter 'username' is set + if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling UpdateUser"); + + + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", ApiClient.ParameterToString(username)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + postBody = ApiClient.Serialize(body); // http body (model) parameter + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + /// + /// Delete user This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// + public void DeleteUser (string username) + { + + // verify the required parameter 'username' is set + if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling DeleteUser"); + + + var path = "/user/{username}"; + path = path.Replace("{format}", "json"); + path = path.Replace("{" + "username" + "}", ApiClient.ParameterToString(username)); + + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + + + + + + // authentication setting, if any + String[] authSettings = new String[] { }; + + // make the HTTP request + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + + if (((int)response.StatusCode) >= 400) + throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content, response.Content); + else if (((int)response.StatusCode) == 0) + throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.ErrorMessage, response.ErrorMessage); + + return; + } + + + } + +} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs new file mode 100644 index 00000000000..d4f32908b3d --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs @@ -0,0 +1,296 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; +using System.IO; +using System.Web; +using System.Linq; +using System.Net; +using System.Text; +using Newtonsoft.Json; +using RestSharp; +using RestSharp.Extensions; + +namespace IO.Swagger.Client +{ + /// + /// API client is mainly responible for making the HTTP call to the API backend. + /// + public class ApiClient + { + private readonly Dictionary _defaultHeaderMap = new Dictionary(); + + /// + /// Initializes a new instance of the class. + /// + /// The base path. + public ApiClient(String basePath="http://petstore.swagger.io/v2") + { + BasePath = basePath; + RestClient = new RestClient(BasePath); + } + + /// + /// Gets or sets the base path. + /// + /// The base path + public string BasePath { get; set; } + + /// + /// Gets or sets the RestClient. + /// + /// An instance of the RestClient + public RestClient RestClient { get; set; } + + /// + /// Gets the default header. + /// + public Dictionary DefaultHeader + { + get { return _defaultHeaderMap; } + } + + /// + /// Makes the HTTP request (Sync). + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// HTTP body (POST request). + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Authentication settings. + /// Object + public Object CallApi(String path, RestSharp.Method method, Dictionary queryParams, String postBody, + Dictionary headerParams, Dictionary formParams, + Dictionary fileParams, String[] authSettings) + { + + var request = new RestRequest(path, method); + + UpdateParamsForAuth(queryParams, headerParams, authSettings); + + // add default header, if any + foreach(var defaultHeader in _defaultHeaderMap) + request.AddHeader(defaultHeader.Key, defaultHeader.Value); + + // add header parameter, if any + foreach(var param in headerParams) + request.AddHeader(param.Key, param.Value); + + // add query parameter, if any + foreach(var param in queryParams) + request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost); + + // add form parameter, if any + foreach(var param in formParams) + request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost); + + // add file parameter, if any + foreach(var param in fileParams) + request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); + + if (postBody != null) // http body (model) parameter + request.AddParameter("application/json", postBody, ParameterType.RequestBody); + + return (Object)RestClient.Execute(request); + + } + + /// + /// Add default header. + /// + /// Header field name. + /// Header field value. + /// + public void AddDefaultHeader(string key, string value) + { + _defaultHeaderMap.Add(key, value); + } + + /// + /// Escape string (url-encoded). + /// + /// String to be escaped. + /// Escaped string. + public string EscapeString(string str) + { + return RestSharp.Contrib.HttpUtility.UrlEncode(str); + } + + /// + /// Create FileParameter based on Stream. + /// + /// Parameter name. + /// Input stream. + /// FileParameter. + public FileParameter ParameterToFile(string name, Stream stream) + { + if (stream is FileStream) + return FileParameter.Create(name, stream.ReadAsBytes(), Path.GetFileName(((FileStream)stream).Name)); + else + return FileParameter.Create(name, stream.ReadAsBytes(), "no_file_name_provided"); + } + + /// + /// If parameter is DateTime, output in ISO8601 format. + /// If parameter is a list of string, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// Formatted string. + public string ParameterToString(object obj) + { + if (obj is DateTime) + return ((DateTime)obj).ToString ("u"); + else if (obj is List) + return String.Join(",", (obj as List).ToArray()); + else + return Convert.ToString (obj); + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// HTTP body (e.g. string, JSON). + /// Object type. + /// Object representation of the JSON string. + public object Deserialize(string content, Type type, IList headers=null) + { + if (type == typeof(Object)) // return an object + { + return content; + } + + if (type == typeof(Stream)) + { + var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) + ? Path.GetTempPath() + : Configuration.TempFolderPath; + + var fileName = filePath + Guid.NewGuid(); + if (headers != null) + { + var regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$"); + var match = regex.Match(headers.ToString()); + if (match.Success) + fileName = filePath + match.Value.Replace("\"", "").Replace("'", ""); + } + File.WriteAllText(fileName, content); + return new FileStream(fileName, FileMode.Open); + + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(content, null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return ConvertType(content, type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(content, type); + } + catch (IOException e) + { + throw new ApiException(500, e.Message); + } + } + + /// + /// Serialize an object into JSON string. + /// + /// Object. + /// JSON string. + public string Serialize(object obj) + { + try + { + return obj != null ? JsonConvert.SerializeObject(obj) : null; + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + /// + /// Get the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix (string apiKeyIdentifier) + { + var apiKeyValue = ""; + Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); + var apiKeyPrefix = ""; + if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) + return apiKeyPrefix + " " + apiKeyValue; + else + return apiKeyValue; + } + + /// + /// Update parameters based on authentication. + /// + /// Query parameters. + /// Header parameters. + /// Authentication settings. + public void UpdateParamsForAuth(Dictionary queryParams, Dictionary headerParams, string[] authSettings) + { + if (authSettings == null || authSettings.Length == 0) + return; + + foreach (string auth in authSettings) + { + // determine which one to use + switch(auth) + { + + case "api_key": + headerParams["api_key"] = GetApiKeyWithPrefix("api_key"); + + break; + + case "petstore_auth": + + //TODO support oauth + break; + + default: + //TODO show warning about security definition not found + break; + } + } + } + + /// + /// Encode string in base64 format. + /// + /// String to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + var textByte = System.Text.Encoding.UTF8.GetBytes(text); + return System.Convert.ToBase64String(textByte); + } + + /// + /// Dynamically cast the object into target type. + /// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast + /// + /// Object to be casted + /// Target type + /// Casted object + public static Object ConvertType(Object source, Type dest) { + return Convert.ChangeType(source, dest); + } + + } +} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiException.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiException.cs new file mode 100644 index 00000000000..ff0b4be791e --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiException.cs @@ -0,0 +1,48 @@ +using System; + +namespace IO.Swagger.Client { + /// + /// API Exception + /// + public class ApiException : Exception { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public Object ErrorContent { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The base path. + public ApiException() {} + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + public ApiException(int errorCode, string message, Object errorContent = null) : base(message) { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + } + + } + +} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/Configuration.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/Configuration.cs new file mode 100644 index 00000000000..80df0f4ec72 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/Configuration.cs @@ -0,0 +1,99 @@ +using System; +using System.Reflection; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace IO.Swagger.Client +{ + /// + /// Represents a set of configuration settings + /// + public class Configuration + { + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "1.0.0"; + + /// + /// Gets or sets the default API client for making HTTP calls. + /// + /// The API client. + public static ApiClient DefaultApiClient = new ApiClient(); + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public static String Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public static String Password { get; set; } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public static Dictionary ApiKey = new Dictionary(); + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + public static Dictionary ApiKeyPrefix = new Dictionary(); + + private static string _tempFolderPath = Path.GetTempPath(); + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public static String TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (String.IsNullOrEmpty(value)) + { + _tempFolderPath = value; + return; + } + + // create the directory if it does not exist + if (!Directory.Exists(value)) + Directory.CreateDirectory(value); + + // check if the path contains directory separator at the end + if (value[value.Length - 1] == Path.DirectorySeparatorChar) + _tempFolderPath = value; + else + _tempFolderPath = value + Path.DirectorySeparatorChar; + } + } + + /// + /// Returns a string with essential information for debugging. + /// + public static String ToDebugReport() + { + String report = "C# SDK (IO.Swagger) Debug Report:\n"; + report += " OS: " + Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + Assembly + .GetExecutingAssembly() + .GetReferencedAssemblies() + .Where(x => x.Name == "System.Core").First().Version.ToString() + "\n"; + report += " Version of the API: 1.0.0\n"; + report += " SDK Package Version: 1.0.0\n"; + + return report; + } + } +} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Category.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Category.cs new file mode 100644 index 00000000000..a11c0761d2d --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Category.cs @@ -0,0 +1,58 @@ +using System; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.Serialization; +using Newtonsoft.Json; + +namespace IO.Swagger.Model { + + /// + /// + /// + [DataContract] + public class Category { + + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + + /// + /// Gets or Sets Name + /// + [DataMember(Name="name", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class Category {\n"); + + sb.Append(" Id: ").Append(Id).Append("\n"); + + sb.Append(" Name: ").Append(Name).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} +} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Order.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Order.cs new file mode 100644 index 00000000000..17890990aa6 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Order.cs @@ -0,0 +1,99 @@ +using System; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.Serialization; +using Newtonsoft.Json; + +namespace IO.Swagger.Model { + + /// + /// + /// + [DataContract] + public class Order { + + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + + /// + /// Gets or Sets PetId + /// + [DataMember(Name="petId", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "petId")] + public long? PetId { get; set; } + + + /// + /// Gets or Sets Quantity + /// + [DataMember(Name="quantity", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "quantity")] + public int? Quantity { get; set; } + + + /// + /// Gets or Sets ShipDate + /// + [DataMember(Name="shipDate", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "shipDate")] + public DateTime? ShipDate { get; set; } + + + /// + /// Order Status + /// + /// Order Status + [DataMember(Name="status", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "status")] + public string Status { get; set; } + + + /// + /// Gets or Sets Complete + /// + [DataMember(Name="complete", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "complete")] + public bool? Complete { get; set; } + + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class Order {\n"); + + sb.Append(" Id: ").Append(Id).Append("\n"); + + sb.Append(" PetId: ").Append(PetId).Append("\n"); + + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + + sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); + + sb.Append(" Status: ").Append(Status).Append("\n"); + + sb.Append(" Complete: ").Append(Complete).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} +} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Pet.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Pet.cs new file mode 100644 index 00000000000..14f285794ad --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Pet.cs @@ -0,0 +1,99 @@ +using System; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.Serialization; +using Newtonsoft.Json; + +namespace IO.Swagger.Model { + + /// + /// + /// + [DataContract] + public class Pet { + + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + + /// + /// Gets or Sets Category + /// + [DataMember(Name="category", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "category")] + public Category Category { get; set; } + + + /// + /// Gets or Sets Name + /// + [DataMember(Name="name", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + + /// + /// Gets or Sets PhotoUrls + /// + [DataMember(Name="photoUrls", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "photoUrls")] + public List PhotoUrls { get; set; } + + + /// + /// Gets or Sets Tags + /// + [DataMember(Name="tags", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "tags")] + public List Tags { get; set; } + + + /// + /// pet status in the store + /// + /// pet status in the store + [DataMember(Name="status", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "status")] + public string Status { get; set; } + + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class Pet {\n"); + + sb.Append(" Id: ").Append(Id).Append("\n"); + + sb.Append(" Category: ").Append(Category).Append("\n"); + + sb.Append(" Name: ").Append(Name).Append("\n"); + + sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + + sb.Append(" Tags: ").Append(Tags).Append("\n"); + + sb.Append(" Status: ").Append(Status).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} +} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Tag.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Tag.cs new file mode 100644 index 00000000000..9a784e07a7e --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Tag.cs @@ -0,0 +1,58 @@ +using System; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.Serialization; +using Newtonsoft.Json; + +namespace IO.Swagger.Model { + + /// + /// + /// + [DataContract] + public class Tag { + + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + + /// + /// Gets or Sets Name + /// + [DataMember(Name="name", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class Tag {\n"); + + sb.Append(" Id: ").Append(Id).Append("\n"); + + sb.Append(" Name: ").Append(Name).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} +} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/User.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/User.cs new file mode 100644 index 00000000000..ee7d6b035a3 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/User.cs @@ -0,0 +1,119 @@ +using System; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.Serialization; +using Newtonsoft.Json; + +namespace IO.Swagger.Model { + + /// + /// + /// + [DataContract] + public class User { + + /// + /// Gets or Sets Id + /// + [DataMember(Name="id", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "id")] + public long? Id { get; set; } + + + /// + /// Gets or Sets Username + /// + [DataMember(Name="username", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "username")] + public string Username { get; set; } + + + /// + /// Gets or Sets FirstName + /// + [DataMember(Name="firstName", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "firstName")] + public string FirstName { get; set; } + + + /// + /// Gets or Sets LastName + /// + [DataMember(Name="lastName", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "lastName")] + public string LastName { get; set; } + + + /// + /// Gets or Sets Email + /// + [DataMember(Name="email", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "email")] + public string Email { get; set; } + + + /// + /// Gets or Sets Password + /// + [DataMember(Name="password", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "password")] + public string Password { get; set; } + + + /// + /// Gets or Sets Phone + /// + [DataMember(Name="phone", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "phone")] + public string Phone { get; set; } + + + /// + /// User Status + /// + /// User Status + [DataMember(Name="userStatus", EmitDefaultValue=false)] + [JsonProperty(PropertyName = "userStatus")] + public int? UserStatus { get; set; } + + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class User {\n"); + + sb.Append(" Id: ").Append(Id).Append("\n"); + + sb.Append(" Username: ").Append(Username).Append("\n"); + + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + + sb.Append(" LastName: ").Append(LastName).Append("\n"); + + sb.Append(" Email: ").Append(Email).Append("\n"); + + sb.Append(" Password: ").Append(Password).Append("\n"); + + sb.Append(" Phone: ").Append(Phone).Append("\n"); + + sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} +} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/vendor/packages.config b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/vendor/packages.config new file mode 100644 index 00000000000..7b9cf186303 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/vendor/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs index 166d40b5656..9f3bb5501b5 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs @@ -102,18 +102,18 @@ namespace IO.Swagger.Api /// /// Deletes a pet /// - /// /// Pet id to delete + /// /// - void DeletePet (string apiKey, long? petId); + void DeletePet (long? petId, string apiKey); /// /// Deletes a pet /// - /// /// Pet id to delete + /// /// - System.Threading.Tasks.Task DeletePetAsync (string apiKey, long? petId); + System.Threading.Tasks.Task DeletePetAsync (long? petId, string apiKey); /// /// uploads an image @@ -199,15 +199,16 @@ namespace IO.Swagger.Api var path = "/pet"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + @@ -218,7 +219,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content, response.Content); @@ -238,15 +239,16 @@ namespace IO.Swagger.Api var path = "/pet"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + @@ -257,7 +259,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content, response.Content); @@ -275,15 +277,16 @@ namespace IO.Swagger.Api var path = "/pet"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + @@ -294,7 +297,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content, response.Content); @@ -314,15 +317,16 @@ namespace IO.Swagger.Api var path = "/pet"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + @@ -333,7 +337,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content, response.Content); @@ -351,16 +355,17 @@ namespace IO.Swagger.Api var path = "/pet/findByStatus"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - - if (status != null) queryParams.Add("status", ApiClient.ParameterToString(status)); // query parameter + + pathParams.Add("format", "json"); + + if (status != null) queryParams.Add("status", ApiClient.ParameterToString(status)); // query parameter @@ -370,7 +375,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); @@ -390,16 +395,17 @@ namespace IO.Swagger.Api var path = "/pet/findByStatus"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - if (status != null) queryParams.Add("status", ApiClient.ParameterToString(status)); // query parameter + pathParams.Add("format", "json"); + + if (status != null) queryParams.Add("status", ApiClient.ParameterToString(status)); // query parameter @@ -409,7 +415,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); @@ -426,16 +432,17 @@ namespace IO.Swagger.Api var path = "/pet/findByTags"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - - if (tags != null) queryParams.Add("tags", ApiClient.ParameterToString(tags)); // query parameter + + pathParams.Add("format", "json"); + + if (tags != null) queryParams.Add("tags", ApiClient.ParameterToString(tags)); // query parameter @@ -445,7 +452,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); @@ -465,16 +472,17 @@ namespace IO.Swagger.Api var path = "/pet/findByTags"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - if (tags != null) queryParams.Add("tags", ApiClient.ParameterToString(tags)); // query parameter + pathParams.Add("format", "json"); + + if (tags != null) queryParams.Add("tags", ApiClient.ParameterToString(tags)); // query parameter @@ -484,7 +492,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); @@ -504,16 +512,17 @@ namespace IO.Swagger.Api var path = "/pet/{petId}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + @@ -523,7 +532,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "api_key", "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content, response.Content); @@ -545,16 +554,17 @@ namespace IO.Swagger.Api var path = "/pet/{petId}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + @@ -564,7 +574,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "api_key", "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content, response.Content); @@ -586,16 +596,17 @@ namespace IO.Swagger.Api var path = "/pet/{petId}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (name != null) formParams.Add("name", ApiClient.ParameterToString(name)); // form parameter @@ -607,7 +618,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); @@ -631,16 +642,17 @@ namespace IO.Swagger.Api var path = "/pet/{petId}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (name != null) formParams.Add("name", ApiClient.ParameterToString(name)); // form parameter @@ -652,7 +664,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); @@ -663,10 +675,10 @@ namespace IO.Swagger.Api /// /// Deletes a pet /// - /// /// Pet id to delete + /// /// - public void DeletePet (string apiKey, long? petId) + public void DeletePet (long? petId, string apiKey) { // verify the required parameter 'petId' is set @@ -674,18 +686,19 @@ namespace IO.Swagger.Api var path = "/pet/{petId}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter - if (apiKey != null) headerParams.Add("api_key", ApiClient.ParameterToString(apiKey)); // header parameter + + if (apiKey != null) headerParams.Add("api_key", ApiClient.ParameterToString(apiKey)); // header parameter @@ -694,7 +707,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content, response.Content); @@ -707,28 +720,29 @@ namespace IO.Swagger.Api /// /// Deletes a pet /// - /// /// Pet id to delete + /// /// - public async System.Threading.Tasks.Task DeletePetAsync (string apiKey, long? petId) + public async System.Threading.Tasks.Task DeletePetAsync (long? petId, string apiKey) { // verify the required parameter 'petId' is set if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling DeletePet"); var path = "/pet/{petId}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter - if (apiKey != null) headerParams.Add("api_key", ApiClient.ParameterToString(apiKey)); // header parameter + + if (apiKey != null) headerParams.Add("api_key", ApiClient.ParameterToString(apiKey)); // header parameter @@ -737,7 +751,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content, response.Content); @@ -760,16 +774,17 @@ namespace IO.Swagger.Api var path = "/pet/{petId}/uploadImage"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (additionalMetadata != null) formParams.Add("additionalMetadata", ApiClient.ParameterToString(additionalMetadata)); // form parameter @@ -781,7 +796,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content, response.Content); @@ -805,16 +820,17 @@ namespace IO.Swagger.Api var path = "/pet/{petId}/uploadImage"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "petId" + "}", ApiClient.ParameterToString(petId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter + if (additionalMetadata != null) formParams.Add("additionalMetadata", ApiClient.ParameterToString(additionalMetadata)); // form parameter @@ -826,7 +842,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content, response.Content); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs index 74d14e7ffe2..6dfd81bd99d 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs @@ -130,15 +130,16 @@ namespace IO.Swagger.Api var path = "/store/inventory"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + @@ -148,7 +149,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "api_key" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); @@ -167,15 +168,16 @@ namespace IO.Swagger.Api var path = "/store/inventory"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + @@ -185,7 +187,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "api_key" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); @@ -202,15 +204,16 @@ namespace IO.Swagger.Api var path = "/store/order"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + @@ -221,7 +224,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); @@ -241,15 +244,16 @@ namespace IO.Swagger.Api var path = "/store/order"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + @@ -260,7 +264,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); @@ -280,16 +284,17 @@ namespace IO.Swagger.Api var path = "/store/order/{orderId}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter + @@ -299,7 +304,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); @@ -321,16 +326,17 @@ namespace IO.Swagger.Api var path = "/store/order/{orderId}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter + @@ -340,7 +346,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); @@ -360,16 +366,17 @@ namespace IO.Swagger.Api var path = "/store/order/{orderId}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter + @@ -379,7 +386,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); @@ -401,16 +408,17 @@ namespace IO.Swagger.Api var path = "/store/order/{orderId}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "orderId" + "}", ApiClient.ParameterToString(orderId)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter + @@ -420,7 +428,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs index b69bd7be58b..1ca200137a2 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs @@ -191,15 +191,16 @@ namespace IO.Swagger.Api var path = "/user"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + @@ -210,7 +211,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content, response.Content); @@ -230,15 +231,16 @@ namespace IO.Swagger.Api var path = "/user"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + @@ -249,7 +251,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content, response.Content); @@ -267,15 +269,16 @@ namespace IO.Swagger.Api var path = "/user/createWithArray"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + @@ -286,7 +289,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); @@ -306,15 +309,16 @@ namespace IO.Swagger.Api var path = "/user/createWithArray"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + @@ -325,7 +329,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); @@ -343,15 +347,16 @@ namespace IO.Swagger.Api var path = "/user/createWithList"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + @@ -362,7 +367,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); @@ -382,15 +387,16 @@ namespace IO.Swagger.Api var path = "/user/createWithList"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + @@ -401,7 +407,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); @@ -420,17 +426,18 @@ namespace IO.Swagger.Api var path = "/user/login"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - - if (username != null) queryParams.Add("username", ApiClient.ParameterToString(username)); // query parameter - if (password != null) queryParams.Add("password", ApiClient.ParameterToString(password)); // query parameter + + pathParams.Add("format", "json"); + + if (username != null) queryParams.Add("username", ApiClient.ParameterToString(username)); // query parameter + if (password != null) queryParams.Add("password", ApiClient.ParameterToString(password)); // query parameter @@ -440,7 +447,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content, response.Content); @@ -461,17 +468,18 @@ namespace IO.Swagger.Api var path = "/user/login"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - if (username != null) queryParams.Add("username", ApiClient.ParameterToString(username)); // query parameter - if (password != null) queryParams.Add("password", ApiClient.ParameterToString(password)); // query parameter + pathParams.Add("format", "json"); + + if (username != null) queryParams.Add("username", ApiClient.ParameterToString(username)); // query parameter + if (password != null) queryParams.Add("password", ApiClient.ParameterToString(password)); // query parameter @@ -481,7 +489,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content, response.Content); @@ -497,15 +505,16 @@ namespace IO.Swagger.Api var path = "/user/logout"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + @@ -515,7 +524,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content, response.Content); @@ -534,15 +543,16 @@ namespace IO.Swagger.Api var path = "/user/logout"; - path = path.Replace("{format}", "json"); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + @@ -552,7 +562,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content, response.Content); @@ -573,16 +583,17 @@ namespace IO.Swagger.Api var path = "/user/{username}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "username" + "}", ApiClient.ParameterToString(username)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + @@ -592,7 +603,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content, response.Content); @@ -614,16 +625,17 @@ namespace IO.Swagger.Api var path = "/user/{username}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "username" + "}", ApiClient.ParameterToString(username)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + @@ -633,7 +645,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content, response.Content); @@ -654,16 +666,17 @@ namespace IO.Swagger.Api var path = "/user/{username}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "username" + "}", ApiClient.ParameterToString(username)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + @@ -674,7 +687,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content, response.Content); @@ -697,16 +710,17 @@ namespace IO.Swagger.Api var path = "/user/{username}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "username" + "}", ApiClient.ParameterToString(username)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + @@ -717,7 +731,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content, response.Content); @@ -738,16 +752,17 @@ namespace IO.Swagger.Api var path = "/user/{username}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "username" + "}", ApiClient.ParameterToString(username)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + pathParams.Add("format", "json"); + if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + @@ -757,7 +772,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content, response.Content); @@ -779,16 +794,17 @@ namespace IO.Swagger.Api var path = "/user/{username}"; - path = path.Replace("{format}", "json"); - path = path.Replace("{" + "username" + "}", ApiClient.ParameterToString(username)); - + var pathParams = new Dictionary(); var queryParams = new Dictionary(); var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; + pathParams.Add("format", "json"); + if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter + @@ -798,7 +814,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content, response.Content); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs index 117cd598008..9041bbf42f0 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs @@ -50,23 +50,12 @@ namespace IO.Swagger.Client get { return _defaultHeaderMap; } } - /// - /// Makes the HTTP request (Sync). - /// - /// URL path. - /// HTTP method. - /// Query parameters. - /// HTTP body (POST request). - /// Header parameters. - /// Form parameters. - /// File parameters. - /// Authentication settings. - /// Object - public Object CallApi(String path, RestSharp.Method method, Dictionary queryParams, String postBody, - Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, String[] authSettings) + // Creates and sets up a RestRequest prior to a call. + private RestRequest PrepareRequest( + String path, RestSharp.Method method, Dictionary queryParams, String postBody, + Dictionary headerParams, Dictionary formParams, + Dictionary fileParams, Dictionary pathParams, String[] authSettings) { - var request = new RestRequest(path, method); UpdateParamsForAuth(queryParams, headerParams, authSettings); @@ -75,6 +64,10 @@ namespace IO.Swagger.Client foreach(var defaultHeader in _defaultHeaderMap) request.AddHeader(defaultHeader.Key, defaultHeader.Value); + // add path parameter, if any + foreach(var param in pathParams) + request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); + // add header parameter, if any foreach(var param in headerParams) request.AddHeader(param.Key, param.Value); @@ -93,9 +86,31 @@ namespace IO.Swagger.Client if (postBody != null) // http body (model) parameter request.AddParameter("application/json", postBody, ParameterType.RequestBody); + + return request; + } + /// + /// Makes the HTTP request (Sync). + /// + /// URL path. + /// HTTP method. + /// Query parameters. + /// HTTP body (POST request). + /// Header parameters. + /// Form parameters. + /// File parameters. + /// Path parameters. + /// Authentication settings. + /// Object + public Object CallApi( + String path, RestSharp.Method method, Dictionary queryParams, String postBody, + Dictionary headerParams, Dictionary formParams, + Dictionary fileParams, Dictionary pathParams, String[] authSettings) + { + var request = PrepareRequest( + path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); return (Object)RestClient.Execute(request); - } /// @@ -108,39 +123,16 @@ namespace IO.Swagger.Client /// Header parameters. /// Form parameters. /// File parameters. + /// Path parameters. /// Authentication settings. /// The Task instance. - public async System.Threading.Tasks.Task CallApiAsync(String path, RestSharp.Method method, Dictionary queryParams, String postBody, - Dictionary headerParams, Dictionary formParams, Dictionary fileParams, String[] authSettings) + public async System.Threading.Tasks.Task CallApiAsync( + String path, RestSharp.Method method, Dictionary queryParams, String postBody, + Dictionary headerParams, Dictionary formParams, + Dictionary fileParams, Dictionary pathParams, String[] authSettings) { - - var request = new RestRequest(path, method); - - UpdateParamsForAuth(queryParams, headerParams, authSettings); - - // add default header, if any - foreach(var defaultHeader in _defaultHeaderMap) - request.AddHeader(defaultHeader.Key, defaultHeader.Value); - - // add header parameter, if any - foreach(var param in headerParams) - request.AddHeader(param.Key, param.Value); - - // add query parameter, if any - foreach(var param in queryParams) - request.AddQueryParameter(param.Key, param.Value); - - // add form parameter, if any - foreach(var param in formParams) - request.AddParameter(param.Key, param.Value); - - // add file parameter, if any - foreach(var param in fileParams) - request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); - - if (postBody != null) // http body (model) parameter - request.AddParameter("application/json", postBody, ParameterType.RequestBody); - + var request = PrepareRequest( + path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); return (Object) await RestClient.ExecuteTaskAsync(request); } @@ -162,7 +154,7 @@ namespace IO.Swagger.Client /// Escaped string. public string EscapeString(string str) { - return HttpUtility.UrlEncode(str); + return RestSharp.Contrib.HttpUtility.UrlEncode(str); } /// @@ -243,7 +235,7 @@ namespace IO.Swagger.Client { return JsonConvert.DeserializeObject(content, type); } - catch (IOException e) + catch (Exception e) { throw new ApiException(500, e.Message); } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs index 509243bbdfc..3839afecb77 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -2,7 +2,7 @@ - + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs index 33530cb0b99..98326a63ae7 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs @@ -45,7 +45,7 @@ namespace SwaggerClient.TestPet { // remove the pet after testing PetApi petApi = new PetApi (); - petApi.DeletePet("test key", petId); + petApi.DeletePet(petId, "test key"); } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll index 9fd1a6e805a..0fa7c24ab8a 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb index 0e1d0d209c3..1830197d9e7 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll index 9fd1a6e805a..0fa7c24ab8a 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb index 0e1d0d209c3..1830197d9e7 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/flash/FlashPetstoreCodegen.scala b/samples/client/petstore/flash/FlashPetstoreCodegen.scala deleted file mode 100644 index e318765c57e..00000000000 --- a/samples/client/petstore/flash/FlashPetstoreCodegen.scala +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -object FlashPetstoreCodegen extends BasicFlashCodegen { - def main(args: Array[String]) = generateClient(args) - - override def packageName = "io.swagger.client" - - // where to write generated code - override def destinationDir = destinationRoot + "/src/main/flex" - - override def destinationRoot = "samples/client/petstore/flash" - - // package for models - override def modelPackage = Some("com.wordnik.client.model") - - // package for api classes - override def apiPackage = Some("com.wordnik.client.api") - - // supporting classes - override def supportingFiles = baseSupportingFiles ++ List() -} diff --git a/samples/client/petstore/flash/bin/AirExecutorApp-app.xml b/samples/client/petstore/flash/bin/AirExecutorApp-app.xml deleted file mode 100644 index 1eb5e43c7d7..00000000000 --- a/samples/client/petstore/flash/bin/AirExecutorApp-app.xml +++ /dev/null @@ -1,146 +0,0 @@ - - - - - - - AirExecutorApp - - - AirExecutorApp - - - AirExecutorApp - - - v1 - - - - - - - - - - - - - - - AirExecutorApp.swf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/client/petstore/flash/src/main/flex/bin/AirExecutorApp-app.xml b/samples/client/petstore/flash/src/main/flex/bin/AirExecutorApp-app.xml new file mode 100644 index 00000000000..1dbaf98e644 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/bin/AirExecutorApp-app.xml @@ -0,0 +1,146 @@ + + + + + + + AirExecutorApp + + + AirExecutorApp + + + AirExecutorApp + + + v1 + + + + + + + + + + + + + + + AirExecutorApp.swf + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/flash/build.properties b/samples/client/petstore/flash/src/main/flex/build.properties similarity index 100% rename from samples/client/petstore/flash/build.properties rename to samples/client/petstore/flash/src/main/flex/build.properties diff --git a/samples/client/petstore/flash/build.xml b/samples/client/petstore/flash/src/main/flex/build.xml similarity index 89% rename from samples/client/petstore/flash/build.xml rename to samples/client/petstore/flash/src/main/flex/build.xml index 6861dd464ec..4f021b0b8b2 100644 --- a/samples/client/petstore/flash/build.xml +++ b/samples/client/petstore/flash/src/main/flex/build.xml @@ -62,11 +62,11 @@ - - - - - + + + + + diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/PetApi.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/PetApi.as deleted file mode 100644 index 88f9b42eaa0..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/PetApi.as +++ /dev/null @@ -1,272 +0,0 @@ -package com.wordnik.client.api { - -import com.wordnik.swagger.common.ApiInvoker; -import com.wordnik.swagger.exception.ApiErrorCodes; -import com.wordnik.swagger.exception.ApiError; -import com.wordnik.swagger.common.ApiUserCredentials; -import com.wordnik.swagger.event.Response; -import com.wordnik.swagger.common.SwaggerApi; -import com.wordnik.client.model.Pet; -import com.wordnik.client.model.File; - -import mx.rpc.AsyncToken; -import mx.utils.UIDUtil; - -import flash.utils.Dictionary; -import flash.events.EventDispatcher; - -public class PetApi extends SwaggerApi { - public static const event_getPetById:String = "getPetById"; - public static const event_deletePet:String = "deletePet"; - public static const event_partialUpdate:String = "partialUpdate"; - public static const event_updatePetWithForm:String = "updatePetWithForm"; - public static const event_uploadFile:String = "uploadFile"; - public static const event_addPet:String = "addPet"; - public static const event_updatePet:String = "updatePet"; - public static const event_findPetsByStatus:String = "findPetsByStatus"; - public static const event_findPetsByTags:String = "findPetsByTags"; - - /** - * Constructor for the PetApi api client - * @param apiCredentials Wrapper object for tokens and hostName required towards authentication - * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response - */ - public function PetApi(apiCredentials:ApiUserCredentials, eventDispatcher:EventDispatcher = null) { - super(apiCredentials, eventDispatcher); - } - /* - * Returns Pet */ - - public function getPetById(petId:Number):String { - // create path and map variables - var path:String = "/pet/{petId}".replace(/{format}/g, "xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (petId == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "getPetById"; - - token.returnType = Pet; - return requestId; - - } - - /* - * Returns void */ - public function deletePet(petId:String):String { - // create path and map variables - var path:String = "/pet/{petId}".replace(/{format}/g, "xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (petId == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "DELETE", queryParams, null, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "deletePet"; - - token.returnType = null; - return requestId; - - } - - /* - * Returns Array[Pet] */ - public function partialUpdate(petId:String, body:Pet):String { - // create path and map variables - var path:String = "/pet/{petId}".replace(/{format}/g, "xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (petId == null || body == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "PATCH", queryParams, body, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "partialUpdate"; - - token.returnType = Array[Pet]; - return requestId; - - } - - /* - * Returns void */ - public function updatePetWithForm(petId:String, name:String, status:String):String { - // create path and map variables - var path:String = "/pet/{petId}".replace(/{format}/g, "xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (petId == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, null, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "updatePetWithForm"; - - token.returnType = null; - return requestId; - - } - - /* - * Returns void */ - public function uploadFile(additionalMetadata:String, body:File):String { - // create path and map variables - var path:String = "/pet/uploadImage".replace(/{format}/g, "xml"); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "uploadFile"; - - token.returnType = null; - return requestId; - - } - - /* - * Returns void */ - public function addPet(body:Pet):String { - // create path and map variables - var path:String = "/pet".replace(/{format}/g, "xml"); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (body == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "addPet"; - - token.returnType = null; - return requestId; - - } - - /* - * Returns void */ - public function updatePet(body:Pet):String { - // create path and map variables - var path:String = "/pet".replace(/{format}/g, "xml"); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (body == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "PUT", queryParams, body, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "updatePet"; - - token.returnType = null; - return requestId; - - } - - /* - * Returns Array[Pet] */ - public function findPetsByStatus(status:String = "available"):String { - // create path and map variables - var path:String = "/pet/findByStatus".replace(/{format}/g, "xml"); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (status == null) { - throw new ApiError(400, "missing required params"); - } - if ("null" != String(status)) - queryParams["status"] = toPathValue(status); - var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "findPetsByStatus"; - - token.returnType = Array[Pet]; - return requestId; - - } - - /* - * Returns Array[Pet] */ - public function findPetsByTags(tags:String):String { - // create path and map variables - var path:String = "/pet/findByTags".replace(/{format}/g, "xml"); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (tags == null) { - throw new ApiError(400, "missing required params"); - } - if ("null" != String(tags)) - queryParams["tags"] = toPathValue(tags); - var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "findPetsByTags"; - - token.returnType = Array[Pet]; - return requestId; - - } -} -} diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/StoreApi.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/StoreApi.as deleted file mode 100644 index cc4bc2c4a13..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/StoreApi.as +++ /dev/null @@ -1,109 +0,0 @@ -package com.wordnik.client.api { - -import com.wordnik.swagger.common.ApiInvoker; -import com.wordnik.swagger.exception.ApiErrorCodes; -import com.wordnik.swagger.exception.ApiError; -import com.wordnik.swagger.common.ApiUserCredentials; -import com.wordnik.swagger.event.Response; -import com.wordnik.swagger.common.SwaggerApi; -import com.wordnik.client.model.Order; - -import mx.rpc.AsyncToken; -import mx.utils.UIDUtil; - -import flash.utils.Dictionary; -import flash.events.EventDispatcher; - -public class StoreApi extends SwaggerApi { - public static const event_getOrderById:String = "getOrderById"; - public static const event_deleteOrder:String = "deleteOrder"; - public static const event_placeOrder:String = "placeOrder"; - - /** - * Constructor for the StoreApi api client - * @param apiCredentials Wrapper object for tokens and hostName required towards authentication - * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response - */ - public function StoreApi(apiCredentials:ApiUserCredentials, eventDispatcher:EventDispatcher = null) { - super(apiCredentials, eventDispatcher); - } - /* - * Returns Order */ - - public function getOrderById(orderId:String):String { - // create path and map variables - var path:String = "/store/order/{orderId}".replace(/{format}/g, "xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId)); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (orderId == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "getOrderById"; - - token.returnType = Order; - return requestId; - - } - - /* - * Returns void */ - public function deleteOrder(orderId:String):String { - // create path and map variables - var path:String = "/store/order/{orderId}".replace(/{format}/g, "xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId)); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (orderId == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "DELETE", queryParams, null, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "deleteOrder"; - - token.returnType = null; - return requestId; - - } - - /* - * Returns void */ - public function placeOrder(body:Order):String { - // create path and map variables - var path:String = "/store/order".replace(/{format}/g, "xml"); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (body == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "placeOrder"; - - token.returnType = null; - return requestId; - - } -} -} diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/UserApi.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/UserApi.as deleted file mode 100644 index 1714b4a0381..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/UserApi.as +++ /dev/null @@ -1,244 +0,0 @@ -package com.wordnik.client.api { - -import com.wordnik.swagger.common.ApiInvoker; -import com.wordnik.swagger.exception.ApiErrorCodes; -import com.wordnik.swagger.exception.ApiError; -import com.wordnik.swagger.common.ApiUserCredentials; -import com.wordnik.swagger.event.Response; -import com.wordnik.swagger.common.SwaggerApi; -import com.wordnik.client.model.User; - -import mx.rpc.AsyncToken; -import mx.utils.UIDUtil; - -import flash.utils.Dictionary; -import flash.events.EventDispatcher; - -public class UserApi extends SwaggerApi { - public static const event_updateUser:String = "updateUser"; - public static const event_deleteUser:String = "deleteUser"; - public static const event_getUserByName:String = "getUserByName"; - public static const event_loginUser:String = "loginUser"; - public static const event_logoutUser:String = "logoutUser"; - public static const event_createUser:String = "createUser"; - public static const event_createUsersWithArrayInput:String = "createUsersWithArrayInput"; - public static const event_createUsersWithListInput:String = "createUsersWithListInput"; - - /** - * Constructor for the UserApi api client - * @param apiCredentials Wrapper object for tokens and hostName required towards authentication - * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response - */ - public function UserApi(apiCredentials:ApiUserCredentials, eventDispatcher:EventDispatcher = null) { - super(apiCredentials, eventDispatcher); - } - /* - * Returns void */ - - public function updateUser(username:String, body:User):String { - // create path and map variables - var path:String = "/user/{username}".replace(/{format}/g, "xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (username == null || body == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "PUT", queryParams, body, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "updateUser"; - - token.returnType = null; - return requestId; - - } - - /* - * Returns void */ - public function deleteUser(username:String):String { - // create path and map variables - var path:String = "/user/{username}".replace(/{format}/g, "xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (username == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "DELETE", queryParams, null, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "deleteUser"; - - token.returnType = null; - return requestId; - - } - - /* - * Returns User */ - public function getUserByName(username:String):String { - // create path and map variables - var path:String = "/user/{username}".replace(/{format}/g, "xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (username == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "getUserByName"; - - token.returnType = User; - return requestId; - - } - - /* - * Returns string */ - public function loginUser(username:String, password:String):String { - // create path and map variables - var path:String = "/user/login".replace(/{format}/g, "xml"); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (username == null || password == null) { - throw new ApiError(400, "missing required params"); - } - if ("null" != String(username)) - queryParams["username"] = toPathValue(username); - if ("null" != String(password)) - queryParams["password"] = toPathValue(password); - var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "loginUser"; - - token.returnType = string; - return requestId; - - } - - /* - * Returns void */ - public function logoutUser():String { - // create path and map variables - var path:String = "/user/logout".replace(/{format}/g, "xml"); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "logoutUser"; - - token.returnType = null; - return requestId; - - } - - /* - * Returns void */ - public function createUser(body:User):String { - // create path and map variables - var path:String = "/user".replace(/{format}/g, "xml"); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (body == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "createUser"; - - token.returnType = null; - return requestId; - - } - - /* - * Returns void */ - public function createUsersWithArrayInput(body:Array):String { - // create path and map variables - var path:String = "/user/createWithArray".replace(/{format}/g, "xml"); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (body == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "createUsersWithArrayInput"; - - token.returnType = null; - return requestId; - - } - - /* - * Returns void */ - public function createUsersWithListInput(body:Array):String { - // create path and map variables - var path:String = "/user/createWithList".replace(/{format}/g, "xml"); - - // query params - var queryParams:Dictionary = new Dictionary(); - var headerParams:Dictionary = new Dictionary(); - - // verify required params are set - if (body == null) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); - - var requestId:String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "createUsersWithListInput"; - - token.returnType = null; - return requestId; - - } -} -} diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Category.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Category.as deleted file mode 100644 index e20d3701cf7..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Category.as +++ /dev/null @@ -1,21 +0,0 @@ -package com.wordnik.client.model { - -[XmlRootNode(name="Category")] -public class Category { - [XmlElement(name="id")] - public var id:Number = 0.0; - - [XmlElement(name="name")] - public var name:String = null; - - public function toString():String { - var str:String = "Category: "; - str += " (id: " + id + ")"; - str += " (name: " + name + ")"; - return str; - } - - -} -} - diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/CategoryList.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/CategoryList.as deleted file mode 100644 index 48b18dbe1f4..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/CategoryList.as +++ /dev/null @@ -1,17 +0,0 @@ -package com.wordnik.client.model { - -import com.wordnik.swagger.common.ListWrapper; - -public class CategoryList implements ListWrapper { - // This declaration below of _Category_obj_class is to force flash compiler to include this class - [XmlElements(name="category", type="com.wordnik.client.model.Category")] - public var category:Array = new Array(); - private var _category_obj_class:com.wordnik.client.model.Category = null; - - public function getList():Array { - return category; - } - -} -} - diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Order.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Order.as deleted file mode 100644 index 5147a428ba5..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Order.as +++ /dev/null @@ -1,34 +0,0 @@ -package com.wordnik.client.model { - -[XmlRootNode(name="Order")] -public class Order { - [XmlElement(name="id")] - public var id:Number = 0.0; - - [XmlElement(name="petId")] - public var petId:Number = 0.0; - - [XmlElement(name="quantity")] - public var quantity:Number = 0.0; - - /* Order Status */ - [XmlElement(name="status")] - public var status:String = null; - - [XmlElement(name="shipDate")] - public var shipDate:Date = null; - - public function toString():String { - var str:String = "Order: "; - str += " (id: " + id + ")"; - str += " (petId: " + petId + ")"; - str += " (quantity: " + quantity + ")"; - str += " (status: " + status + ")"; - str += " (shipDate: " + shipDate + ")"; - return str; - } - - -} -} - diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/OrderList.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/OrderList.as deleted file mode 100644 index 56825295dd8..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/OrderList.as +++ /dev/null @@ -1,17 +0,0 @@ -package com.wordnik.client.model { - -import com.wordnik.swagger.common.ListWrapper; - -public class OrderList implements ListWrapper { - // This declaration below of _Order_obj_class is to force flash compiler to include this class - [XmlElements(name="order", type="com.wordnik.client.model.Order")] - public var order:Array = new Array(); - private var _order_obj_class:com.wordnik.client.model.Order = null; - - public function getList():Array { - return order; - } - -} -} - diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Pet.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Pet.as deleted file mode 100644 index 4a19692e9f1..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Pet.as +++ /dev/null @@ -1,48 +0,0 @@ -package com.wordnik.client.model { - -import com.wordnik.client.model.Category; -import com.wordnik.client.model.Tag; - -[XmlRootNode(name="Pet")] -public class Pet { - /* unique identifier for the pet */ - [XmlElement(name="id")] - public var id:Number = 0.0; - - [XmlElement(name="category")] - public var category:Category = null; - - [XmlElement(name="name")] - public var name:String = null; - - // This declaration below of _photoUrls_obj_class is to force flash compiler to include this class - [XmlElementWrapper(name="photoUrls")] - [XmlElements(name="photoUrl", type="com.wordnik.client.model.String")] - public var photoUrls:Array = new Array(); - [XmlElementWrapper(name="tags")] - [XmlElements(name="tag", type="com.wordnik.client.model.Tag")] - public var tags:Array = new Array(); - - // This declaration below of _tags_obj_class is to force flash compiler to include this class - [XmlElement(name="status")] - public var status:String = null; - private var _photoUrls_obj_class:com.wordnik.client.model.String = null; - - /* pet status in the store */ - private var _tags_obj_class:com.wordnik.client.model.Tag = null; - - public function toString():String { - var str:String = "Pet: "; - str += " (id: " + id + ")"; - str += " (category: " + category + ")"; - str += " (name: " + name + ")"; - str += " (photoUrls: " + photoUrls + ")"; - str += " (tags: " + tags + ")"; - str += " (status: " + status + ")"; - return str; - } - - -} -} - diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/PetList.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/PetList.as deleted file mode 100644 index 61b4070a543..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/PetList.as +++ /dev/null @@ -1,19 +0,0 @@ -package com.wordnik.client.model { - -import com.wordnik.swagger.common.ListWrapper; -import com.wordnik.client.model.Category; -import com.wordnik.client.model.Tag; - -public class PetList implements ListWrapper { - // This declaration below of _Pet_obj_class is to force flash compiler to include this class - [XmlElements(name="pet", type="com.wordnik.client.model.Pet")] - public var pet:Array = new Array(); - private var _pet_obj_class:com.wordnik.client.model.Pet = null; - - public function getList():Array { - return pet; - } - -} -} - diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Tag.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Tag.as deleted file mode 100644 index 07f1f8dd9f3..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Tag.as +++ /dev/null @@ -1,21 +0,0 @@ -package com.wordnik.client.model { - -[XmlRootNode(name="Tag")] -public class Tag { - [XmlElement(name="id")] - public var id:Number = 0.0; - - [XmlElement(name="name")] - public var name:String = null; - - public function toString():String { - var str:String = "Tag: "; - str += " (id: " + id + ")"; - str += " (name: " + name + ")"; - return str; - } - - -} -} - diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/TagList.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/TagList.as deleted file mode 100644 index 92a9f7d71b1..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/TagList.as +++ /dev/null @@ -1,17 +0,0 @@ -package com.wordnik.client.model { - -import com.wordnik.swagger.common.ListWrapper; - -public class TagList implements ListWrapper { - // This declaration below of _Tag_obj_class is to force flash compiler to include this class - [XmlElements(name="tag", type="com.wordnik.client.model.Tag")] - public var tag:Array = new Array(); - private var _tag_obj_class:com.wordnik.client.model.Tag = null; - - public function getList():Array { - return tag; - } - -} -} - diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/User.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/User.as deleted file mode 100644 index d5227f9d28e..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/User.as +++ /dev/null @@ -1,46 +0,0 @@ -package com.wordnik.client.model { - -[XmlRootNode(name="User")] -public class User { - [XmlElement(name="id")] - public var id:Number = 0.0; - - [XmlElement(name="firstName")] - public var firstName:String = null; - - [XmlElement(name="username")] - public var username:String = null; - - [XmlElement(name="lastName")] - public var lastName:String = null; - - [XmlElement(name="email")] - public var email:String = null; - - [XmlElement(name="password")] - public var password:String = null; - - [XmlElement(name="phone")] - public var phone:String = null; - - /* User Status */ - [XmlElement(name="userStatus")] - public var userStatus:Number = 0.0; - - public function toString():String { - var str:String = "User: "; - str += " (id: " + id + ")"; - str += " (firstName: " + firstName + ")"; - str += " (username: " + username + ")"; - str += " (lastName: " + lastName + ")"; - str += " (email: " + email + ")"; - str += " (password: " + password + ")"; - str += " (phone: " + phone + ")"; - str += " (userStatus: " + userStatus + ")"; - return str; - } - - -} -} - diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/UserList.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/UserList.as deleted file mode 100644 index fdaab68ac23..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/UserList.as +++ /dev/null @@ -1,17 +0,0 @@ -package com.wordnik.client.model { - -import com.wordnik.swagger.common.ListWrapper; - -public class UserList implements ListWrapper { - // This declaration below of _User_obj_class is to force flash compiler to include this class - [XmlElements(name="user", type="com.wordnik.client.model.User")] - public var user:Array = new Array(); - private var _user_obj_class:com.wordnik.client.model.User = null; - - public function getList():Array { - return user; - } - -} -} - diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ListWrapper.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ListWrapper.as deleted file mode 100644 index 1dc8ef029fa..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ListWrapper.as +++ /dev/null @@ -1,7 +0,0 @@ -package com.wordnik.swagger.common { -public interface ListWrapper { - - function getList():Array; - -} -} \ No newline at end of file diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/SwaggerApi.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/SwaggerApi.as deleted file mode 100644 index af58870d179..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/SwaggerApi.as +++ /dev/null @@ -1,70 +0,0 @@ -package com.wordnik.swagger.common { -import com.wordnik.swagger.common.ApiUserCredentials; - -import flash.events.EventDispatcher; -import flash.events.IEventDispatcher; - -import mx.utils.UIDUtil; - -public class SwaggerApi extends EventDispatcher { - - /** - * Method for returning the path value - * For a string value an empty value is returned if the value is null - * @param value - * @return - */ - protected static function toPathValue(value:Object):String { - if (value is Array) { - return arrayToPathValue(value as Array); - } - return value == null ? "" : value.toString(); - } - - /** - * Method for returning a path value - * For a list of objects a comma separated string is returned - * @param objects - * @return - */ - protected static function arrayToPathValue(objects:Array):String { - var out:String = ""; - - return objects.join(","); - } - - /** - * Constructor for the api client - * @param apiCredentials Wrapper object for tokens and hostName required towards authentication - * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response - */ - public function SwaggerApi(apiCredentials:ApiUserCredentials, eventDispatcher:EventDispatcher = null) { - super(); - _apiUsageCredentials = apiCredentials; - _apiEventNotifier = eventDispatcher; - } - protected var _apiUsageCredentials:ApiUserCredentials; - protected var _apiEventNotifier:EventDispatcher; - protected var _apiInvoker:ApiInvoker; - protected var _useProxyServer:Boolean = false; - - public function useProxyServer(value:Boolean, proxyServerUrl:String = null):void { - _useProxyServer = value; - } - - protected function getApiInvoker():ApiInvoker { - if (_apiInvoker == null) { - if (_apiEventNotifier == null) { - _apiEventNotifier = this; - } - _apiInvoker = new ApiInvoker(_apiUsageCredentials, _apiEventNotifier, _useProxyServer); - } - return _apiInvoker; - } - - protected function getUniqueId():String { - return UIDUtil.createUID(); - } - -} -} \ No newline at end of file diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/XMLWriter.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/XMLWriter.as deleted file mode 100644 index 9b575262a31..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/XMLWriter.as +++ /dev/null @@ -1,24 +0,0 @@ -package com.wordnik.swagger.common { -public class XMLWriter { - public function XMLWriter() { - xml = ; - } - public var xml:XML; - - public function reset():void { - xml = new XML(); - } - - public function addProperty(propertyName:String, propertyValue:String):XML { - var xmlProperty:XML = - xmlProperty.setName(propertyName); - xmlProperty.appendChild(propertyValue); - xml.appendChild(xmlProperty); - return xmlProperty; - } - - public function addAttribute(propertyName:String, attribute:String, attributeValue:String):void { - xml.elements(propertyName)[0].@[attribute] = attributeValue; - } -} -} \ No newline at end of file diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/exception/ApiError.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/exception/ApiError.as deleted file mode 100644 index 8f473a0cbf9..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/exception/ApiError.as +++ /dev/null @@ -1,7 +0,0 @@ -package com.wordnik.swagger.exception { -public class ApiError extends Error { - public function ApiError(id:* = 0, message:* = "") { - super(message, id); - } -} -} \ No newline at end of file diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/exception/ApiErrorCodes.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/exception/ApiErrorCodes.as deleted file mode 100644 index 7abb7642f8e..00000000000 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/exception/ApiErrorCodes.as +++ /dev/null @@ -1,32 +0,0 @@ -package com.wordnik.swagger.exception { -public class ApiErrorCodes { - /** - * System exception. - */ - public static const SYSTEM_EXCEPTION:Number = 0; - - /** - * With Arguments as current key. - */ - public static const API_KEY_NOT_VALID:Number = 1000; - /** - * With arguments as current token value - */ - public static const AUTH_TOKEN_NOT_VALID:Number = 1001; - /** - * With arguments as input JSON and output class anme - */ - public static const ERROR_CONVERTING_JSON_TO_JAVA:Number = 1002; - /** - * With arguments as JAVA class name - */ - public static const ERROR_CONVERTING_JAVA_TO_JSON:Number = 1003; - - public static const ERROR_FROM_WEBSERVICE_CALL:Number = 1004; - /** - * With arguments as current API server name - */ - public static const API_SERVER_NOT_VALID:Number = 1005; - -} -} \ No newline at end of file diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/api/PetApi.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/api/PetApi.as new file mode 100644 index 00000000000..edd1298600f --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/api/PetApi.as @@ -0,0 +1,276 @@ +package io.swagger.client.api { + +import io.swagger.common.ApiInvoker; +import io.swagger.exception.ApiErrorCodes; +import io.swagger.exception.ApiError; +import io.swagger.common.ApiUserCredentials; +import io.swagger.event.Response; +import io.swagger.common.SwaggerApi; +import io.swagger.client.model.Pet; +import flash.filesystem.File; + +import mx.rpc.AsyncToken; +import mx.utils.UIDUtil; +import flash.utils.Dictionary; +import flash.events.EventDispatcher; + +public class PetApi extends SwaggerApi { + /** + * Constructor for the PetApi api client + * @param apiCredentials Wrapper object for tokens and hostName required towards authentication + * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response + */ + public function PetApi(apiCredentials: ApiUserCredentials, eventDispatcher: EventDispatcher = null) { + super(apiCredentials, eventDispatcher); + } + + public static const event_update_pet: String = "update_pet"; + public static const event_add_pet: String = "add_pet"; + public static const event_find_pets_by_status: String = "find_pets_by_status"; + public static const event_find_pets_by_tags: String = "find_pets_by_tags"; + public static const event_get_pet_by_id: String = "get_pet_by_id"; + public static const event_update_pet_with_form: String = "update_pet_with_form"; + public static const event_delete_pet: String = "delete_pet"; + public static const event_upload_file: String = "upload_file"; + + + /* + * Returns void + */ + public function update_pet (body: Pet): String { + // create path and map variables + var path: String = "/pet".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "PUT", queryParams, body, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "update_pet"; + + token.returnType = null ; + return requestId; + + } + + /* + * Returns void + */ + public function add_pet (body: Pet): String { + // create path and map variables + var path: String = "/pet".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "add_pet"; + + token.returnType = null ; + return requestId; + + } + + /* + * Returns Array + */ + public function find_pets_by_status (status: Array = available): String { + // create path and map variables + var path: String = "/pet/findByStatus".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + if("null" != String(status)) + queryParams["status"] = toPathValue(status); + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "find_pets_by_status"; + + token.returnType = Array; + return requestId; + + } + + /* + * Returns Array + */ + public function find_pets_by_tags (tags: Array): String { + // create path and map variables + var path: String = "/pet/findByTags".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + if("null" != String(tags)) + queryParams["tags"] = toPathValue(tags); + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "find_pets_by_tags"; + + token.returnType = Array; + return requestId; + + } + + /* + * Returns Pet + */ + public function get_pet_by_id (petId: Number): String { + // create path and map variables + var path: String = "/pet/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "get_pet_by_id"; + + token.returnType = Pet; + return requestId; + + } + + /* + * Returns void + */ + public function update_pet_with_form (petId: String, name: String, status: String): String { + // create path and map variables + var path: String = "/pet/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "update_pet_with_form"; + + token.returnType = null ; + return requestId; + + } + + /* + * Returns void + */ + public function delete_pet (petId: Number, apiKey: String): String { + // create path and map variables + var path: String = "/pet/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + headerParams["apiKey"] = toPathValue(apiKey); + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "DELETE", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "delete_pet"; + + token.returnType = null ; + return requestId; + + } + + /* + * Returns void + */ + public function upload_file (petId: Number, additionalMetadata: String, file: File): String { + // create path and map variables + var path: String = "/pet/{petId}/uploadImage".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "upload_file"; + + token.returnType = null ; + return requestId; + + } + +} + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/api/StoreApi.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/api/StoreApi.as new file mode 100644 index 00000000000..061878ad257 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/api/StoreApi.as @@ -0,0 +1,150 @@ +package io.swagger.client.api { + +import io.swagger.common.ApiInvoker; +import io.swagger.exception.ApiErrorCodes; +import io.swagger.exception.ApiError; +import io.swagger.common.ApiUserCredentials; +import io.swagger.event.Response; +import io.swagger.common.SwaggerApi; +import io.swagger.client.model.Order; + +import mx.rpc.AsyncToken; +import mx.utils.UIDUtil; +import flash.utils.Dictionary; +import flash.events.EventDispatcher; + +public class StoreApi extends SwaggerApi { + /** + * Constructor for the StoreApi api client + * @param apiCredentials Wrapper object for tokens and hostName required towards authentication + * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response + */ + public function StoreApi(apiCredentials: ApiUserCredentials, eventDispatcher: EventDispatcher = null) { + super(apiCredentials, eventDispatcher); + } + + public static const event_get_inventory: String = "get_inventory"; + public static const event_place_order: String = "place_order"; + public static const event_get_order_by_id: String = "get_order_by_id"; + public static const event_delete_order: String = "delete_order"; + + + /* + * Returns Dictionary + */ + public function get_inventory (): String { + // create path and map variables + var path: String = "/store/inventory".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "get_inventory"; + + token.returnType = Dictionary; + return requestId; + + } + + /* + * Returns Order + */ + public function place_order (body: Order): String { + // create path and map variables + var path: String = "/store/order".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "place_order"; + + token.returnType = Order; + return requestId; + + } + + /* + * Returns Order + */ + public function get_order_by_id (orderId: String): String { + // create path and map variables + var path: String = "/store/order/{orderId}".replace(/{format}/g,"xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "get_order_by_id"; + + token.returnType = Order; + return requestId; + + } + + /* + * Returns void + */ + public function delete_order (orderId: String): String { + // create path and map variables + var path: String = "/store/order/{orderId}".replace(/{format}/g,"xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "DELETE", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "delete_order"; + + token.returnType = null ; + return requestId; + + } + +} + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/api/UserApi.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/api/UserApi.as new file mode 100644 index 00000000000..06b0d079799 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/api/UserApi.as @@ -0,0 +1,274 @@ +package io.swagger.client.api { + +import io.swagger.common.ApiInvoker; +import io.swagger.exception.ApiErrorCodes; +import io.swagger.exception.ApiError; +import io.swagger.common.ApiUserCredentials; +import io.swagger.event.Response; +import io.swagger.common.SwaggerApi; +import io.swagger.client.model.User; + +import mx.rpc.AsyncToken; +import mx.utils.UIDUtil; +import flash.utils.Dictionary; +import flash.events.EventDispatcher; + +public class UserApi extends SwaggerApi { + /** + * Constructor for the UserApi api client + * @param apiCredentials Wrapper object for tokens and hostName required towards authentication + * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response + */ + public function UserApi(apiCredentials: ApiUserCredentials, eventDispatcher: EventDispatcher = null) { + super(apiCredentials, eventDispatcher); + } + + public static const event_create_user: String = "create_user"; + public static const event_create_users_with_array_input: String = "create_users_with_array_input"; + public static const event_create_users_with_list_input: String = "create_users_with_list_input"; + public static const event_login_user: String = "login_user"; + public static const event_logout_user: String = "logout_user"; + public static const event_get_user_by_name: String = "get_user_by_name"; + public static const event_update_user: String = "update_user"; + public static const event_delete_user: String = "delete_user"; + + + /* + * Returns void + */ + public function create_user (body: User): String { + // create path and map variables + var path: String = "/user".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "create_user"; + + token.returnType = null ; + return requestId; + + } + + /* + * Returns void + */ + public function create_users_with_array_input (body: Array): String { + // create path and map variables + var path: String = "/user/createWithArray".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "create_users_with_array_input"; + + token.returnType = null ; + return requestId; + + } + + /* + * Returns void + */ + public function create_users_with_list_input (body: Array): String { + // create path and map variables + var path: String = "/user/createWithList".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "create_users_with_list_input"; + + token.returnType = null ; + return requestId; + + } + + /* + * Returns String + */ + public function login_user (username: String, password: String): String { + // create path and map variables + var path: String = "/user/login".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + if("null" != String(username)) + queryParams["username"] = toPathValue(username); + if("null" != String(password)) + queryParams["password"] = toPathValue(password); + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "login_user"; + + token.returnType = String; + return requestId; + + } + + /* + * Returns void + */ + public function logout_user (): String { + // create path and map variables + var path: String = "/user/logout".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "logout_user"; + + token.returnType = null ; + return requestId; + + } + + /* + * Returns User + */ + public function get_user_by_name (username: String): String { + // create path and map variables + var path: String = "/user/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "GET", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "get_user_by_name"; + + token.returnType = User; + return requestId; + + } + + /* + * Returns void + */ + public function update_user (username: String, body: User): String { + // create path and map variables + var path: String = "/user/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "PUT", queryParams, body, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "update_user"; + + token.returnType = null ; + return requestId; + + } + + /* + * Returns void + */ + public function delete_user (username: String): String { + // create path and map variables + var path: String = "/user/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + + + + + + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "DELETE", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "delete_user"; + + token.returnType = null ; + return requestId; + + } + +} + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Category.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Category.as new file mode 100644 index 00000000000..6aa73414387 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Category.as @@ -0,0 +1,32 @@ +package io.swagger.client.model { + + + [XmlRootNode(name="Category")] + public class Category { + + + + [XmlElement(name="id")] + + public var id: Number = 0; + + + + [XmlElement(name="name")] + + public var name: String = null; + + + public function toString(): String { + var str: String = "Category: "; + + str += " (id: " + id + ")"; + + str += " (name: " + name + ")"; + + return str; + } + +} + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/CategoryList.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/CategoryList.as new file mode 100644 index 00000000000..342cd70c001 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/CategoryList.as @@ -0,0 +1,18 @@ +package io.swagger.client.model { + +import io.swagger.common.ListWrapper; + + public class CategoryList implements ListWrapper { + // This declaration below of _Category_obj_class is to force flash compiler to include this class + private var _category_obj_class: io.swagger.client.model.Category = null; + [XmlElements(name="category", type="io.swagger.client.model.Category")] + public var category: Array = new Array(); + + public function getList(): Array{ + return category; + } + +} + + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Order.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Order.as new file mode 100644 index 00000000000..d6e4e6dc4d7 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Order.as @@ -0,0 +1,65 @@ +package io.swagger.client.model { + + + [XmlRootNode(name="Order")] + public class Order { + + + + [XmlElement(name="id")] + + public var id: Number = 0; + + + + [XmlElement(name="petId")] + + public var petId: Number = 0; + + + + [XmlElement(name="quantity")] + + public var quantity: Number = 0; + + + + [XmlElement(name="shipDate")] + + public var shipDate: Date = null; + + /* Order Status */ + + + [XmlElement(name="status")] + + public var status: String = null; + + + + [XmlElement(name="complete")] + + public var complete: Boolean = false; + + + public function toString(): String { + var str: String = "Order: "; + + str += " (id: " + id + ")"; + + str += " (petId: " + petId + ")"; + + str += " (quantity: " + quantity + ")"; + + str += " (shipDate: " + shipDate + ")"; + + str += " (status: " + status + ")"; + + str += " (complete: " + complete + ")"; + + return str; + } + +} + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/OrderList.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/OrderList.as new file mode 100644 index 00000000000..bba3d8a4724 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/OrderList.as @@ -0,0 +1,18 @@ +package io.swagger.client.model { + +import io.swagger.common.ListWrapper; + + public class OrderList implements ListWrapper { + // This declaration below of _Order_obj_class is to force flash compiler to include this class + private var _order_obj_class: io.swagger.client.model.Order = null; + [XmlElements(name="order", type="io.swagger.client.model.Order")] + public var order: Array = new Array(); + + public function getList(): Array{ + return order; + } + +} + + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Pet.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Pet.as new file mode 100644 index 00000000000..81b29d91e4c --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Pet.as @@ -0,0 +1,75 @@ +package io.swagger.client.model { + +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; + + [XmlRootNode(name="Pet")] + public class Pet { + + + + [XmlElement(name="id")] + + public var id: Number = 0; + + + + [XmlElement(name="category")] + + public var category: Category = null; + + + + [XmlElement(name="name")] + + public var name: String = null; + + + + // This declaration below of _photoUrls_obj_class is to force flash compiler to include this class + private var _photoUrls_obj_class: Array = null; + [XmlElementWrapper(name="photoUrls")] + [XmlElements(name="photoUrls", type="Array")] + + + public var photoUrls: Array = new Array(); + + + + // This declaration below of _tags_obj_class is to force flash compiler to include this class + private var _tags_obj_class: Array = null; + [XmlElementWrapper(name="tags")] + [XmlElements(name="tags", type="Array")] + + + public var tags: Array = new Array(); + + /* pet status in the store */ + + + [XmlElement(name="status")] + + public var status: String = null; + + + public function toString(): String { + var str: String = "Pet: "; + + str += " (id: " + id + ")"; + + str += " (category: " + category + ")"; + + str += " (name: " + name + ")"; + + str += " (photoUrls: " + photoUrls + ")"; + + str += " (tags: " + tags + ")"; + + str += " (status: " + status + ")"; + + return str; + } + +} + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/PetList.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/PetList.as new file mode 100644 index 00000000000..ada0846c5ea --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/PetList.as @@ -0,0 +1,20 @@ +package io.swagger.client.model { + +import io.swagger.common.ListWrapper; +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; + + public class PetList implements ListWrapper { + // This declaration below of _Pet_obj_class is to force flash compiler to include this class + private var _pet_obj_class: io.swagger.client.model.Pet = null; + [XmlElements(name="pet", type="io.swagger.client.model.Pet")] + public var pet: Array = new Array(); + + public function getList(): Array{ + return pet; + } + +} + + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Tag.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Tag.as new file mode 100644 index 00000000000..7387e2e2745 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/Tag.as @@ -0,0 +1,32 @@ +package io.swagger.client.model { + + + [XmlRootNode(name="Tag")] + public class Tag { + + + + [XmlElement(name="id")] + + public var id: Number = 0; + + + + [XmlElement(name="name")] + + public var name: String = null; + + + public function toString(): String { + var str: String = "Tag: "; + + str += " (id: " + id + ")"; + + str += " (name: " + name + ")"; + + return str; + } + +} + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/TagList.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/TagList.as new file mode 100644 index 00000000000..25ebadb27fb --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/TagList.as @@ -0,0 +1,18 @@ +package io.swagger.client.model { + +import io.swagger.common.ListWrapper; + + public class TagList implements ListWrapper { + // This declaration below of _Tag_obj_class is to force flash compiler to include this class + private var _tag_obj_class: io.swagger.client.model.Tag = null; + [XmlElements(name="tag", type="io.swagger.client.model.Tag")] + public var tag: Array = new Array(); + + public function getList(): Array{ + return tag; + } + +} + + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/User.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/User.as new file mode 100644 index 00000000000..2b6474de90c --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/User.as @@ -0,0 +1,81 @@ +package io.swagger.client.model { + + + [XmlRootNode(name="User")] + public class User { + + + + [XmlElement(name="id")] + + public var id: Number = 0; + + + + [XmlElement(name="username")] + + public var username: String = null; + + + + [XmlElement(name="firstName")] + + public var firstName: String = null; + + + + [XmlElement(name="lastName")] + + public var lastName: String = null; + + + + [XmlElement(name="email")] + + public var email: String = null; + + + + [XmlElement(name="password")] + + public var password: String = null; + + + + [XmlElement(name="phone")] + + public var phone: String = null; + + /* User Status */ + + + [XmlElement(name="userStatus")] + + public var userStatus: Number = 0; + + + public function toString(): String { + var str: String = "User: "; + + str += " (id: " + id + ")"; + + str += " (username: " + username + ")"; + + str += " (firstName: " + firstName + ")"; + + str += " (lastName: " + lastName + ")"; + + str += " (email: " + email + ")"; + + str += " (password: " + password + ")"; + + str += " (phone: " + phone + ")"; + + str += " (userStatus: " + userStatus + ")"; + + return str; + } + +} + +} diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/UserList.as b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/UserList.as new file mode 100644 index 00000000000..e8a1fdb27f6 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/client/model/UserList.as @@ -0,0 +1,18 @@ +package io.swagger.client.model { + +import io.swagger.common.ListWrapper; + + public class UserList implements ListWrapper { + // This declaration below of _User_obj_class is to force flash compiler to include this class + private var _user_obj_class: io.swagger.client.model.User = null; + [XmlElements(name="user", type="io.swagger.client.model.User")] + public var user: Array = new Array(); + + public function getList(): Array{ + return user; + } + +} + + +} diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ApiInvoker.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ApiInvoker.as similarity index 93% rename from samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ApiInvoker.as rename to samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ApiInvoker.as index 89fd394d2e9..98d94052ec4 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ApiInvoker.as +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ApiInvoker.as @@ -1,27 +1,6 @@ -package com.wordnik.swagger.common { -import asaxb.xml.bind.ASAXBContext; -import asaxb.xml.bind.Unmarshaller; - -import com.wordnik.swagger.event.ApiClientEvent; -import com.wordnik.swagger.event.Response; -import com.wordnik.swagger.common.ApiUserCredentials; - -import flash.events.EventDispatcher; -import flash.utils.Dictionary; -import flash.utils.describeType; -import flash.xml.XMLDocument; -import flash.xml.XMLNode; - -import mx.messaging.ChannelSet; -import mx.messaging.channels.HTTPChannel; -import mx.messaging.messages.HTTPRequestMessage; -import mx.rpc.AsyncToken; -import mx.rpc.events.FaultEvent; -import mx.rpc.events.ResultEvent; -import mx.rpc.http.HTTPService; -import mx.rpc.xml.SimpleXMLEncoder; -import mx.utils.ObjectUtil; - +package io.swagger.common { +import io.swagger.event.ApiClientEvent; +import io.swagger.event.Response; public class ApiInvoker extends EventDispatcher { diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ApiUrlHelper.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ApiUrlHelper.as similarity index 74% rename from samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ApiUrlHelper.as rename to samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ApiUrlHelper.as index 0fc7e1821b1..4333c6c7e4c 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ApiUrlHelper.as +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ApiUrlHelper.as @@ -1,5 +1,5 @@ -package com.wordnik.swagger.common { -import com.wordnik.swagger.common.ApiUserCredentials; +package io.swagger.common { +import io.swagger.common.ApiUserCredentials; /** * @private @@ -12,17 +12,17 @@ internal class ApiUrlHelper { private static const HTTP_URL_PREFIX:String = "http://"; - internal static function appendTokenInfo(restUrl:String, requestHeader:Object, credentials:ApiUserCredentials):String { + internal static function appendTokenInfo(restUrl:String, requestHeader: Object, credentials: ApiUserCredentials): String { //checks for the presence api credentials on client initialization and not repeated here - if (restUrl.indexOf("?") == -1) { + if(restUrl.indexOf("?") == -1){ restUrl += ( "?" + API_URL_KEY + "=" + credentials.apiToken ); } - else { + else{ restUrl += ( "&" + API_URL_KEY + "=" + credentials.apiToken ); } requestHeader.api_key = credentials.apiToken; - if (credentials.authToken != null && credentials.authToken != "") { + if(credentials.authToken != null && credentials.authToken != ""){ restUrl += ( "&" + AUTH_TOKEN_URL_KEY + "=" + credentials.authToken ); requestHeader.auth_token = credentials.authToken; } @@ -30,7 +30,7 @@ internal class ApiUrlHelper { return restUrl; } - internal static function getProxyUrl(hostName:String, proxyPath:String):String { + internal static function getProxyUrl(hostName: String, proxyPath: String): String{ if (hostName(hostName.length - 1) == "/") //remove trailing slash { hostName = hostName.substring(0, hostName.length - 1); diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ApiUserCredentials.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ApiUserCredentials.as similarity index 53% rename from samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ApiUserCredentials.as rename to samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ApiUserCredentials.as index 3b0e38e6ccc..118d917a247 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/common/ApiUserCredentials.as +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ApiUserCredentials.as @@ -1,28 +1,10 @@ -package com.wordnik.swagger.common { +package io.swagger.common { /** * Api account credentials. * */ public class ApiUserCredentials { - /** - * Constructor of ApiUserCredentials - * @param apiToken An apitoken that is passed along with the requests - * @param authToken A valid auth_token which could necessary for certain operations - * @param hostName The host name for the Rest API eg. api.companyName.com - * @param userId The userId which is required for certain operations - currently, get user lists - */ - public function ApiUserCredentials(hostName:String, apiPath:String, apiToken:String, - authToken:String = null, userId:Number = -1, apiProxyServerUrl:String = "", - proxyPath:String = null) { - this.hostName = hostName; - this.apiToken = apiToken; - this.authToken = authToken; - this.userId = userId; - this.apiPath = apiPath; - this.apiProxyServerUrl = apiProxyServerUrl; - this.proxyPath = proxyPath; - } /** * An apitoken that is passed along with the requests */ @@ -39,21 +21,43 @@ public class ApiUserCredentials { * The host name for the Rest API eg. api.companyName.com */ public var hostName:String; + + /** + * The base path to the api resources - used along with the hostname + * eg. /v4 + */ + public var apiPath: String; + + /** + * The base path to the blazeds proxy + * eg. /v4/messagebroker/restproxy + */ + public var proxyPath: String; + + /** + * If a proxy server has been set up for the services specify the URL here. This value is used when the Api is invoked with + * the value useProxy as true + */ + public var apiProxyServerUrl: String; + /** - * The base path to the api resources - used along with the hostname - * eg. /v4 + * Constructor of ApiUserCredentials + * @param apiToken An apitoken that is passed along with the requests + * @param authToken A valid auth_token which could necessary for certain operations + * @param hostName The host name for the Rest API eg. api.companyName.com + * @param userId The userId which is required for certain operations - currently, get user lists */ - public var apiPath:String; - /** - * The base path to the blazeds proxy - * eg. /v4/messagebroker/restproxy - */ - public var proxyPath:String; - /** - * If a proxy server has been set up for the services specify the URL here. This value is used when the Api is invoked with - * the value useProxy as true - */ - public var apiProxyServerUrl:String; + public function ApiUserCredentials(hostName: String, apiPath: String, apiToken: String, + authToken: String = null, userId: Number = -1, apiProxyServerUrl: String="", + proxyPath: String = null) { + this.hostName = hostName; + this.apiToken = apiToken; + this.authToken = authToken; + this.userId = userId; + this.apiPath = apiPath; + this.apiProxyServerUrl = apiProxyServerUrl; + this.proxyPath = proxyPath; + } } } \ No newline at end of file diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ListWrapper.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ListWrapper.as new file mode 100644 index 00000000000..b22890ad1d1 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/ListWrapper.as @@ -0,0 +1,9 @@ +package io.swagger.common +{ + public interface ListWrapper + { + + function getList(): Array; + + } +} \ No newline at end of file diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/SwaggerApi.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/SwaggerApi.as new file mode 100644 index 00000000000..059de642a74 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/SwaggerApi.as @@ -0,0 +1,75 @@ +package io.swagger.common +{ + import io.swagger.common.ApiUserCredentials; + + import flash.events.EventDispatcher; + import flash.events.IEventDispatcher; + + import mx.utils.UIDUtil; + + public class SwaggerApi extends EventDispatcher + { + + protected var _apiUsageCredentials:ApiUserCredentials; + protected var _apiEventNotifier:EventDispatcher; + protected var _apiInvoker: ApiInvoker; + + protected var _useProxyServer: Boolean = false; + + + /** + * Constructor for the api client + * @param apiCredentials Wrapper object for tokens and hostName required towards authentication + * @param eventDispatcher Optional event dispatcher that when provided is used by the SDK to dispatch any Response + */ + public function SwaggerApi(apiCredentials: ApiUserCredentials, eventDispatcher: EventDispatcher = null) { + super(); + _apiUsageCredentials = apiCredentials; + _apiEventNotifier = eventDispatcher; + } + + public function useProxyServer(value:Boolean, proxyServerUrl: String = null):void { + _useProxyServer = value; + } + + protected function getApiInvoker():ApiInvoker { + if(_apiInvoker == null){ + if(_apiEventNotifier == null){ + _apiEventNotifier = this; + } + _apiInvoker = new ApiInvoker(_apiUsageCredentials, _apiEventNotifier, _useProxyServer); + } + return _apiInvoker; + } + + protected function getUniqueId():String { + return UIDUtil.createUID(); + } + + /** + * Method for returning the path value + * For a string value an empty value is returned if the value is null + * @param value + * @return + */ + protected static function toPathValue(value: Object): String { + if(value is Array){ + return arrayToPathValue(value as Array); + } + return value == null ? "" : value.toString(); + } + + /** + * Method for returning a path value + * For a list of objects a comma separated string is returned + * @param objects + * @return + */ + protected static function arrayToPathValue(objects: Array): String { + var out: String = ""; + + return objects.join(","); + } + + } +} \ No newline at end of file diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/XMLWriter.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/XMLWriter.as new file mode 100644 index 00000000000..0b08066775b --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/common/XMLWriter.as @@ -0,0 +1,28 @@ +package io.swagger.common +{ + public class XMLWriter + { + public var xml:XML; + + public function XMLWriter() + { + xml=; + } + + public function reset():void { + xml=new XML(); + } + + public function addProperty(propertyName:String, propertyValue:String):XML { + var xmlProperty:XML= + xmlProperty.setName(propertyName); + xmlProperty.appendChild(propertyValue); + xml.appendChild(xmlProperty); + return xmlProperty; + } + + public function addAttribute(propertyName:String, attribute:String, attributeValue:String):void { + xml.elements(propertyName)[0].@[attribute]=attributeValue; + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/event/ApiClientEvent.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/ApiClientEvent.as similarity index 75% rename from samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/event/ApiClientEvent.as rename to samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/ApiClientEvent.as index 923cf3454fa..d64cd304d49 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/event/ApiClientEvent.as +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/ApiClientEvent.as @@ -1,5 +1,5 @@ -package com.wordnik.swagger.event { -import com.wordnik.swagger.event.Response; +package io.swagger.event { +import io.swagger.event.Response; import flash.events.Event; @@ -8,7 +8,7 @@ import flash.events.Event; * If a custom dispatcher has been assigned by the consumer on the generated client then the dispatcher dispatches * the ApiClientEvent to indicate success or failure of the invocation using the Response */ -public class ApiClientEvent extends Event { +public class ApiClientEvent extends Event{ /** * Event type to indicate a unsuccessful invocation @@ -19,17 +19,18 @@ public class ApiClientEvent extends Event { * Event type to indicate a successful invocation */ public static const SUCCESS_EVENT:String = "successfulInvocation"; - - public function ApiClientEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false) { - super(type, bubbles, cancelable); - } + /** * The Response object which contains response info */ - public var response:Response; + public var response: Response; /** * Any additional info */ public var message:String; + + public function ApiClientEvent(type:String,bubbles:Boolean = false,cancelable:Boolean = false) { + super(type, bubbles, cancelable); + } } } \ No newline at end of file diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/event/Response.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/Response.as similarity index 63% rename from samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/event/Response.as rename to samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/Response.as index 2379096932a..a43b7980a38 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/swagger/event/Response.as +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/event/Response.as @@ -1,4 +1,4 @@ -package com.wordnik.swagger.event { +package io.swagger.event { /** * Response contains info on the result of an API invocation. @@ -6,47 +6,50 @@ package com.wordnik.swagger.event { */ public class Response { + /** + * Indicates whether the invoked operation failed or succeeded + */ + public var isSuccess:Boolean; + + /** + * The payload of the succesful operation eg. a Word in a WordRequest + */ + public var payload:Object; + + /** + * Error message in case of failure + */ + public var errorMessage:String; + + /** + * A request Id that was passed in by the user as a param when invoking the operation + */ + public var requestId:String; private static const API_ERROR_MSG:String = "Api error response: "; - private static function getFriendlyMessage(errorMessage:String):String { - var result:String = errorMessage; - if (errorMessage == null) + public function Response(isSuccessful: Boolean, payload: Object = null, errorMessage: String = null, requestId: String = null) { + this.isSuccess = isSuccessful; + this.payload = payload; + this.errorMessage = getFriendlyMessage(errorMessage); + } + + private static function getFriendlyMessage(errorMessage: String): String{ + var result: String = errorMessage; + if(errorMessage == null) return null; - var errorCode:String; - var errorCodeArray:Array = errorMessage.match(/(?<=HTTP\/1.1 )[0-9][0-9][0-9]/); - if (errorCodeArray != null && errorCodeArray.length == 1) { + var errorCode: String; + var errorCodeArray: Array = errorMessage.match(/(?<=HTTP\/1.1 )[0-9][0-9][0-9]/); + if(errorCodeArray != null && errorCodeArray.length == 1){ errorCode = String(errorCodeArray[0]); } - var msgArray:Array = errorMessage.match(/(?<=HTTP\/1.1 [0-9][0-9][0-9] )[^]*/); - if (msgArray != null && msgArray.length == 1) { + var msgArray: Array = errorMessage.match(/(?<=HTTP\/1.1 [0-9][0-9][0-9] )[^]*/); + if(msgArray != null && msgArray.length == 1){ result = API_ERROR_MSG + String(msgArray[0]); } return result; } - public function Response(isSuccessful:Boolean, payload:Object = null, errorMessage:String = null, requestId:String = null) { - this.isSuccess = isSuccessful; - this.payload = payload; - this.errorMessage = getFriendlyMessage(errorMessage); - } - /** - * Indicates whether the invoked operation failed or succeeded - */ - public var isSuccess:Boolean; - /** - * The payload of the succesful operation eg. a Word in a WordRequest - */ - public var payload:Object; - /** - * Error message in case of failure - */ - public var errorMessage:String; - /** - * A request Id that was passed in by the user as a param when invoking the operation - */ - public var requestId:String; - - public function toString():String { + public function toString(): String { return "Response (requestId:" + requestId + "; isSuccess:" + isSuccess + "; errorMessage:" + errorMessage + "; payload:" + payload + ")"; } } diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/exception/ApiErrorCodes.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/exception/ApiErrorCodes.as new file mode 100644 index 00000000000..e5ea46480aa --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/exception/ApiErrorCodes.as @@ -0,0 +1,34 @@ +package io.swagger.exception +{ + public class ApiErrorCodes + { + /** + * System exception. + */ + public static const SYSTEM_EXCEPTION: Number = 0; + + /** + * With Arguments as current key. + */ + public static const API_KEY_NOT_VALID: Number = 1000; + /** + * With arguments as current token value + */ + public static const AUTH_TOKEN_NOT_VALID: Number = 1001; + /** + * With arguments as input JSON and output class anme + */ + public static const ERROR_CONVERTING_JSON_TO_JAVA: Number = 1002; + /** + * With arguments as JAVA class name + */ + public static const ERROR_CONVERTING_JAVA_TO_JSON: Number = 1003; + + public static const ERROR_FROM_WEBSERVICE_CALL: Number = 1004; + /** + * With arguments as current API server name + */ + public static const API_SERVER_NOT_VALID: Number = 1005; + + } +} \ No newline at end of file diff --git a/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/exception/ApiErrors.as b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/exception/ApiErrors.as new file mode 100644 index 00000000000..c8ac95a5c59 --- /dev/null +++ b/samples/client/petstore/flash/src/main/flex/io/swagger/swagger/exception/ApiErrors.as @@ -0,0 +1,10 @@ +package io.swagger.exception +{ + public class ApiError extends Error + { + public function ApiError(id:*=0, message:*="") + { + super(message,id); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/flash/lib/ASAXB-0.1.1.swc b/samples/client/petstore/flash/src/main/flex/lib/ASAXB-0.1.1.swc similarity index 100% rename from samples/client/petstore/flash/lib/ASAXB-0.1.1.swc rename to samples/client/petstore/flash/src/main/flex/lib/ASAXB-0.1.1.swc diff --git a/samples/client/petstore/flash/lib/ext/as3corelib.swc b/samples/client/petstore/flash/src/main/flex/lib/as3corelib.swc similarity index 100% rename from samples/client/petstore/flash/lib/ext/as3corelib.swc rename to samples/client/petstore/flash/src/main/flex/lib/as3corelib.swc diff --git a/samples/client/petstore/flash/lib/ext/flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc b/samples/client/petstore/flash/src/main/flex/lib/ext/flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc similarity index 100% rename from samples/client/petstore/flash/lib/ext/flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc rename to samples/client/petstore/flash/src/main/flex/lib/ext/flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc diff --git a/samples/client/petstore/flash/lib/ext/flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc b/samples/client/petstore/flash/src/main/flex/lib/ext/flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc similarity index 100% rename from samples/client/petstore/flash/lib/ext/flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc rename to samples/client/petstore/flash/src/main/flex/lib/ext/flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc diff --git a/samples/client/petstore/flash/lib/ext/flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc b/samples/client/petstore/flash/src/main/flex/lib/ext/flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc similarity index 100% rename from samples/client/petstore/flash/lib/ext/flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc rename to samples/client/petstore/flash/src/main/flex/lib/ext/flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc diff --git a/samples/client/petstore/flash/lib/ext/flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc b/samples/client/petstore/flash/src/main/flex/lib/ext/flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc similarity index 100% rename from samples/client/petstore/flash/lib/ext/flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc rename to samples/client/petstore/flash/src/main/flex/lib/ext/flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java index cf7ace02309..d7c2038dead 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java @@ -14,8 +14,8 @@ public class Pet { private Long id = null; private Category category = null; private String name = null; - private List photoUrls = new ArrayList() ; - private List tags = new ArrayList() ; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); public enum StatusEnum { available, pending, sold, }; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index 56c6adf30f2..7802a5b46c0 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -5,14 +5,21 @@ #import "SWGJSONRequestSerializer.h" #import "SWGQueryParamCollection.h" #import "SWGConfiguration.h" - -#import "SWGUser.h" -#import "SWGCategory.h" -#import "SWGPet.h" -#import "SWGTag.h" -#import "SWGOrder.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ +#import "SWGUser.h" +#import "SWGCategory.h" +#import "SWGPet.h" +#import "SWGTag.h" +#import "SWGOrder.h" + + +@class SWGConfiguration; /** * A key for `NSError` user info dictionaries. @@ -29,77 +36,61 @@ extern NSString *const SWGResponseObjectErrorKey; @property(nonatomic, readonly) NSOperationQueue* queue; /** - * Get the Api Client instance from pool - * - * @param baseUrl The base url of api client. - * - * @return The SWGApiClient instance. - */ -+(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl; - -/** - * Get the operations queue - * - * @return The `shardQueue` static variable. - */ -+(NSOperationQueue*) sharedQueue; - -/** - * Clear Cache + * Clears Cache */ +(void)clearCache; /** - * Turn on cache + * Turns on cache * * @param enabled If the cached is enable, must be `YES` or `NO` */ +(void)setCacheEnabled:(BOOL) enabled; /** - * Get the request queue size + * Gets the request queue size * * @return The size of `queuedRequests` static variable. */ +(unsigned long)requestQueueSize; /** - * Set the client unreachable + * Sets the client unreachable * - * @param state off line state, must be `YES` or `NO` + * @param state off line state, must be `YES` or `NO` */ +(void) setOfflineState:(BOOL) state; /** - * Get the client reachability + * Gets the client reachability * * @return The client reachability. */ +(AFNetworkReachabilityStatus) getReachabilityStatus; /** - * Get the next request id + * Gets the next request id * * @return The next executed request id. */ +(NSNumber*) nextRequestId; /** - * Generate request id and add it to the queue + * Generates request id and add it to the queue * * @return The next executed request id. */ +(NSNumber*) queueRequest; /** - * Remove request id from the queue + * Removes request id from the queue * * @param requestId The request which will be removed. */ +(void) cancelRequest:(NSNumber*)requestId; /** - * URL encode NSString + * Gets URL encoded NSString * * @param unescaped The string which will be escaped. * @@ -108,21 +99,19 @@ extern NSString *const SWGResponseObjectErrorKey; +(NSString*) escape:(id)unescaped; /** - * Customize the behavior when the reachability changed + * Customizes the behavior when the reachability changed * * @param changeBlock The block will be executed when the reachability changed. */ +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; /** - * Set the client reachability strategy - * - * @param host The host of SWGApiClient. + * Sets the api client reachability strategy */ -+(void) configureCacheReachibilityForHost:(NSString*)host; +- (void)configureCacheReachibility; /** - * Detect Accept header from accepts NSArray + * Detects Accept header from accepts NSArray * * @param accepts NSArray of header * @@ -131,7 +120,7 @@ extern NSString *const SWGResponseObjectErrorKey; +(NSString *) selectHeaderAccept:(NSArray *)accepts; /** - * Detect Content-Type header from contentTypes NSArray + * Detects Content-Type header from contentTypes NSArray * * @param contentTypes NSArray of header * @@ -140,7 +129,7 @@ extern NSString *const SWGResponseObjectErrorKey; +(NSString *) selectHeaderContentType:(NSArray *)contentTypes; /** - * Set header for request + * Sets header for request * * @param value The header value * @param forKey The header key @@ -149,7 +138,7 @@ extern NSString *const SWGResponseObjectErrorKey; forKey:(NSString*) forKey; /** - * Update header parameters and query parameters for authentication + * Updates header parameters and query parameters for authentication * * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. @@ -160,7 +149,7 @@ extern NSString *const SWGResponseObjectErrorKey; WithAuthSettings:(NSArray *)authSettings; /** - * Deserialize the given data to Objective-C object. + * Deserializes the given data to Objective-C object. * * @param data The data will be deserialized. * @param class The type of objective-c object. @@ -168,7 +157,7 @@ extern NSString *const SWGResponseObjectErrorKey; - (id) deserialize:(id) data class:(NSString *) class; /** - * Logging request and response + * Logs request and response * * @param operation AFHTTPRequestOperation for the HTTP request. * @param request The HTTP request. @@ -179,7 +168,7 @@ extern NSString *const SWGResponseObjectErrorKey; error:(NSError *)error; /** - * Perform request + * Performs request * * @param path Request url. * @param method Request method. @@ -189,7 +178,7 @@ extern NSString *const SWGResponseObjectErrorKey; * @param authSettings Request authentication names. * @param requestContentType Request content-type. * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. + * @param completionBlock The block will be executed when the request completed. * * @return The request id. */ diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index f51a012a811..22b5c256402 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -1,7 +1,5 @@ #import "SWGApiClient.h" -@implementation SWGApiClient - NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject"; static long requestId = 0; @@ -9,41 +7,75 @@ static bool offlineState = false; static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; -static NSOperationQueue* sharedQueue; static void (^reachabilityChangeBlock)(int); +@implementation SWGApiClient + +- (instancetype)init { + NSString *baseUrl = [[SWGConfiguration sharedConfig] host]; + return [self initWithBaseURL:[NSURL URLWithString:baseUrl]]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + self = [super initWithBaseURL:url]; + if (self) { + self.requestSerializer = [AFJSONRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + // configure reachability + [self configureCacheReachibility]; + } + return self; +} + ++ (void)initialize { + if (self == [SWGApiClient class]) { + queuedRequests = [[NSMutableSet alloc] init]; + // initialize URL cache + [self configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; + } +} + +#pragma mark - Setter Methods + ++ (void) setOfflineState:(BOOL) state { + offlineState = state; +} + ++ (void) setCacheEnabled:(BOOL)enabled { + cacheEnabled = enabled; +} + +- (void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey { + [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; +} + #pragma mark - Log Methods - (void)logResponse:(AFHTTPRequestOperation *)operation forRequest:(NSURLRequest *)request error:(NSError*)error { SWGConfiguration *config = [SWGConfiguration sharedConfig]; - + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] Request body \n~BEGIN~\n %@\n~END~\n"\ "[DEBUG] HTTP Response body \n~BEGIN~\n %@\n~END~\n", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], operation.responseString]; - + if (config.loggingFileHanlder) { [config.loggingFileHanlder seekToEndOfFile]; [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; } - + NSLog(@"%@", message); } #pragma mark - Cache Methods -+ (void) setCacheEnabled:(BOOL)enabled { - cacheEnabled = enabled; -} - +(void)clearCache { [[NSURLCache sharedURLCache] removeAllCachedResponses]; } -#pragma mark - - +(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize diskSize: (unsigned long) diskSize { NSAssert(memorySize > 0, @"invalid in-memory cache size"); @@ -58,43 +90,7 @@ static void (^reachabilityChangeBlock)(int); [NSURLCache setSharedURLCache:cache]; } -+(NSOperationQueue*) sharedQueue { - return sharedQueue; -} - -+(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl { - static NSMutableDictionary *_pool = nil; - if (queuedRequests == nil) { - queuedRequests = [[NSMutableSet alloc]init]; - } - if(_pool == nil) { - // setup static vars - // create queue - sharedQueue = [[NSOperationQueue alloc] init]; - - // create pool - _pool = [[NSMutableDictionary alloc] init]; - - // initialize URL cache - [SWGApiClient configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; - - // configure reachability - [SWGApiClient configureCacheReachibilityForHost:baseUrl]; - } - - @synchronized(self) { - SWGApiClient * client = [_pool objectForKey:baseUrl]; - if (client == nil) { - client = [[SWGApiClient alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]]; - [_pool setValue:client forKey:baseUrl ]; - if([[SWGConfiguration sharedConfig] debug]) - NSLog(@"new client for path %@", baseUrl); - } - if([[SWGConfiguration sharedConfig] debug]) - NSLog(@"returning client for path %@", baseUrl); - return client; - } -} +#pragma mark - Utility Methods /* * Detect `Accept` from accepts @@ -104,13 +100,13 @@ static void (^reachabilityChangeBlock)(int); if (accepts == nil || [accepts count] == 0) { return @""; } - + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; [accepts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [lowerAccepts addObject:[obj lowercaseString]]; }]; - + if ([lowerAccepts containsObject:@"application/json"]) { return @"application/json"; } @@ -127,7 +123,7 @@ static void (^reachabilityChangeBlock)(int); if (contentTypes == nil || [contentTypes count] == 0) { return @"application/json"; } - + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [lowerContentTypes addObject:[obj lowercaseString]]; @@ -141,11 +137,23 @@ static void (^reachabilityChangeBlock)(int); } } --(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey { - [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; ++ (NSString*)escape:(id)unescaped { + if([unescaped isKindOfClass:[NSString class]]){ + return (NSString *)CFBridgingRelease + (CFURLCreateStringByAddingPercentEscapes( + NULL, + (__bridge CFStringRef) unescaped, + NULL, + (CFStringRef)@"!*'();:@&=+$,/?%#[]", + kCFStringEncodingUTF8)); + } + else { + return [NSString stringWithFormat:@"%@", unescaped]; + } } +#pragma mark - Request Methods + +(unsigned long)requestQueueSize { return [queuedRequests count]; } @@ -171,46 +179,28 @@ static void (^reachabilityChangeBlock)(int); [queuedRequests removeObject:requestId]; } -+(NSString*) escape:(id)unescaped { - if([unescaped isKindOfClass:[NSString class]]){ - return (NSString *)CFBridgingRelease - (CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); - } - else { - return [NSString stringWithFormat:@"%@", unescaped]; - } -} - -(Boolean) executeRequestWithId:(NSNumber*) requestId { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - if([obj intValue] == [requestId intValue]) - return TRUE; - else return FALSE; + if([obj intValue] == [requestId intValue]) { + return YES; + } + else { + return NO; + } }]; if(matchingItems.count == 1) { if([[SWGConfiguration sharedConfig] debug]) NSLog(@"removing request id %@", requestId); [queuedRequests removeObject:requestId]; - return true; + return YES; + } + else { + return NO; } - else - return false; } --(id)initWithBaseURL:(NSURL *)url { - self = [super initWithBaseURL:url]; - self.requestSerializer = [AFJSONRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - if (!self) - return nil; - return self; -} +#pragma mark - Reachability Methods +(AFNetworkReachabilityStatus) getReachabilityStatus { return reachabilityStatus; @@ -220,12 +210,8 @@ static void (^reachabilityChangeBlock)(int); reachabilityChangeBlock = changeBlock; } -+(void) setOfflineState:(BOOL) state { - offlineState = state; -} - -+(void) configureCacheReachibilityForHost:(NSString*)host { - [[SWGApiClient sharedClientFromPool:host].reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { +- (void) configureCacheReachibility { + [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { reachabilityStatus = status; switch (status) { case AFNetworkReachabilityStatusUnknown: @@ -254,16 +240,352 @@ static void (^reachabilityChangeBlock)(int); default: break; } + // call the reachability block, if configured if(reachabilityChangeBlock != nil) { reachabilityChangeBlock(status); } }]; - [[SWGApiClient sharedClientFromPool:host].reachabilityManager startMonitoring]; + + [self.reachabilityManager startMonitoring]; } --(NSString*) pathWithQueryParamsToString:(NSString*) path - queryParams:(NSDictionary*) queryParams { +#pragma mark - Deserialize methods + +- (id) deserialize:(id) data class:(NSString *) class { + NSRegularExpression *regexp = nil; + NSTextCheckingResult *match = nil; + NSMutableArray *resultArray = nil; + NSMutableDictionary *resultDict = nil; + NSString *innerType = nil; + + // return nil if data is nil or class is nil + if (!data || !class) { + return nil; + } + + // remove "*" from class, if ends with "*" + if ([class hasSuffix:@"*"]) { + class = [class substringToIndex:[class length] - 1]; + } + + // pure object + if ([class isEqualToString:@"NSObject"]) { + return [[NSObject alloc] init]; + } + + // list of models + NSString *arrayOfModelsPat = @"NSArray<(.+)>"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + innerType = [class substringWithRange:[match rangeAtIndex:1]]; + + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:innerType]]; + } + ]; + + return resultArray; + } + + // list of primitives + NSString *arrayOfPrimitivesPat = @"NSArray\\* /\\* (.+) \\*/"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + innerType = [class substringWithRange:[match rangeAtIndex:1]]; + + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:innerType]]; + }]; + + return resultArray; + } + + // map + NSString *dictPat = @"NSDictionary\\* /\\* (.+?), (.+) \\*/"; + regexp = [NSRegularExpression regularExpressionWithPattern:dictPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; + + resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; + }]; + + return resultDict; + } + + // primitives + NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; + + if ([primitiveTypes containsObject:class]) { + if ([class isEqualToString:@"NSString"]) { + return [NSString stringWithString:data]; + } + else if ([class isEqualToString:@"NSDate"]) { + return [NSDate dateWithISO8601String:data]; + } + else if ([class isEqualToString:@"NSNumber"]) { + // NSNumber from NSNumber + if ([data isKindOfClass:[NSNumber class]]) { + return data; + } + else if ([data isKindOfClass:[NSString class]]) { + // NSNumber (NSCFBoolean) from NSString + if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { + return [NSNumber numberWithBool:[data boolValue]]; + // NSNumber from NSString + } else { + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + formatter.numberStyle = NSNumberFormatterDecimalStyle; + return [formatter numberFromString:data]; + } + } + } + } + + // model + Class ModelClass = NSClassFromString(class); + if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { + return [[ModelClass alloc] initWithDictionary:data error:nil]; + } + + return nil; +} + +#pragma mark - Operation Methods + +- (void) operationWithCompletionBlock: (NSURLRequest *)request + requestId: (NSNumber *) requestId + completionBlock: (void (^)(id, NSError *))completionBlock { + AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request + success:^(AFHTTPRequestOperation *operation, id response) { + if([self executeRequestWithId:requestId]) { + if([[SWGConfiguration sharedConfig] debug]) { + [self logResponse:operation forRequest:request error:nil]; + } + completionBlock(response, nil); + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if([self executeRequestWithId:requestId]) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if(operation.responseObject) { + // Add in the (parsed) response body. + userInfo[SWGResponseObjectErrorKey] = operation.responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + + if([[SWGConfiguration sharedConfig] debug]) + [self logResponse:nil forRequest:request error:augmentedError]; + completionBlock(nil, augmentedError); + } + }]; + + [self.operationQueue addOperation:op]; +} + +- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request + requestId: (NSNumber *) requestId + completionBlock: (void (^)(id, NSError *))completionBlock { + AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request + success:^(AFHTTPRequestOperation *operation, id responseObject) { + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + NSString *directory = nil; + if (config.tempFolderPath) { + directory = config.tempFolderPath; + } + else { + directory = NSTemporaryDirectory(); + } + + NSDictionary *headers = operation.response.allHeaderFields; + NSString *filename = nil; + if ([headers objectForKey:@"Content-Disposition"]) { + + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; + } + else { + filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; + + [operation.responseData writeToURL:file atomically:YES]; + completionBlock(file, nil); + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + + if ([self executeRequestWithId:requestId]) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (operation.responseObject) { + userInfo[SWGResponseObjectErrorKey] = operation.responseObject; + } + + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + + if ([[SWGConfiguration sharedConfig] debug]) { + [self logResponse:nil forRequest:request error:augmentedError]; + } + + completionBlock(nil, augmentedError); + } + }]; + + [self.operationQueue addOperation:op]; +} + +#pragma mark - Perform Request Methods + +-(NSNumber*) requestWithCompletionBlock: (NSString*) path + method: (NSString*) method + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock { + // setting request serializer + if ([requestContentType isEqualToString:@"application/json"]) { + self.requestSerializer = [SWGJSONRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"multipart/form-data"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else { + NSAssert(false, @"unsupport request type %@", requestContentType); + } + + // setting response serializer + if ([responseContentType isEqualToString:@"application/json"]) { + self.responseSerializer = [SWGJSONResponseSerializer serializer]; + } + else { + self.responseSerializer = [AFHTTPResponseSerializer serializer]; + } + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + + NSMutableURLRequest * request = nil; + + NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; + if ([pathWithQueryParams hasPrefix:@"/"]) { + pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; + } + + NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + if (files.count > 0) { + request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" + URLString:urlString + parameters:nil + constructingBodyWithBlock:^(id formData) { + [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSData *data = [obj dataUsingEncoding:NSUTF8StringEncoding]; + [formData appendPartWithFormData:data name:key]; + }]; + [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSURL *filePath = (NSURL *)obj; + [formData appendPartWithFileURL:filePath name:key error:nil]; + }]; + } error:nil]; + } + else { + if (formParams) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:formParams + error:nil]; + } + if (body) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:body + error:nil]; + } + } + + BOOL hasHeaderParams = false; + if(headerParams != nil && [headerParams count] > 0) { + hasHeaderParams = true; + } + if(offlineState) { + NSLog(@"%@ cache forced", path); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + NSLog(@"%@ cache enabled", path); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + NSLog(@"%@ cache disabled", path); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + if(hasHeaderParams){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + + + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; + + NSNumber* requestId = [SWGApiClient queueRequest]; + if ([responseType isEqualToString:@"NSURL*"]) { + [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + completionBlock(data, error); + }]; + } + else { + [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + completionBlock([self deserialize:data class:responseType], error); + }]; + } + return requestId; +} + +#pragma mark - + +- (NSString*) pathWithQueryParamsToString:(NSString*) path + queryParams:(NSDictionary*) queryParams { NSString * separator = nil; int counter = 0; @@ -323,18 +645,18 @@ static void (^reachabilityChangeBlock)(int); - (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers queryParams:(NSDictionary *__autoreleasing *)querys WithAuthSettings:(NSArray *)authSettings { - + if (!authSettings || [authSettings count] == 0) { return; } - + NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - + SWGConfiguration *config = [SWGConfiguration sharedConfig]; for (NSString *auth in authSettings) { NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; - + if (authSetting) { if ([authSetting[@"in"] isEqualToString:@"header"]) { [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; @@ -344,338 +666,9 @@ static void (^reachabilityChangeBlock)(int); } } } - + *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -#pragma mark - Deserialize methods - -- (id) deserialize:(id) data class:(NSString *) class { - NSRegularExpression *regexp = nil; - NSTextCheckingResult *match = nil; - NSMutableArray *resultArray = nil; - NSMutableDictionary *resultDict = nil; - - // return nil if data is nil or class is nil - if (!data || !class) { - return nil; - } - - // remove "*" from class, if ends with "*" - if ([class hasSuffix:@"*"]) { - class = [class substringToIndex:[class length] - 1]; - } - - // pure object - if ([class isEqualToString:@"NSObject"]) { - return [[NSObject alloc] init]; - } - - // list of models - NSString *arrayOfModelsPat = @"NSArray<(.+)>"; - regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - NSString *innerType = [class substringWithRange:[match rangeAtIndex:1]]; - - resultArray = [NSMutableArray arrayWithCapacity:[data count]]; - [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [resultArray addObject:[self deserialize:obj class:innerType]]; - } - ]; - - return resultArray; - } - - // list of primitives - NSString *arrayOfPrimitivesPet = @"NSArray"; - regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPet - options:NSRegularExpressionCaseInsensitive - error:nil]; - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - resultArray = [NSMutableArray arrayWithCapacity:[data count]]; - [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [resultArray addObject:[self deserialize:obj class:NSStringFromClass([obj class])]]; - }]; - - return resultArray; - } - - // map - NSString *dictPat = @"NSDictionary\\* /\\* (.+), (.+) \\*/"; - regexp = [NSRegularExpression regularExpressionWithPattern:dictPat - options:NSRegularExpressionCaseInsensitive - error:nil]; - match = [regexp firstMatchInString:class - options:0 - range:NSMakeRange(0, [class length])]; - - if (match) { - NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; - - resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; - [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; - }]; - - return resultDict; - } - - // primitives - NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"BOOL", @"NSNumber"]; - - if ([primitiveTypes containsObject:class]) { - if ([class isEqualToString:@"NSString"]) { - return [NSString stringWithString:data]; - } - else if ([class isEqualToString:@"NSDate"]) { - return [NSDate dateWithISO8601String:data]; - } - else if ([class isEqualToString:@"BOOL"]) { - // Returns YES on encountering one of "Y", "y", "T", "t", or a - // digit 1-9—the method ignores any trailing characters - // NSString => BOOL => NSNumber - return [NSNumber numberWithBool:[data boolValue]]; - } - else if ([class isEqualToString:@"NSNumber"]) { - // NSNumber from NSNumber - if ([data isKindOfClass:[NSNumber class]]) { - return data; - } - // NSNumber from NSString - else { - NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; - formatter.numberStyle = NSNumberFormatterDecimalStyle; - return [formatter numberFromString:data]; - } - } - } - - // model - Class ModelClass = NSClassFromString(class); - if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { - return [[ModelClass alloc] initWithDictionary:data error:nil]; - } - - return nil; -} - -#pragma mark - Operation Methods - -- (void) operationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id response) { - if([self executeRequestWithId:requestId]) { - if([[SWGConfiguration sharedConfig] debug]) { - [self logResponse:operation forRequest:request error:nil]; - } - completionBlock(response, nil); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if(operation.responseObject) { - // Add in the (parsed) response body. - userInfo[SWGResponseObjectErrorKey] = operation.responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - if([[SWGConfiguration sharedConfig] debug]) - [self logResponse:nil forRequest:request error:augmentedError]; - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; -} - -- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id responseObject) { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - NSString *directory = nil; - if (config.tempFolderPath) { - directory = config.tempFolderPath; - } - else { - directory = NSTemporaryDirectory(); - } - - NSDictionary *headers = operation.response.allHeaderFields; - NSString *filename = nil; - if ([headers objectForKey:@"Content-Disposition"]) { - - NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; - filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; - } - else { - filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; - } - - NSString *filepath = [directory stringByAppendingPathComponent:filename]; - NSURL *file = [NSURL fileURLWithPath:filepath]; - - [operation.responseData writeToURL:file atomically:YES]; - completionBlock(file, nil); - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - - if ([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (operation.responseObject) { - userInfo[SWGResponseObjectErrorKey] = operation.responseObject; - } - - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - if ([[SWGConfiguration sharedConfig] debug]) { - [self logResponse:nil forRequest:request error:augmentedError]; - } - - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; -} - -#pragma mark - Perform Request Methods - --(NSNumber*) requestWithCompletionBlock: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock { - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [SWGJSONRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"multipart/form-data"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else { - NSAssert(false, @"unsupport request type %@", requestContentType); - } - - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [SWGJSONResponseSerializer serializer]; - } - else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - } - - // auth setting - [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; - - NSMutableURLRequest * request = nil; - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; - NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - if (files.count > 0) { - request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" - URLString:urlString - parameters:nil - constructingBodyWithBlock:^(id formData) { - [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSData *data = [obj dataUsingEncoding:NSUTF8StringEncoding]; - [formData appendPartWithFormData:data name:key]; - }]; - [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSURL *filePath = (NSURL *)obj; - [formData appendPartWithFileURL:filePath name:key error:nil]; - }]; - } error:nil]; - } - else { - if (formParams) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:formParams - error:nil]; - } - if (body) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:body - error:nil]; - } - } - - BOOL hasHeaderParams = false; - if(headerParams != nil && [headerParams count] > 0) { - hasHeaderParams = true; - } - if(offlineState) { - NSLog(@"%@ cache forced", path); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - NSLog(@"%@ cache enabled", path); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - NSLog(@"%@ cache disabled", path); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; - } - - if(hasHeaderParams){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; - - NSNumber* requestId = [SWGApiClient queueRequest]; - if ([responseType isEqualToString:@"NSURL*"]) { - [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { - completionBlock(data, error); - }]; - } - else { - [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { - completionBlock([self deserialize:data class:responseType], error); - }]; - } - return requestId; -} - @end - - - - diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.h b/samples/client/petstore/objc/SwaggerClient/SWGCategory.h index a2fed79b4a3..983fd610123 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGCategory @end - + @interface SWGCategory : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m index c41f76a5247..fb3ccecf176 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m @@ -1,12 +1,21 @@ #import "SWGCategory.h" @implementation SWGCategory - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"name"]; @@ -19,4 +28,12 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h index d3619c72ab5..99f97cdec1b 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h @@ -1,26 +1,49 @@ #import +#import "SWGApiClient.h" + +/** The `SWGConfiguration` class manages the configurations for the sdk. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ +@class SWGApiClient; + @interface SWGConfiguration : NSObject +/** + * Default api client + */ +@property (nonatomic) SWGApiClient *apiClient; + +/** + * Default base url + */ +@property (nonatomic) NSString *host; /** * Api key values for Api Key type Authentication * - * To add or remove api key, use `setValue:forApiKeyField:`. + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKey; /** * Api key prefix values to be prepend to the respective api key * - * To add or remove prefix, use `setValue:forApiKeyPrefixField:`. + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename and Password for Basic type Authentication + * Usename for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication */ -@property (nonatomic) NSString *username; @property (nonatomic) NSString *password; /** @@ -31,37 +54,74 @@ /** * Logging Settings */ -@property (nonatomic) BOOL debug; -@property (nonatomic) NSString *loggingFile; -@property (nonatomic) NSFileHandle *loggingFileHanlder; /** - * Get configuration singleton instance + * Debug switch, default false + */ +@property (nonatomic) BOOL debug; + +/** + * Debug file location, default log in console + */ +@property (nonatomic) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; + +/** + * Gets configuration singleton instance */ + (instancetype) sharedConfig; /** - * Sets field in `apiKey` + * Sets API key + * + * To remove a apiKey for an identifier, just set the apiKey to nil. + * + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). + * */ -- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; /** - * Sets field in `apiKeyPrefix` + * Removes api key + * + * @param identifier API key identifier. */ -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; +- (void) removeApiKey:(NSString *)identifier; /** - * Get API key (with prefix if set) + * Sets the prefix for API key + * + * To remove a apiKeyPrefix for an identifier, just set the apiKeyPrefix to nil. + * + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. + */ +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Removes api key prefix + * + * @param identifier API key identifier. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; + +/** + * Gets API key (with prefix if set) */ - (NSString *) getApiKeyWithPrefix:(NSString *) key; /** - * Get Basic Auth token + * Gets Basic Auth token */ - (NSString *) getBasicAuthToken; /** - * Get Authentication Setings + * Gets Authentication Setings */ - (NSDictionary *) authSettings; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m index 81e308a53fc..9cc1c07d9f9 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m @@ -25,6 +25,8 @@ - (instancetype) init { self = [super init]; if (self) { + self.apiClient = nil; + self.host = @"http://petstore.swagger.io/v2"; self.username = @""; self.password = @""; self.tempFolderPath = nil; @@ -54,18 +56,26 @@ NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - + return basicAuthCredentials; } #pragma mark - Setter Methods -- (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { - [self.mutableApiKey setValue:value forKey:field]; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { + [self.mutableApiKey setValue:apiKey forKey:identifier]; } -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field { - [self.mutableApiKeyPrefix setValue:value forKey:field]; +- (void) removeApiKey:(NSString *)identifier { + [self.mutableApiKey removeObjectForKey:identifier]; +} + +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { + [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; +} + +- (void) removeApiKeyPrefix:(NSString *)identifier { + [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } - (void) setLoggingFile:(NSString *)loggingFile { @@ -73,12 +83,12 @@ if ([self.loggingFileHanlder isKindOfClass:[NSFileHandle class]]) { [self.loggingFileHanlder closeFile]; } - + _loggingFile = loggingFile; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (self.loggingFileHanlder == nil) { + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHanlder == nil) { [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; } } @@ -95,15 +105,15 @@ #pragma mark - - (NSDictionary *) authSettings { - return @{ - @"api_key": @{ - @"type": @"api_key", - @"in": @"header", - @"key": @"api_key", - @"value": [self getApiKeyWithPrefix:@"api_key"] - }, - - }; + return @{ + @"api_key": + @{ + @"type": @"api_key", + @"in": @"header", + @"key": @"api_key", + @"value": [self getApiKeyWithPrefix:@"api_key"] + }, + }; } @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h b/samples/client/petstore/objc/SwaggerClient/SWGOrder.h index 2e71906cd53..48a7cf0d6c1 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGOrder @end - + @interface SWGOrder : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m index 5d3179446ed..83fe5741cd7 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m @@ -1,12 +1,21 @@ #import "SWGOrder.h" @implementation SWGOrder - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"]; @@ -19,4 +28,12 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/SWGPet.h index edd54e9f31a..e340e0e2b86 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.h @@ -1,12 +1,19 @@ #import #import "SWGObject.h" + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + #import "SWGTag.h" #import "SWGCategory.h" @protocol SWGPet @end - + @interface SWGPet : SWGObject @@ -16,7 +23,7 @@ @property(nonatomic) NSString* name; -@property(nonatomic) NSArray* photoUrls; +@property(nonatomic) NSArray* /* NSString */ photoUrls; @property(nonatomic) NSArray* tags; /* pet status in the store [optional] diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/SWGPet.m index d5559aa6f72..3fd315ab011 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.m @@ -1,12 +1,21 @@ #import "SWGPet.h" @implementation SWGPet - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"category", @"tags", @"status"]; @@ -19,4 +28,12 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h index 39f23edb028..f7e67d0aa1f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h @@ -4,6 +4,12 @@ #import "SWGApiClient.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + @interface SWGPetApi: NSObject @property(nonatomic, assign)SWGApiClient *apiClient; @@ -12,8 +18,6 @@ -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; -+(void) setBasePath:(NSString*)basePath; -+(NSString*) getBasePath; /// /// /// Update an existing pet @@ -53,7 +57,7 @@ /// /// /// @return NSArray* --(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status +-(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray* /* NSString */) status completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; @@ -68,7 +72,7 @@ /// /// /// @return NSArray* --(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray*) tags +-(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray* /* NSString */) tags completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index 15f4af0564e..f2e7fb64030 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -9,14 +9,16 @@ @implementation SWGPetApi -static NSString * basePath = @"http://petstore.swagger.io/v2"; - #pragma mark - Initialize methods - (id) init { self = [super init]; if (self) { - self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + if (config.apiClient == nil) { + config.apiClient = [[SWGApiClient alloc] init]; + } + self.apiClient = config.apiClient; self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -25,12 +27,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - (id) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { - if (apiClient) { - self.apiClient = apiClient; - } - else { - self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; - } + self.apiClient = apiClient; self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -48,14 +45,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return singletonAPI; } -+(void) setBasePath:(NSString*)path { - basePath = path; -} - -+(NSString*) getBasePath { - return basePath; -} - -(void) addHeader:(NSString*)value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } @@ -85,12 +74,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -144,7 +134,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"PUT" queryParams: queryParams formParams: formParams @@ -176,12 +166,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -235,7 +226,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" queryParams: queryParams formParams: formParams @@ -260,19 +251,20 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; /// /// @returns NSArray* /// --(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray*) status +-(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray* /* NSString */) status completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock { - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByStatus", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -316,7 +308,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" queryParams: queryParams formParams: formParams @@ -341,19 +333,20 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; /// /// @returns NSArray* /// --(NSNumber*) findPetsByTagsWithCompletionBlock: (NSArray*) tags +-(NSNumber*) findPetsByTagsWithCompletionBlock: (NSArray* /* NSString */) tags completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock { - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByTags", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -397,7 +390,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" queryParams: queryParams formParams: formParams @@ -434,13 +427,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -478,7 +472,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" queryParams: queryParams formParams: formParams @@ -521,13 +515,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -573,7 +568,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" queryParams: queryParams formParams: formParams @@ -613,13 +608,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -659,7 +655,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"DELETE" queryParams: queryParams formParams: formParams @@ -702,13 +698,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}/uploadImage", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/{petId}/uploadImage"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -754,7 +751,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" queryParams: queryParams formParams: formParams diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h index 7488c1baa70..09e67e38ed0 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h @@ -4,6 +4,12 @@ #import "SWGApiClient.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + @interface SWGStoreApi: NSObject @property(nonatomic, assign)SWGApiClient *apiClient; @@ -12,8 +18,6 @@ -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; -+(void) setBasePath:(NSString*)basePath; -+(NSString*) getBasePath; /// /// /// Returns pet inventories by status diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m index 5304b67dd07..ed792988597 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m @@ -9,14 +9,16 @@ @implementation SWGStoreApi -static NSString * basePath = @"http://petstore.swagger.io/v2"; - #pragma mark - Initialize methods - (id) init { self = [super init]; if (self) { - self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + if (config.apiClient == nil) { + config.apiClient = [[SWGApiClient alloc] init]; + } + self.apiClient = config.apiClient; self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -25,12 +27,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - (id) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { - if (apiClient) { - self.apiClient = apiClient; - } - else { - self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; - } + self.apiClient = apiClient; self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -48,14 +45,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return singletonAPI; } -+(void) setBasePath:(NSString*)path { - basePath = path; -} - -+(NSString*) getBasePath { - return basePath; -} - -(void) addHeader:(NSString*)value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } @@ -82,12 +71,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/inventory", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -125,7 +115,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" queryParams: queryParams formParams: formParams @@ -157,12 +147,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -216,7 +207,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" queryParams: queryParams formParams: formParams @@ -253,13 +244,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order/{orderId}"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -297,7 +289,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" queryParams: queryParams formParams: formParams @@ -334,13 +326,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order/{orderId}"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -378,7 +371,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"DELETE" queryParams: queryParams formParams: formParams diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.h b/samples/client/petstore/objc/SwaggerClient/SWGTag.h index d9cc84be270..97e95807550 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGTag @end - + @interface SWGTag : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/SWGTag.m index 5d48a099070..3bcb9973dfd 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.m @@ -1,12 +1,21 @@ #import "SWGTag.h" @implementation SWGTag - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"name"]; @@ -19,4 +28,12 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.h b/samples/client/petstore/objc/SwaggerClient/SWGUser.h index f505ca2c041..6ba19e632b8 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGUser @end - + @interface SWGUser : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/SWGUser.m index 060b65ffa12..d040a6bce6d 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.m @@ -1,12 +1,21 @@ #import "SWGUser.h" @implementation SWGUser - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"username", @"firstName", @"lastName", @"email", @"password", @"phone", @"userStatus"]; @@ -19,4 +28,12 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h index 6fda87cca70..a6e69a8947d 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h @@ -4,6 +4,12 @@ #import "SWGApiClient.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + @interface SWGUserApi: NSObject @property(nonatomic, assign)SWGApiClient *apiClient; @@ -12,8 +18,6 @@ -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; -+(void) setBasePath:(NSString*)basePath; -+(NSString*) getBasePath; /// /// /// Create user diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 845e8d93ae3..46a76b35b57 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -9,14 +9,16 @@ @implementation SWGUserApi -static NSString * basePath = @"http://petstore.swagger.io/v2"; - #pragma mark - Initialize methods - (id) init { self = [super init]; if (self) { - self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + if (config.apiClient == nil) { + config.apiClient = [[SWGApiClient alloc] init]; + } + self.apiClient = config.apiClient; self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -25,12 +27,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - (id) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { - if (apiClient) { - self.apiClient = apiClient; - } - else { - self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; - } + self.apiClient = apiClient; self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -48,14 +45,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return singletonAPI; } -+(void) setBasePath:(NSString*)path { - basePath = path; -} - -+(NSString*) getBasePath { - return basePath; -} - -(void) addHeader:(NSString*)value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } @@ -85,12 +74,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -144,7 +134,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" queryParams: queryParams formParams: formParams @@ -176,12 +166,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithArray", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -235,7 +226,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" queryParams: queryParams formParams: formParams @@ -267,12 +258,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithList", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -326,7 +318,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" queryParams: queryParams formParams: formParams @@ -361,12 +353,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/login", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -412,7 +405,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" queryParams: queryParams formParams: formParams @@ -441,12 +434,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/logout", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -484,7 +478,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" queryParams: queryParams formParams: formParams @@ -521,13 +515,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -565,7 +560,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" queryParams: queryParams formParams: formParams @@ -605,13 +600,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -665,7 +661,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"PUT" queryParams: queryParams formParams: formParams @@ -702,13 +698,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/{username}"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } + + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -746,7 +743,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"DELETE" queryParams: queryParams formParams: formParams diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 0ba21c560ef..a5fe06f63b7 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -23,6 +23,8 @@ 6003F5BC195388D20070C39A /* Tests.m in Sources */ = {isa = PBXBuildFile; fileRef = 6003F5BB195388D20070C39A /* Tests.m */; }; 873B8AEB1B1F5CCA007FD442 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 873B8AEA1B1F5CCA007FD442 /* Main.storyboard */; }; 94BE6BE84795B5034A811E61 /* libPods-SwaggerClient_Example.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 8D46325ECAD48245C07F6733 /* libPods-SwaggerClient_Example.a */; }; + CF0ADB481B5F95D6008A2729 /* PetTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF0ADB471B5F95D6008A2729 /* PetTest.m */; }; + CF8F71391B5F73AC00162980 /* DeserializationTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF8F71381B5F73AC00162980 /* DeserializationTest.m */; }; CFDFB4121B3CFFA8009739C5 /* UserApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFDFB40D1B3CFEC3009739C5 /* UserApiTest.m */; }; CFDFB4131B3CFFDD009739C5 /* PetApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFDFB40A1B3CFEC3009739C5 /* PetApiTest.m */; }; CFDFB4141B3CFFF6009739C5 /* StoreApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFDFB40B1B3CFEC3009739C5 /* StoreApiTest.m */; }; @@ -65,6 +67,8 @@ 873B8AEA1B1F5CCA007FD442 /* Main.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = Main.storyboard; sourceTree = ""; }; 8D46325ECAD48245C07F6733 /* libPods-SwaggerClient_Example.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-SwaggerClient_Example.a"; sourceTree = BUILT_PRODUCTS_DIR; }; BFB4BE760737508B3CFC23B2 /* Pods-SwaggerClient_Example.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient_Example.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example.release.xcconfig"; sourceTree = ""; }; + CF0ADB471B5F95D6008A2729 /* PetTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PetTest.m; sourceTree = ""; }; + CF8F71381B5F73AC00162980 /* DeserializationTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DeserializationTest.m; sourceTree = ""; }; CFDFB40A1B3CFEC3009739C5 /* PetApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PetApiTest.m; sourceTree = ""; }; CFDFB40B1B3CFEC3009739C5 /* StoreApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = StoreApiTest.m; sourceTree = ""; }; CFDFB40C1B3CFEC3009739C5 /* SWGApiClientTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClientTest.m; sourceTree = ""; }; @@ -166,6 +170,8 @@ CFDFB40A1B3CFEC3009739C5 /* PetApiTest.m */, CFDFB40B1B3CFEC3009739C5 /* StoreApiTest.m */, CFDFB40C1B3CFEC3009739C5 /* SWGApiClientTest.m */, + CF0ADB471B5F95D6008A2729 /* PetTest.m */, + CF8F71381B5F73AC00162980 /* DeserializationTest.m */, CFDFB40D1B3CFEC3009739C5 /* UserApiTest.m */, 6003F5BB195388D20070C39A /* Tests.m */, 6003F5B6195388D20070C39A /* Supporting Files */, @@ -374,10 +380,12 @@ buildActionMask = 2147483647; files = ( CFDFB4141B3CFFF6009739C5 /* StoreApiTest.m in Sources */, + CF0ADB481B5F95D6008A2729 /* PetTest.m in Sources */, CFDFB4131B3CFFDD009739C5 /* PetApiTest.m in Sources */, 6003F5BC195388D20070C39A /* Tests.m in Sources */, CFDFB4151B3D000B009739C5 /* SWGApiClientTest.m in Sources */, CFDFB4121B3CFFA8009739C5 /* UserApiTest.m in Sources */, + CF8F71391B5F73AC00162980 /* DeserializationTest.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m index a56f31408aa..ab7f6e8f72e 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m @@ -7,6 +7,10 @@ // #import "SWGViewController.h" +#import +#import +#import +#import @interface SWGViewController () @@ -17,13 +21,36 @@ - (void)viewDidLoad { [super viewDidLoad]; - // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; - // Dispose of any resources that can be recreated. +} + +- (SWGPet*) createPet { + SWGPet * pet = [[SWGPet alloc] init]; + pet._id = [[NSNumber alloc] initWithLong:[[NSDate date] timeIntervalSince1970]]; + pet.name = @"monkey"; + + SWGCategory * category = [[SWGCategory alloc] init]; + category._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; + category.name = @"super-happy"; + pet.category = category; + + SWGTag *tag1 = [[SWGTag alloc] init]; + tag1._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; + tag1.name = @"test tag 1"; + SWGTag *tag2 = [[SWGTag alloc] init]; + tag2._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; + tag2.name = @"test tag 2"; + pet.tags = (NSArray *)[[NSArray alloc] initWithObjects:tag1, tag2, nil]; + + pet.status = @"available"; + + NSArray * photos = [[NSArray alloc] initWithObjects:@"http://foo.bar.com/3", @"http://foo.bar.com/4", nil]; + pet.photoUrls = photos; + return pet; } @end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m new file mode 100644 index 00000000000..0460a4be4af --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m @@ -0,0 +1,165 @@ +#import +#import +#import +#import + +@interface DeserializationTest : XCTestCase { + +@private SWGApiClient *apiClient; + +} + +@end + +@implementation DeserializationTest + +- (void)setUp { + [super setUp]; + apiClient = [[SWGApiClient alloc] init]; +} + +- (void)testDeserializeDate { + NSString *dateStr = @"2012-09-27"; + + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + NSTimeZone *timezone = [NSTimeZone timeZoneWithName:@"UTC"]; + [formatter setTimeZone:timezone]; + [formatter setDateFormat:@"yyyy-MM-dd"]; + NSDate *date = [formatter dateFromString:dateStr]; + + NSDate *deserializedDate = [apiClient deserialize:dateStr class:@"NSDate*"]; + + XCTAssertEqualWithAccuracy([date timeIntervalSinceReferenceDate], [deserializedDate timeIntervalSinceReferenceDate], 0.001); +} + +- (void)testDeserializeDateTime { + NSString *dateTimeStr = @"1997-07-16T19:20:30+00:00"; + + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; + NSDate *dateTime = [formatter dateFromString:dateTimeStr]; + + NSDate *deserializedDateTime = [apiClient deserialize:dateTimeStr class:@"NSDate*"]; + + XCTAssertEqualWithAccuracy([dateTime timeIntervalSinceReferenceDate], [deserializedDateTime timeIntervalSinceReferenceDate], 0.001); +} + +- (void)testDeserializeObject { + XCTAssertTrue([[apiClient deserialize:@"" class:@"NSObject*"] isKindOfClass:[NSObject class]]); +} + +- (void)testDeserializeString { + NSString *data = @"test string"; + NSString *result = [apiClient deserialize:data class:@"NSString*"]; + + XCTAssertTrue([result isEqualToString:data]); +} + +- (void)testDeserializeListOfString { + NSArray *data = @[@"test string"]; + NSArray *result = [apiClient deserialize:data class:@"NSArray* /* NSString */"]; + + XCTAssertTrue([result isKindOfClass:[NSArray class]]); + XCTAssertTrue([result[0] isKindOfClass:[NSString class]]); +} + +- (void)testDeserializeListOfModels { + NSArray *data = + @[ + @{ + @"id": @119, + @"category": @{ + @"id": @0, + @"name": @"string" + }, + @"name": @"doggie", + @"photoUrls": @[ + @"string" + ], + @"tags": @[ + @{ + @"id": @0, + @"name": @"string" + } + ], + @"status": @"available" + + }]; + + NSArray *result = [apiClient deserialize:data class:@"NSArray*"]; + + XCTAssertTrue([result isKindOfClass:[NSArray class]]); + XCTAssertTrue([[result firstObject] isKindOfClass:[SWGPet class]]); + XCTAssertEqualObjects([[result firstObject] _id], @119); +} + +- (void)testDeserializeMapOfModels { + NSDictionary *data = + @{ + @"pet": @{ + @"id": @119, + @"category": @{ + @"id": @0, + @"name": @"string" + }, + @"name": @"doggie", + @"photoUrls": @[ + @"string" + ], + @"tags": @[ + @{ + @"id": @0, + @"name": @"string" + } + ], + @"status": @"available" + + } + }; + + NSDictionary *result = [apiClient deserialize:data class:@"NSDictionary* /* NSString, SWGPet */"]; + + XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); + XCTAssertTrue([result[@"pet"] isKindOfClass:[SWGPet class]]); + XCTAssertEqualObjects([result[@"pet"] _id], @119); +} + +- (void)testDeserializeNestedMap { + NSDictionary *data = + @{ + @"foo": @{ + @"bar": @1 + } + }; + + NSDictionary *result = [apiClient deserialize:data class:@"NSDictionary* /* NSString, NSDictionary* /* NSString, NSNumber */ */"]; + + XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); + XCTAssertTrue([result[@"foo"] isKindOfClass:[NSDictionary class]]); + XCTAssertTrue([result[@"foo"][@"bar"] isKindOfClass:[NSNumber class]]); +} + +- (void)testDeserializeNestedList { + NSArray *data = @[@[@"foo"]]; + + NSArray *result = [apiClient deserialize:data class:@"NSArray* /* NSArray* /* NSString */ */"]; + + XCTAssertTrue([result isKindOfClass:[NSArray class]]); + XCTAssertTrue([result[0] isKindOfClass:[NSArray class]]); + XCTAssertTrue([result[0][0] isKindOfClass:[NSString class]]); +} + +- (void)testDeserializeBool { + NSString *data; + NSNumber *result; + + data = @"true"; + result = [apiClient deserialize:data class:@"NSNumber*"]; + XCTAssertTrue([result isEqual:@YES]); + + data = @"false"; + result = [apiClient deserialize:data class:@"NSNumber*"]; + XCTAssertTrue([result isEqual:@NO]); +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetTest.m new file mode 100644 index 00000000000..9dbde13310b --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetTest.m @@ -0,0 +1,37 @@ +#import +#import +#import + +@interface PetTest : XCTestCase { + +@private SWGPet *pet; + +} + +@end + +@implementation PetTest + +- (void)setUp { + [super setUp]; + + NSDictionary *petDict = @{ @"id": @1, @"name": @"test pet", + @"status": @"sold", + @"photoUrls": @[@"string"], + @"category": @{ @"id": @1, @"name": @"test category" }, + @"tags": @[ @{ @"id": @1, @"name": @"test tag" } ]}; + pet = [[SWGPet alloc] initWithDictionary:petDict error:nil]; +} + +- (void)testDescription { + NSDictionary *petDict = @{ @"id": @1, @"name": @"test pet", + @"status": @"sold", + @"photoUrls": @[@"string"], + @"category": @{ @"id": @1, @"name": @"test category" }, + @"tags": @[ @{ @"id": @1, @"name": @"test tag" } ]}; + NSString *petStr = [petDict description]; + + XCTAssertTrue([[pet description] isEqualToString:petStr]); +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m index 00c6bf70da6..d19180dc008 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m @@ -61,8 +61,8 @@ - (void)testConfiguration { SWGConfiguration *config = [SWGConfiguration sharedConfig]; - [config setValue:@"123456" forApiKeyField:@"api_key"]; - [config setValue:@"PREFIX" forApiKeyPrefixField:@"api_key"]; + [config setApiKey:@"123456" forApiKeyIdentifier:@"api_key"]; + [config setApiKeyPrefix:@"PREFIX" forApiKeyPrefixIdentifier:@"api_key"]; config.username = @"test_username"; config.password = @"test_password"; @@ -98,77 +98,4 @@ XCTAssertEqualObjects(basicAuthCredentials, [config getBasicAuthToken]); } -- (void)testDeserialize { - id data; - id result; - - // list of models - data = - @[ - @{ - @"id": @119, - @"category": @{ - @"id": @0, - @"name": @"string" - }, - @"name": @"doggie", - @"photoUrls": @[ - @"string" - ], - @"tags": @[ - @{ - @"id": @0, - @"name": @"string" - } - ], - @"status": @"available" - - }]; - result = [self.apiClient deserialize:data class:@"NSArray*"]; - - XCTAssertTrue([result isKindOfClass:[NSArray class]]); - XCTAssertTrue([[result firstObject] isKindOfClass:[SWGPet class]]); - XCTAssertEqualObjects([[result firstObject] _id], @119); - - // map of models - data = - @{ - @"pet": @{ - @"id": @119, - @"category": @{ - @"id": @0, - @"name": @"string" - }, - @"name": @"doggie", - @"photoUrls": @[ - @"string" - ], - @"tags": @[ - @{ - @"id": @0, - @"name": @"string" - } - ], - @"status": @"available" - - } - }; - result = [self.apiClient deserialize:data class:@"NSDictionary* /* NSString, SWGPet */"]; - - XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); - XCTAssertTrue([result[@"pet"] isKindOfClass:[SWGPet class]]); - XCTAssertEqualObjects([result[@"pet"] _id], @119); - - // pure object - result = [self.apiClient deserialize:@"" class:@"NSObject*"]; - - XCTAssertTrue([result isKindOfClass:[NSObject class]]); - - // NSString - data = @"test string"; - result = [self.apiClient deserialize:data class:@"NSString*"]; - - XCTAssertTrue([result isKindOfClass:[NSString class]]); -} - @end diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 002df7fc713..fcea7100ae4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -89,7 +89,7 @@ class Configuration * * @var string */ - protected $host = 'http://localhost'; + protected $host = 'http://petstore.swagger.io/v2'; /** * Timeout (second) of the HTTP request, by default set to 0, no timeout @@ -103,7 +103,7 @@ class Configuration * * @var string */ - protected $userAgent = "PHP-Swagger"; + protected $userAgent = "PHP-Swagger/1.0.0"; /** * Debug switch (default set to false) diff --git a/samples/client/petstore/python/setup.py b/samples/client/petstore/python/setup.py index ffc6f6a3ad2..e66e9689343 100644 --- a/samples/client/petstore/python/setup.py +++ b/samples/client/petstore/python/setup.py @@ -1,3 +1,5 @@ +# coding: utf-8 + import sys from setuptools import setup, find_packages @@ -33,11 +35,3 @@ setup( ) - - - - - - - - diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index 924201c9a4a..ca9a3c05104 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -1,10 +1,20 @@ -#!/usr/bin/env python # coding: utf-8 -"""Swagger generic API client. This client handles the client- -server communication, and is invariant across implementations. Specifics of -the methods and models for each application are generated from the Swagger -templates.""" +""" +Copyright 2015 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" from __future__ import absolute_import from . import models @@ -27,415 +37,523 @@ from datetime import date from six import iteritems try: - # for python3 - from urllib.parse import quote + # for python3 + from urllib.parse import quote except ImportError: - # for python2 - from urllib import quote + # for python2 + from urllib import quote from .configuration import Configuration + class ApiClient(object): - """ - Generic API client for Swagger client library builds - - :param host: The base path for the server to call - :param header_name: a header to pass when making calls to the API - :param header_value: a header value to pass when making calls to the API - """ - def __init__(self, host=Configuration().host, header_name=None, header_value=None): - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.host = host - self.cookie = None - # Set default User-Agent. - self.user_agent = 'Python-Swagger' - - @property - def user_agent(self): - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None): - - # headers parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - for k, v in iteritems(path_params): - replacement = quote(str(self.to_path_value(v))) - resource_path = resource_path.replace('{' + k + '}', replacement) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} - - # post parameters - if post_params: - post_params = self.prepare_post_parameters(post_params, files) - post_params = self.sanitize_for_serialization(post_params) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - url = self.host + resource_path - - # perform request and return response - response_data = self.request(method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body) - - self.last_response = response_data - - # deserialize response data - if response_type: - deserialized_data = self.deserialize(response_data, response_type) - else: - deserialized_data = None - - if callback: - callback(deserialized_data) - else: - return deserialized_data - - def to_path_value(self, obj): """ - Convert a string or object to a path-friendly value + Generic API client for Swagger client library builds. - :param obj: object or string value + Swagger generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the Swagger + templates. - :return string: quoted value + NOTE: This class is auto generated by the swagger code generator program. + https://github.com/swagger-api/swagger-codegen + Do not edit the class manually. + + :param host: The base path for the server to call. + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to the API. """ - if type(obj) == list: - return ','.join(obj) - else: - return str(obj) + def __init__(self, host=Configuration().host, + header_name=None, header_value=None, cookie=None): - def sanitize_for_serialization(self, obj): - """ - Sanitize an object for Request. + """ + Constructor of the class. + """ + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.host = host + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'Python-Swagger' - If obj is None, return None. - If obj is str, int, float, bool, return directly. - If obj is datetime.datetime, datetime.date convert to string in iso8601 format. - If obj is list, santize each element in the list. - If obj is dict, return the dict. - If obj is swagger model, return the properties dict. - """ - if isinstance(obj, type(None)): - return None - elif isinstance(obj, (str, int, float, bool, tuple)): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] - elif isinstance(obj, (datetime, date)): - return obj.isoformat() - else: - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in model definition for request. - obj_dict = {obj.attribute_map[key]: val - for key, val in iteritems(obj.__dict__) - if key != 'swagger_types' and key != 'attribute_map' and val is not None} - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + @property + def user_agent(self): + """ + Gets user agent. + """ + return self.default_headers['User-Agent'] - def deserialize(self, response, response_type): - """ - Derialize response into an object. + @user_agent.setter + def user_agent(self, value): + """ + Sets user agent. + """ + self.default_headers['User-Agent'] = value - :param response: RESTResponse object to be deserialized - :param response_type: class literal for deserialzied object, or string of class name + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value - :return: deserialized object - """ - # handle file downloading - save response body into a tmp file and return the instance - if "file" == response_type: - return self.__deserialize_file(response) + def __call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_type=None, auth_settings=None, callback=None): - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data + # headers parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) - return self.__deserialize(data, response_type) + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + for k, v in iteritems(path_params): + replacement = quote(str(self.to_path_value(v))) + resource_path = resource_path.\ + replace('{' + k + '}', replacement) - def __deserialize(self, data, klass): - """ - :param data: dict, list or str - :param klass: class literal, or string of class name + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + query_params = {k: self.to_path_value(v) + for k, v in iteritems(query_params)} - :return: object - """ - if data is None: - return None + # post parameters + if post_params: + post_params = self.prepare_post_parameters(post_params, files) + post_params = self.sanitize_for_serialization(post_params) - if type(klass) == str: - if 'list[' in klass: - sub_kls = re.match('list\[(.*)\]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) for sub_data in data] + # auth setting + self.update_params_for_auth(header_params, query_params, auth_settings) - if 'dict(' in klass: - sub_kls = re.match('dict\((.*), (.*)\)', klass).group(2) - return {k: self.__deserialize(v, sub_kls) for k, v in iteritems(data)} + # body + if body: + body = self.sanitize_for_serialization(body) - # convert str to class - # for native types - if klass in ['int', 'float', 'str', 'bool', "date", 'datetime', "object"]: - klass = eval(klass) - # for model types - else: - klass = eval('models.' + klass) + # request url + url = self.host + resource_path - if klass in [int, float, str, bool]: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object() - elif klass == date: - return self.__deserialize_date(data) - elif klass == datetime: - return self.__deserialize_datatime(data) - else: - return self.__deserialize_model(data, klass) + # perform request and return response + response_data = self.request(method, url, + query_params=query_params, + headers=header_params, + post_params=post_params, body=body) - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None): - """ - Perform http request and return deserialized data + self.last_response = response_data - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. - :param callback function: Callback function for asynchronous request. - If provide this parameter, the request will be called asynchronously. - :return: - If provide parameter callback, the request will be called asynchronously. - The method will return the request thread. - If parameter callback is None, then the method will return the response directly. - """ - if callback is None: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, callback) - else: - thread = threading.Thread(target=self.__call_api, - args=(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, callback)) - thread.start() - return thread - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None): - """ - Perform http request using RESTClient. - """ - if method == "GET": - return RESTClient.GET(url, query_params=query_params, headers=headers) - elif method == "HEAD": - return RESTClient.HEAD(url, query_params=query_params, headers=headers) - elif method == "POST": - return RESTClient.POST(url, headers=headers, post_params=post_params, body=body) - elif method == "PUT": - return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body) - elif method == "PATCH": - return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body) - elif method == "DELETE": - return RESTClient.DELETE(url, query_params=query_params, headers=headers) - else: - raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`") - - def prepare_post_parameters(self, post_params=None, files=None): - params = {} - - if post_params: - params.update(post_params) - - if files: - for k, v in iteritems(files): - if v: - with open(v, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - params[k] = tuple([filename, filedata, mimetype]) - - return params - - def select_header_accept(self, accepts): - """ - Return `Accept` based on an array of accepts provided - """ - if not accepts: - return - - accepts = list(map(lambda x: x.lower(), accepts)) - - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) - - def select_header_content_type(self, content_types): - """ - Return `Content-Type` baseed on an array of content_types provided - """ - if not content_types: - return 'application/json' - - content_types = list(map(lambda x: x.lower(), content_types)) - - if 'application/json' in content_types: - return 'application/json' - else: - return content_types[0] - - def update_params_for_auth(self, headers, querys, auth_settings): - """ - Update header and query params based on authentication setting - """ - config = Configuration() - - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = config.auth_settings().get(auth) - if auth_setting: - if auth_setting['in'] == 'header': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - querys[auth_setting['key']] = auth_setting['value'] + # deserialize response data + if response_type: + deserialized_data = self.deserialize(response_data, response_type) else: - raise ValueError('Authentication token must be in `query` or `header`') + deserialized_data = None - def __deserialize_file(self, response): - """ - Save response body into a file in (the defined) temporary folder, using the filename - from the `Content-Disposition` header if provided, otherwise a random filename. + if callback: + callback(deserialized_data) + else: + return deserialized_data - :param response: RESTResponse - :return: file path - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) + def to_path_value(self, obj): + """ + Takes value and turn it into a string suitable for inclusion in + the path, by url-encoding. - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) + :param obj: object or string value. - with open(path, "w") as f: - f.write(response.data) + :return string: quoted value. + """ + if type(obj) == list: + return ','.join(obj) + else: + return str(obj) - return path + def sanitize_for_serialization(self, obj): + """ + Builds a JSON POST object. - def __deserialize_primitive(self, data, klass): - """ - Deserialize string to primitive type + If obj is None, return None. + If obj is str, int, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is list, santize each element in the list. + If obj is dict, return the dict. + If obj is swagger model, return the properties dict. - :param data: str - :param klass: class literal + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if isinstance(obj, type(None)): + return None + elif isinstance(obj, (str, int, float, bool, tuple)): + return obj + elif isinstance(obj, list): + return [self.sanitize_for_serialization(sub_obj) + for sub_obj in obj] + elif isinstance(obj, (datetime, date)): + return obj.isoformat() + else: + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `swagger_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = {obj.attribute_map[key[1:]]: val + for key, val in iteritems(obj.__dict__) + if key != 'swagger_types' + and key != 'attribute_map' + and val is not None} - :return: int, float, str, bool - """ - try: - value = klass(data) - except UnicodeEncodeError: - value = unicode(data) - except TypeError: - value = data - return value + return {key: self.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} - def __deserialize_object(self): - """ - Deserialize empty object - """ - return object() + def deserialize(self, response, response_type): + """ + Deserializes response into an object. - def __deserialize_date(self, string): - """ - Deserialize string to date + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialzied object, or string of class name. - :param string: str - :return: date - """ - try: - from dateutil.parser import parse - return parse(string).date() - except ImportError: - return string - except ValueError: - raise ApiException(status=0, reason="Failed to parse `{0}` into a date object".format(string)) - - def __deserialize_datatime(self, string): - """ - Deserialize string to datetime. + :return: deserialized object. + """ + # handle file downloading + # save response body into a tmp file and return the instance + if "file" == response_type: + return self.__deserialize_file(response) - The string should be in iso8601 datetime format. + # fetch data from response object + try: + data = json.loads(response.data) + except ValueError: + data = response.data - :param string: str - :return: datetime - """ - try: - from dateutil.parser import parse - return parse(string) - except ImportError: - return string - except ValueError: - raise ApiException(status=0, reason="Failed to parse `{0}` into a datetime object".format(string)) + return self.__deserialize(data, response_type) - def __deserialize_model(self, data, klass): - """ - Deserialize list or dict to model + def __deserialize(self, data, klass): + """ + Deserializes dict, list, str into an object. - :param data: dict, list - :param klass: class literal - """ - instance = klass() + :param data: dict, list or str. + :param klass: class literal, or string of class name. - for attr, attr_type in iteritems(instance.swagger_types): - if data is not None \ - and instance.attribute_map[attr] in data\ - and isinstance(data, (list, dict)): - value = data[instance.attribute_map[attr]] - setattr(instance, attr, self.__deserialize(value, attr_type)) + :return: object. + """ + if data is None: + return None - return instance + if type(klass) == str: + if klass.startswith('list['): + sub_kls = re.match('list\[(.*)\]', klass).group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] + + if klass.startswith('dict('): + sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in iteritems(data)} + + # convert str to class + # for native types + if klass in ['int', 'float', 'str', 'bool', + "date", 'datetime', "object"]: + klass = eval(klass) + # for model types + else: + klass = eval('models.' + klass) + + if klass in [int, float, str, bool]: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object() + elif klass == date: + return self.__deserialize_date(data) + elif klass == datetime: + return self.__deserialize_datatime(data) + else: + return self.__deserialize_model(data, klass) + + def call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_type=None, auth_settings=None, callback=None): + """ + Makes the HTTP request and return the deserialized data. + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param response: Response data type. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param callback function: Callback function for asynchronous request. + If provide this parameter, + the request will be called asynchronously. + :return: + If provide parameter callback, + the request will be called asynchronously. + The method will return the request thread. + If parameter callback is None, + then the method will return the response directly. + """ + if callback is None: + return self.__call_api(resource_path, method, + path_params, query_params, header_params, + body, post_params, files, + response_type, auth_settings, callback) + else: + thread = threading.Thread(target=self.__call_api, + args=(resource_path, method, + path_params, query_params, + header_params, body, + post_params, files, + response_type, auth_settings, + callback)) + thread.start() + return thread + + def request(self, method, url, query_params=None, headers=None, + post_params=None, body=None): + """ + Makes the HTTP request using RESTClient. + """ + if method == "GET": + return RESTClient.GET(url, + query_params=query_params, + headers=headers) + elif method == "HEAD": + return RESTClient.HEAD(url, + query_params=query_params, + headers=headers) + elif method == "POST": + return RESTClient.POST(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "PUT": + return RESTClient.PUT(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "PATCH": + return RESTClient.PATCH(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "DELETE": + return RESTClient.DELETE(url, + query_params=query_params, + headers=headers) + else: + raise ValueError( + "http method must be `GET`, `HEAD`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def prepare_post_parameters(self, post_params=None, files=None): + """ + Builds form parameters. + + :param post_params: Normal form parameters. + :param files: File parameters. + :return: Form parameters with files. + """ + params = {} + + if post_params: + params.update(post_params) + + if files: + for k, v in iteritems(files): + if not v: + continue + + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.\ + guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) + + return params + + def select_header_accept(self, accepts): + """ + Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return + + accepts = list(map(lambda x: x.lower(), accepts)) + + if 'application/json' in accepts: + return 'application/json' + else: + return ', '.join(accepts) + + def select_header_content_type(self, content_types): + """ + Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return 'application/json' + + content_types = list(map(lambda x: x.lower(), content_types)) + + if 'application/json' in content_types: + return 'application/json' + else: + return content_types[0] + + def update_params_for_auth(self, headers, querys, auth_settings): + """ + Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param querys: Query parameters dict to be updated. + :param auth_settings: Authentication setting identifiers list. + """ + config = Configuration() + + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = config.auth_settings().get(auth) + if auth_setting: + if auth_setting['in'] == 'header': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + querys[auth_setting['key']] = auth_setting['value'] + else: + raise ValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """ + Saves response body into a file in (the defined) temporary folder, + using the filename from the `Content-Disposition` header if provided, + otherwise a random filename. + + :param response: RESTResponse. + :return: file path. + """ + config = Configuration() + + fd, path = tempfile.mkstemp(dir=config.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + filename = re.\ + search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).\ + group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "w") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """ + Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, float, str, bool. + """ + try: + value = klass(data) + except UnicodeEncodeError: + value = unicode(data) + except TypeError: + value = data + return value + + def __deserialize_object(self): + """ + Deserializes empty object. + + :return: object. + """ + return object() + + def __deserialize_date(self, string): + """ + Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + from dateutil.parser import parse + return parse(string).date() + except ImportError: + return string + except ValueError: + raise ApiException( + status=0, + reason="Failed to parse `{0}` into a date object" + .format(string) + ) + + def __deserialize_datatime(self, string): + """ + Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + from dateutil.parser import parse + return parse(string) + except ImportError: + return string + except ValueError: + raise ApiException( + status=0, + reason="Failed to parse `{0}` into a datetime object". + format(string) + ) + + def __deserialize_model(self, data, klass): + """ + Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + instance = klass() + + for attr, attr_type in iteritems(instance.swagger_types): + if data is not None \ + and instance.attribute_map[attr] in data\ + and isinstance(data, (list, dict)): + value = data[instance.attribute_map[attr]] + setattr(instance, attr, self.__deserialize(value, attr_type)) + + return instance diff --git a/samples/client/petstore/python/swagger_client/apis/__init__.py b/samples/client/petstore/python/swagger_client/apis/__init__.py index 128b25dad82..592a56e282d 100644 --- a/samples/client/petstore/python/swagger_client/apis/__init__.py +++ b/samples/client/petstore/python/swagger_client/apis/__init__.py @@ -4,4 +4,3 @@ from __future__ import absolute_import from .user_api import UserApi from .pet_api import PetApi from .store_api import StoreApi - diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index 7c43a72077e..1c34da118c1 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python # coding: utf-8 """ @@ -16,9 +15,8 @@ Copyright 2015 SmartBear Software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ + from __future__ import absolute_import import sys @@ -30,7 +28,12 @@ from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient + class PetApi(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ def __init__(self, api_client=None): config = Configuration() @@ -40,34 +43,38 @@ class PetApi(object): if not config.api_client: config.api_client = ApiClient('http://petstore.swagger.io/v2') self.api_client = config.api_client - - + def update_pet(self, **kwargs): """ Update an existing pet - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update_pet(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - :param Pet body: Pet object that needs to be added to the store - + :param callback function: The callback function + for asynchronous request. (optional) + :param Pet body: Pet object that needs to be added to the store :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method update_pet" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method update_pet" % key + ) params[key] = val del params['kwargs'] @@ -75,61 +82,74 @@ class PetApi(object): method = 'PUT' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json', 'application/xml']) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type(['application/json', 'application/xml']) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def add_pet(self, **kwargs): """ Add a new pet to the store - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.add_pet(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - :param Pet body: Pet object that needs to be added to the store - + :param callback function: The callback function + for asynchronous request. (optional) + :param Pet body: Pet object that needs to be added to the store :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method add_pet" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method add_pet" % key + ) params[key] = val del params['kwargs'] @@ -137,61 +157,74 @@ class PetApi(object): method = 'POST' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json', 'application/xml']) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type(['application/json', 'application/xml']) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def find_pets_by_status(self, **kwargs): """ Finds Pets by status Multiple status values can be provided with comma seperated strings - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.find_pets_by_status(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - :param list[str] status: Status values that need to be considered for filter - + :param callback function: The callback function + for asynchronous request. (optional) + :param list[str] status: Status values that need to be considered for filter :return: list[Pet] - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['status'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_status" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method find_pets_by_status" % key + ) params[key] = val del params['kwargs'] @@ -199,61 +232,74 @@ class PetApi(object): method = 'GET' path_params = {} - + query_params = {} - if 'status' in params: query_params['status'] = params['status'] - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='list[Pet]', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def find_pets_by_tags(self, **kwargs): """ Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.find_pets_by_tags(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - :param list[str] tags: Tags to filter by - + :param callback function: The callback function + for asynchronous request. (optional) + :param list[str] tags: Tags to filter by :return: list[Pet] - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['tags'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_tags" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method find_pets_by_tags" % key + ) params[key] = val del params['kwargs'] @@ -261,65 +307,77 @@ class PetApi(object): method = 'GET' path_params = {} - + query_params = {} - if 'tags' in params: query_params['tags'] = params['tags'] - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='list[Pet]', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def get_pet_by_id(self, pet_id, **kwargs): """ Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_pet_by_id(pet_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param int pet_id: ID of pet that needs to be fetched (required) - :return: Pet - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") - + all_params = ['pet_id'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method get_pet_by_id" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_pet_by_id" % key + ) params[key] = val del params['kwargs'] @@ -327,67 +385,79 @@ class PetApi(object): method = 'GET' path_params = {} - if 'pet_id' in params: - path_params['petId'] = params['pet_id'] - + path_params['petId'] = params['pet_id'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = ['api_key', 'petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='Pet', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='Pet', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def update_pet_with_form(self, pet_id, **kwargs): """ Updates a pet in the store with form data - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update_pet_with_form(pet_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str pet_id: ID of pet that needs to be updated (required) - :param str name: Updated name of the pet - :param str status: Updated status of the pet - + :param str name: Updated name of the pet + :param str status: Updated status of the pet :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") - + all_params = ['pet_id', 'name', 'status'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method update_pet_with_form" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method update_pet_with_form" % key + ) params[key] = val del params['kwargs'] @@ -395,72 +465,82 @@ class PetApi(object): method = 'POST' path_params = {} - if 'pet_id' in params: - path_params['petId'] = params['pet_id'] - + path_params['petId'] = params['pet_id'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - if 'name' in params: form_params['name'] = params['name'] - if 'status' in params: form_params['status'] = params['status'] - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type(['application/x-www-form-urlencoded']) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type(['application/x-www-form-urlencoded']) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def delete_pet(self, pet_id, **kwargs): """ Deletes a pet - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete_pet(pet_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param int pet_id: Pet id to delete (required) - :param str api_key: - + :param str api_key: :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") - + all_params = ['pet_id', 'api_key'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_pet" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_pet" % key + ) params[key] = val del params['kwargs'] @@ -468,70 +548,81 @@ class PetApi(object): method = 'DELETE' path_params = {} - if 'pet_id' in params: - path_params['petId'] = params['pet_id'] - + path_params['petId'] = params['pet_id'] + query_params = {} - + header_params = {} - if 'api_key' in params: header_params['api_key'] = params['api_key'] - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def upload_file(self, pet_id, **kwargs): """ uploads an image - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.upload_file(pet_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param int pet_id: ID of pet to update (required) - :param str additional_metadata: Additional data to pass to server - :param file file: file to upload - + :param str additional_metadata: Additional data to pass to server + :param file file: file to upload :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") - + all_params = ['pet_id', 'additional_metadata', 'file'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method upload_file" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method upload_file" % key + ) params[key] = val del params['kwargs'] @@ -539,38 +630,43 @@ class PetApi(object): method = 'POST' path_params = {} - if 'pet_id' in params: - path_params['petId'] = params['pet_id'] - + path_params['petId'] = params['pet_id'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - if 'additional_metadata' in params: form_params['additionalMetadata'] = params['additional_metadata'] - if 'file' in params: files['file'] = params['file'] - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type(['multipart/form-data']) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type(['multipart/form-data']) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index 702cd814aa6..4dca0af85e2 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python # coding: utf-8 """ @@ -16,9 +15,8 @@ Copyright 2015 SmartBear Software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ + from __future__ import absolute_import import sys @@ -30,7 +28,12 @@ from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient + class StoreApi(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ def __init__(self, api_client=None): config = Configuration() @@ -40,33 +43,37 @@ class StoreApi(object): if not config.api_client: config.api_client = ApiClient('http://petstore.swagger.io/v2') self.api_client = config.api_client - - + def get_inventory(self, **kwargs): """ Returns pet inventories by status Returns a map of status codes to quantities - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_inventory(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - + :param callback function: The callback function + for asynchronous request. (optional) :return: dict(str, int) - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = [] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method get_inventory" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_inventory" % key + ) params[key] = val del params['kwargs'] @@ -74,58 +81,72 @@ class StoreApi(object): method = 'GET' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = ['api_key'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='dict(str, int)', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='dict(str, int)', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def place_order(self, **kwargs): """ Place an order for a pet - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.place_order(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - :param Order body: order placed for purchasing the pet - + :param callback function: The callback function + for asynchronous request. (optional) + :param Order body: order placed for purchasing the pet :return: Order - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method place_order" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method place_order" % key + ) params[key] = val del params['kwargs'] @@ -133,65 +154,77 @@ class StoreApi(object): method = 'POST' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='Order', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='Order', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def get_order_by_id(self, order_id, **kwargs): """ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_order_by_id(order_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str order_id: ID of pet that needs to be fetched (required) - :return: Order - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - # verify the required parameter 'order_id' is set if order_id is None: raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") - + all_params = ['order_id'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method get_order_by_id" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_order_by_id" % key + ) params[key] = val del params['kwargs'] @@ -199,65 +232,77 @@ class StoreApi(object): method = 'GET' path_params = {} - if 'order_id' in params: - path_params['orderId'] = params['order_id'] - + path_params['orderId'] = params['order_id'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='Order', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='Order', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def delete_order(self, order_id, **kwargs): """ Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete_order(order_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str order_id: ID of the order that needs to be deleted (required) - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - # verify the required parameter 'order_id' is set if order_id is None: raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") - + all_params = ['order_id'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_order" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_order" % key + ) params[key] = val del params['kwargs'] @@ -265,32 +310,39 @@ class StoreApi(object): method = 'DELETE' path_params = {} - if 'order_id' in params: - path_params['orderId'] = params['order_id'] - + path_params['orderId'] = params['order_id'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index 83b6941e002..4897abe8801 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python # coding: utf-8 """ @@ -16,9 +15,8 @@ Copyright 2015 SmartBear Software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ + from __future__ import absolute_import import sys @@ -30,7 +28,12 @@ from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient + class UserApi(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ def __init__(self, api_client=None): config = Configuration() @@ -40,34 +43,38 @@ class UserApi(object): if not config.api_client: config.api_client = ApiClient('http://petstore.swagger.io/v2') self.api_client = config.api_client - - + def create_user(self, **kwargs): """ Create user This can only be done by the logged in user. - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_user(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - :param User body: Created user object - + :param callback function: The callback function + for asynchronous request. (optional) + :param User body: Created user object :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method create_user" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method create_user" % key + ) params[key] = val del params['kwargs'] @@ -75,61 +82,74 @@ class UserApi(object): method = 'POST' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def create_users_with_array_input(self, **kwargs): """ Creates list of users with given input array - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_users_with_array_input(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - :param list[User] body: List of user object - + :param callback function: The callback function + for asynchronous request. (optional) + :param list[User] body: List of user object :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_array_input" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method create_users_with_array_input" % key + ) params[key] = val del params['kwargs'] @@ -137,61 +157,74 @@ class UserApi(object): method = 'POST' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def create_users_with_list_input(self, **kwargs): """ Creates list of users with given input array - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_users_with_list_input(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - :param list[User] body: List of user object - + :param callback function: The callback function + for asynchronous request. (optional) + :param list[User] body: List of user object :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_list_input" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method create_users_with_list_input" % key + ) params[key] = val del params['kwargs'] @@ -199,62 +232,75 @@ class UserApi(object): method = 'POST' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def login_user(self, **kwargs): """ Logs user into the system - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.login_user(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - :param str username: The user name for login - :param str password: The password for login in clear text - + :param callback function: The callback function + for asynchronous request. (optional) + :param str username: The user name for login + :param str password: The password for login in clear text :return: str - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['username', 'password'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method login_user" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method login_user" % key + ) params[key] = val del params['kwargs'] @@ -262,63 +308,75 @@ class UserApi(object): method = 'GET' path_params = {} - + query_params = {} - if 'username' in params: query_params['username'] = params['username'] - if 'password' in params: query_params['password'] = params['password'] - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='str', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='str', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def logout_user(self, **kwargs): """ Logs out current logged in user session - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.logout_user(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - + :param callback function: The callback function + for asynchronous request. (optional) :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = [] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method logout_user" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method logout_user" % key + ) params[key] = val del params['kwargs'] @@ -326,62 +384,75 @@ class UserApi(object): method = 'GET' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def get_user_by_name(self, username, **kwargs): """ Get user by user name - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_user_by_name(username, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str username: The name that needs to be fetched. Use user1 for testing. (required) - :return: User - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - # verify the required parameter 'username' is set if username is None: raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") - + all_params = ['username'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method get_user_by_name" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_user_by_name" % key + ) params[key] = val del params['kwargs'] @@ -389,66 +460,78 @@ class UserApi(object): method = 'GET' path_params = {} - if 'username' in params: - path_params['username'] = params['username'] - + path_params['username'] = params['username'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='User', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='User', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def update_user(self, username, **kwargs): """ Updated user This can only be done by the logged in user. - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update_user(username, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str username: name that need to be deleted (required) - :param User body: Updated user object - + :param User body: Updated user object :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - # verify the required parameter 'username' is set if username is None: raise ValueError("Missing the required parameter `username` when calling `update_user`") - + all_params = ['username', 'body'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method update_user" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method update_user" % key + ) params[key] = val del params['kwargs'] @@ -456,68 +539,79 @@ class UserApi(object): method = 'PUT' path_params = {} - if 'username' in params: - path_params['username'] = params['username'] - + path_params['username'] = params['username'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def delete_user(self, username, **kwargs): """ Delete user This can only be done by the logged in user. - SDK also supports asynchronous requests in which you can define a `callback` function - to be passed along and invoked when receiving response: + This method makes a synchronous HTTP request by default.To make an + asynchronous HTTP request, please define a `callback` function + to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete_user(username, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str username: The name that needs to be deleted (required) - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - # verify the required parameter 'username' is set if username is None: raise ValueError("Missing the required parameter `username` when calling `delete_user`") - + all_params = ['username'] all_params.append('callback') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_user" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_user" % key + ) params[key] = val del params['kwargs'] @@ -525,32 +619,39 @@ class UserApi(object): method = 'DELETE' path_params = {} - if 'username' in params: - path_params['username'] = params['username'] - + path_params['username'] = params['username'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + header_params['Accept'] = self.api_client.\ + select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index aff44cd2fa3..8f469b72653 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -1,10 +1,35 @@ +# coding: utf-8 + +""" +Copyright 2015 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +""" + from __future__ import absolute_import import base64 import urllib3 -import httplib + +try: + import httplib +except ImportError: + # python3 + import http.client as httplib + import sys import logging + def singleton(cls, *args, **kw): instances = {} @@ -17,24 +42,45 @@ def singleton(cls, *args, **kw): @singleton class Configuration(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + https://github.com/swagger-api/swagger-codegen + Do not edit the class manually. + """ def __init__(self): + """ + Constructor + """ # Default Base url self.host = "http://petstore.swagger.io/v2" # Default api client self.api_client = None + # Temp file folder for download + self.temp_folder_path = None + # Authentication Settings + # dict to store API key(s) self.api_key = {} + # dict to store API prefix (e.g. Bearer) self.api_key_prefix = {} + # Username for HTTP basic authentication self.username = "" + # Password for HTTP basic authentication self.password = "" + # Logging Settings self.logging_format = '%(asctime)s %(levelname)s %(message)s' + # Debug file location self.__logging_file = None + # Debug switch self.__debug = False self.init_logger() def init_logger(self): + """ + Initializes logger settings. + """ self.logger = logging.getLogger() formatter = logging.Formatter(self.logging_format) stream_handler = logging.StreamHandler() @@ -79,36 +125,52 @@ class Configuration(object): # setting log level to default `logging.WARNING` self.logger.setLevel(logging.WARNING) - def get_api_key_with_prefix(self, key): - """ Return api key prepend prefix for key """ - if self.api_key.get(key) and self.api_key_prefix.get(key): - return self.api_key_prefix[key] + ' ' + self.api_key[key] - elif self.api_key.get(key): - return self.api_key[key] + def get_api_key_with_prefix(self, identifier): + """ + Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :return: The token for api key authentication. + """ + if self.api_key.get(identifier) and self.api_key_prefix.get(identifier): + return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier] + elif self.api_key.get(identifier): + return self.api_key[identifier] def get_basic_auth_token(self): - """ Return basic auth header string """ + """ + Gets basic auth header string. + + :return: The token for basic HTTP authentication. + """ return urllib3.util.make_headers(basic_auth=self.username + ':' + self.password)\ .get('authorization') def auth_settings(self): - """ Return Auth Settings for api client """ - return { - 'api_key': { - 'type': 'api_key', - 'in': 'header', - 'key': 'api_key', - 'value': self.get_api_key_with_prefix('api_key') - }, - - } + """ + Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + return { + 'api_key': + { + 'type': 'api_key', + 'in': 'header', + 'key': 'api_key', + 'value': self.get_api_key_with_prefix('api_key') + }, + } def to_debug_report(self): + """ + Gets the essential information for debugging. + + :return: The report for debugging. + """ return "Python SDK Debug Report:\n"\ "OS: {env}\n"\ "Python Version: {pyversion}\n"\ "Version of the API: 1.0.0\n"\ - "SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version) - - - + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) diff --git a/samples/client/petstore/python/swagger_client/models/__init__.py b/samples/client/petstore/python/swagger_client/models/__init__.py index de307a26503..236f10e934a 100644 --- a/samples/client/petstore/python/swagger_client/models/__init__.py +++ b/samples/client/petstore/python/swagger_client/models/__init__.py @@ -6,4 +6,3 @@ from .category import Category from .pet import Pet from .tag import Tag from .order import Order - diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py index cfd69ee955c..615e65ea839 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/swagger_client/models/category.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python # coding: utf-8 """ @@ -17,18 +16,23 @@ Copyright 2015 SmartBear Software limitations under the License. """ +from pprint import pformat +from six import iteritems + + class Category(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { 'id': 'int', @@ -39,20 +43,83 @@ class Category(object): 'id': 'id', 'name': 'name' } - - - self.id = None # int - - - self.name = None # str - + + self._id = None + self._name = None + + @property + def id(self): + """ + Gets the id of this Category. + + + :return: The id of this Category. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """ + Sets the id of this Category. + + + :param id: The id of this Category. + :type: int + """ + self._id = id + + @property + def name(self): + """ + Gets the name of this Category. + + + :return: The name of this Category. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """ + Sets the name of this Category. + + + :param name: The name of this Category. + :type: str + """ + self._name = name + + def to_dict(self): + """ + Return model properties dict + """ + result = {} + + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) - - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) - - + """ + For `print` and `pprint` + """ + return self.to_str() diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/swagger_client/models/order.py index 2e448f5f425..a381853b91f 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/swagger_client/models/order.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python # coding: utf-8 """ @@ -17,18 +16,23 @@ Copyright 2015 SmartBear Software limitations under the License. """ +from pprint import pformat +from six import iteritems + + class Order(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { 'id': 'int', @@ -47,32 +51,181 @@ class Order(object): 'status': 'status', 'complete': 'complete' } - - - self.id = None # int - - - self.pet_id = None # int - - - self.quantity = None # int - - - self.ship_date = None # datetime - - # Order Status - self.status = None # str - - - self.complete = None # bool - + + self._id = None + self._pet_id = None + self._quantity = None + self._ship_date = None + self._status = None + self._complete = None + + @property + def id(self): + """ + Gets the id of this Order. + + + :return: The id of this Order. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """ + Sets the id of this Order. + + + :param id: The id of this Order. + :type: int + """ + self._id = id + + @property + def pet_id(self): + """ + Gets the pet_id of this Order. + + + :return: The pet_id of this Order. + :rtype: int + """ + return self._pet_id + + @pet_id.setter + def pet_id(self, pet_id): + """ + Sets the pet_id of this Order. + + + :param pet_id: The pet_id of this Order. + :type: int + """ + self._pet_id = pet_id + + @property + def quantity(self): + """ + Gets the quantity of this Order. + + + :return: The quantity of this Order. + :rtype: int + """ + return self._quantity + + @quantity.setter + def quantity(self, quantity): + """ + Sets the quantity of this Order. + + + :param quantity: The quantity of this Order. + :type: int + """ + self._quantity = quantity + + @property + def ship_date(self): + """ + Gets the ship_date of this Order. + + + :return: The ship_date of this Order. + :rtype: datetime + """ + return self._ship_date + + @ship_date.setter + def ship_date(self, ship_date): + """ + Sets the ship_date of this Order. + + + :param ship_date: The ship_date of this Order. + :type: datetime + """ + self._ship_date = ship_date + + @property + def status(self): + """ + Gets the status of this Order. + Order Status + + :return: The status of this Order. + :rtype: str + """ + return self._status + + @status.setter + def status(self, status): + """ + Sets the status of this Order. + Order Status + + :param status: The status of this Order. + :type: str + """ + allowed_values = ["placed", "approved", "delivered"] + if status not in allowed_values: + raise ValueError( + "Invalid value for `status`, must be one of {0}" + .format(allowed_values) + ) + self._status = status + + @property + def complete(self): + """ + Gets the complete of this Order. + + + :return: The complete of this Order. + :rtype: bool + """ + return self._complete + + @complete.setter + def complete(self, complete): + """ + Sets the complete of this Order. + + + :param complete: The complete of this Order. + :type: bool + """ + self._complete = complete + + def to_dict(self): + """ + Return model properties dict + """ + result = {} + + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) - - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) - - + """ + For `print` and `pprint` + """ + return self.to_str() diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py index a943b639663..57dc93387a9 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/swagger_client/models/pet.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python # coding: utf-8 """ @@ -17,18 +16,23 @@ Copyright 2015 SmartBear Software limitations under the License. """ +from pprint import pformat +from six import iteritems + + class Pet(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { 'id': 'int', @@ -47,32 +51,181 @@ class Pet(object): 'tags': 'tags', 'status': 'status' } - - - self.id = None # int - - - self.category = None # Category - - - self.name = None # str - - - self.photo_urls = None # list[str] - - - self.tags = None # list[Tag] - - # pet status in the store - self.status = None # str - + + self._id = None + self._category = None + self._name = None + self._photo_urls = None + self._tags = None + self._status = None + + @property + def id(self): + """ + Gets the id of this Pet. + + + :return: The id of this Pet. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """ + Sets the id of this Pet. + + + :param id: The id of this Pet. + :type: int + """ + self._id = id + + @property + def category(self): + """ + Gets the category of this Pet. + + + :return: The category of this Pet. + :rtype: Category + """ + return self._category + + @category.setter + def category(self, category): + """ + Sets the category of this Pet. + + + :param category: The category of this Pet. + :type: Category + """ + self._category = category + + @property + def name(self): + """ + Gets the name of this Pet. + + + :return: The name of this Pet. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """ + Sets the name of this Pet. + + + :param name: The name of this Pet. + :type: str + """ + self._name = name + + @property + def photo_urls(self): + """ + Gets the photo_urls of this Pet. + + + :return: The photo_urls of this Pet. + :rtype: list[str] + """ + return self._photo_urls + + @photo_urls.setter + def photo_urls(self, photo_urls): + """ + Sets the photo_urls of this Pet. + + + :param photo_urls: The photo_urls of this Pet. + :type: list[str] + """ + self._photo_urls = photo_urls + + @property + def tags(self): + """ + Gets the tags of this Pet. + + + :return: The tags of this Pet. + :rtype: list[Tag] + """ + return self._tags + + @tags.setter + def tags(self, tags): + """ + Sets the tags of this Pet. + + + :param tags: The tags of this Pet. + :type: list[Tag] + """ + self._tags = tags + + @property + def status(self): + """ + Gets the status of this Pet. + pet status in the store + + :return: The status of this Pet. + :rtype: str + """ + return self._status + + @status.setter + def status(self, status): + """ + Sets the status of this Pet. + pet status in the store + + :param status: The status of this Pet. + :type: str + """ + allowed_values = ["available", "pending", "sold"] + if status not in allowed_values: + raise ValueError( + "Invalid value for `status`, must be one of {0}" + .format(allowed_values) + ) + self._status = status + + def to_dict(self): + """ + Return model properties dict + """ + result = {} + + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) - - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) - - + """ + For `print` and `pprint` + """ + return self.to_str() diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py index 6347352eba7..bfa389520a3 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/swagger_client/models/tag.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python # coding: utf-8 """ @@ -17,18 +16,23 @@ Copyright 2015 SmartBear Software limitations under the License. """ +from pprint import pformat +from six import iteritems + + class Tag(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { 'id': 'int', @@ -39,20 +43,83 @@ class Tag(object): 'id': 'id', 'name': 'name' } - - - self.id = None # int - - - self.name = None # str - + + self._id = None + self._name = None + + @property + def id(self): + """ + Gets the id of this Tag. + + + :return: The id of this Tag. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """ + Sets the id of this Tag. + + + :param id: The id of this Tag. + :type: int + """ + self._id = id + + @property + def name(self): + """ + Gets the name of this Tag. + + + :return: The name of this Tag. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """ + Sets the name of this Tag. + + + :param name: The name of this Tag. + :type: str + """ + self._name = name + + def to_dict(self): + """ + Return model properties dict + """ + result = {} + + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) - - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) - - + """ + For `print` and `pprint` + """ + return self.to_str() diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/swagger_client/models/user.py index 83efcd9ee2b..7380bc94582 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/swagger_client/models/user.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python # coding: utf-8 """ @@ -17,18 +16,23 @@ Copyright 2015 SmartBear Software limitations under the License. """ +from pprint import pformat +from six import iteritems + + class User(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { 'id': 'int', @@ -51,38 +55,221 @@ class User(object): 'phone': 'phone', 'user_status': 'userStatus' } - - - self.id = None # int - - - self.username = None # str - - - self.first_name = None # str - - - self.last_name = None # str - - - self.email = None # str - - - self.password = None # str - - - self.phone = None # str - - # User Status - self.user_status = None # int - + + self._id = None + self._username = None + self._first_name = None + self._last_name = None + self._email = None + self._password = None + self._phone = None + self._user_status = None + + @property + def id(self): + """ + Gets the id of this User. + + + :return: The id of this User. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """ + Sets the id of this User. + + + :param id: The id of this User. + :type: int + """ + self._id = id + + @property + def username(self): + """ + Gets the username of this User. + + + :return: The username of this User. + :rtype: str + """ + return self._username + + @username.setter + def username(self, username): + """ + Sets the username of this User. + + + :param username: The username of this User. + :type: str + """ + self._username = username + + @property + def first_name(self): + """ + Gets the first_name of this User. + + + :return: The first_name of this User. + :rtype: str + """ + return self._first_name + + @first_name.setter + def first_name(self, first_name): + """ + Sets the first_name of this User. + + + :param first_name: The first_name of this User. + :type: str + """ + self._first_name = first_name + + @property + def last_name(self): + """ + Gets the last_name of this User. + + + :return: The last_name of this User. + :rtype: str + """ + return self._last_name + + @last_name.setter + def last_name(self, last_name): + """ + Sets the last_name of this User. + + + :param last_name: The last_name of this User. + :type: str + """ + self._last_name = last_name + + @property + def email(self): + """ + Gets the email of this User. + + + :return: The email of this User. + :rtype: str + """ + return self._email + + @email.setter + def email(self, email): + """ + Sets the email of this User. + + + :param email: The email of this User. + :type: str + """ + self._email = email + + @property + def password(self): + """ + Gets the password of this User. + + + :return: The password of this User. + :rtype: str + """ + return self._password + + @password.setter + def password(self, password): + """ + Sets the password of this User. + + + :param password: The password of this User. + :type: str + """ + self._password = password + + @property + def phone(self): + """ + Gets the phone of this User. + + + :return: The phone of this User. + :rtype: str + """ + return self._phone + + @phone.setter + def phone(self, phone): + """ + Sets the phone of this User. + + + :param phone: The phone of this User. + :type: str + """ + self._phone = phone + + @property + def user_status(self): + """ + Gets the user_status of this User. + User Status + + :return: The user_status of this User. + :rtype: int + """ + return self._user_status + + @user_status.setter + def user_status(self, user_status): + """ + Sets the user_status of this User. + User Status + + :param user_status: The user_status of this User. + :type: int + """ + self._user_status = user_status + + def to_dict(self): + """ + Return model properties dict + """ + result = {} + + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) - - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) - - + """ + For `print` and `pprint` + """ + return self.to_str() diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/swagger_client/rest.py index 7cf08f50429..8a8e55eb3d1 100644 --- a/samples/client/petstore/python/swagger_client/rest.py +++ b/samples/client/petstore/python/swagger_client/rest.py @@ -1,6 +1,20 @@ # coding: utf-8 """ +Copyright 2015 SmartBear Software + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + Credit: this file (rest.py) is modified based on rest.py in Dropbox Python SDK: https://www.dropbox.com/developers/core/sdks/python """ @@ -51,6 +65,7 @@ class RESTResponse(io.IOBase): """ return self.urllib3_response.getheader(name, default) + class RESTClientObject(object): def __init__(self, pools_size=4): @@ -87,14 +102,17 @@ class RESTClientObject(object): :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` - :param post_params: request post parameters, `application/x-www-form-urlencode` + :param post_params: request post parameters, + `application/x-www-form-urlencode` and `multipart/form-data` """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] if post_params and body: - raise ValueError("body parameter cannot be used with post_params parameter.") + raise ValueError( + "body parameter cannot be used with post_params parameter." + ) post_params = post_params or {} headers = headers or {} @@ -144,22 +162,37 @@ class RESTClientObject(object): return r def GET(self, url, headers=None, query_params=None): - return self.request("GET", url, headers=headers, query_params=query_params) + return self.request("GET", url, + headers=headers, + query_params=query_params) def HEAD(self, url, headers=None, query_params=None): - return self.request("HEAD", url, headers=headers, query_params=query_params) + return self.request("HEAD", url, + headers=headers, + query_params=query_params) def DELETE(self, url, headers=None, query_params=None): - return self.request("DELETE", url, headers=headers, query_params=query_params) + return self.request("DELETE", url, + headers=headers, + query_params=query_params) def POST(self, url, headers=None, post_params=None, body=None): - return self.request("POST", url, headers=headers, post_params=post_params, body=body) + return self.request("POST", url, + headers=headers, + post_params=post_params, + body=body) def PUT(self, url, headers=None, post_params=None, body=None): - return self.request("PUT", url, headers=headers, post_params=post_params, body=body) + return self.request("PUT", url, + headers=headers, + post_params=post_params, + body=body) def PATCH(self, url, headers=None, post_params=None, body=None): - return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) + return self.request("PATCH", url, + headers=headers, + post_params=post_params, + body=body) class ApiException(Exception): @@ -183,13 +216,14 @@ class ApiException(Exception): error_message = "({0})\n"\ "Reason: {1}\n".format(self.status, self.reason) if self.headers: - error_message += "HTTP response headers: {0}".format(self.headers) + error_message += "HTTP response headers: {0}\n".format(self.headers) if self.body: - error_message += "HTTP response body: {0}".format(self.body) + error_message += "HTTP response body: {0}\n".format(self.body) return error_message + class RESTClient(object): """ A class with all class methods to perform JSON requests. diff --git a/samples/client/petstore/python/tests/test_deserialization.py b/samples/client/petstore/python/tests/test_deserialization.py index 1121558adca..1eae045ff76 100644 --- a/samples/client/petstore/python/tests/test_deserialization.py +++ b/samples/client/petstore/python/tests/test_deserialization.py @@ -150,6 +150,28 @@ class DeserializationTests(unittest.TestCase): self.assertEqual(deserialized[0].name, "doggie0") self.assertEqual(deserialized[1].name, "doggie1") + def test_deserialize_nested_dict(self): + """ deserialize dict(str, dict(str, int)) """ + data = { + "foo": { + "bar": 1 + } + } + + deserialized = self.deserialize(data, "dict(str, dict(str, int))") + self.assertTrue(isinstance(deserialized, dict)) + self.assertTrue(isinstance(deserialized["foo"], dict)) + self.assertTrue(isinstance(deserialized["foo"]["bar"], int)) + + def test_deserialize_nested_list(self): + """ deserialize list[list[str]] """ + data = [["foo"]] + + deserialized = self.deserialize(data, "list[list[str]]") + self.assertTrue(isinstance(deserialized, list)) + self.assertTrue(isinstance(deserialized[0], list)) + self.assertTrue(isinstance(deserialized[0][0], str)) + def test_deserialize_none(self): """ deserialize None """ deserialized = self.deserialize(None, "datetime") diff --git a/samples/client/petstore/python/tests/test_order_model.py b/samples/client/petstore/python/tests/test_order_model.py new file mode 100644 index 00000000000..e411ca0103d --- /dev/null +++ b/samples/client/petstore/python/tests/test_order_model.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" +Run the tests. +$ pip install nose (optional) +$ cd swagger_client-python +$ nosetests -v +""" + +import os +import time +import unittest + +import swagger_client + + +class OrderModelTests(unittest.TestCase): + + def test_status(self): + order = swagger_client.Order() + order.status = "placed" + self.assertEqual("placed", order.status) + + with self.assertRaises(ValueError): + order.status = "invalid" diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index f78a301a9dc..6994ddbd649 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -35,7 +35,7 @@ class PetApiTests(unittest.TestCase): self.category.name = "dog" self.tag = swagger_client.Tag() self.tag.id = int(time.time()) - self.tag.name = "blank" + self.tag.name = "swagger-codegen-python-pet-tag" self.pet = swagger_client.Pet() self.pet.id = int(time.time()) self.pet.name = "hello kity" diff --git a/samples/client/petstore/python/tests/test_pet_model.py b/samples/client/petstore/python/tests/test_pet_model.py new file mode 100644 index 00000000000..0b0df18a8d0 --- /dev/null +++ b/samples/client/petstore/python/tests/test_pet_model.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" +Run the tests. +$ pip install nose (optional) +$ cd swagger_client-python +$ nosetests -v +""" + +import os +import time +import unittest + +import swagger_client + + +class PetModelTests(unittest.TestCase): + + def setUp(self): + self.pet = swagger_client.Pet() + self.pet.name = "test name" + self.pet.id = 1 + self.pet.photo_urls = ["string"] + self.pet.status = "available" + cate = swagger_client.Category() + cate.id = 1 + cate.name = "dog" + self.pet.category = cate + tag = swagger_client.Tag() + tag.id = 1 + self.pet.tags = [tag] + + def test_to_str(self): + data = ("{'category': {'id': 1, 'name': 'dog'},\n" + " 'id': 1,\n" + " 'name': 'test name',\n" + " 'photo_urls': ['string'],\n" + " 'status': 'available',\n" + " 'tags': [{'id': 1, 'name': None}]}") + self.assertEqual(data, self.pet.to_str()) diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/ServiceGenerator.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/ServiceGenerator.java index e443c984fd0..1ffb0c58b0c 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/ServiceGenerator.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/ServiceGenerator.java @@ -2,8 +2,20 @@ package io.swagger.client; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.IOException; +import java.lang.reflect.Type; + import retrofit.RestAdapter; +import retrofit.converter.ConversionException; +import retrofit.converter.Converter; import retrofit.converter.GsonConverter; +import retrofit.mime.TypedByteArray; +import retrofit.mime.TypedInput; +import retrofit.mime.TypedOutput; public class ServiceGenerator { // No need to instantiate this class. @@ -15,9 +27,63 @@ public class ServiceGenerator { .create(); RestAdapter adapter = new RestAdapter.Builder() .setEndpoint("http://petstore.swagger.io/v2") - .setConverter(new GsonConverter(gson)) + .setConverter(new GsonConverterWrapper(gson)) .build(); return adapter.create(serviceClass); } } + +/** + * This wrapper is to take care of this case: + * when the deserialization fails due to JsonParseException and the + * expected type is String, then just return the body string. + */ +class GsonConverterWrapper implements Converter { + private GsonConverter converter; + + public GsonConverterWrapper(Gson gson) { + converter = new GsonConverter(gson); + } + + @Override public Object fromBody(TypedInput body, Type type) throws ConversionException { + byte[] bodyBytes = readInBytes(body); + TypedByteArray newBody = new TypedByteArray(body.mimeType(), bodyBytes); + try { + return converter.fromBody(newBody, type); + } catch (ConversionException e) { + if (e.getCause() instanceof JsonParseException && type.equals(String.class)) { + return new String(bodyBytes); + } else { + throw e; + } + } + } + + @Override public TypedOutput toBody(Object object) { + return converter.toBody(object); + } + + private byte[] readInBytes(TypedInput body) throws ConversionException { + InputStream in = null; + try { + in = body.in(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + byte[] buffer = new byte[0xFFFF]; + for (int len; (len = in.read(buffer)) != -1;) + os.write(buffer, 0, len); + os.flush(); + return os.toByteArray(); + } catch (IOException e) { + throw new ConversionException(e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException ignored) { + } + } + } + + } +} diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 3d1b0893b61..cca8370a181 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -10,108 +10,108 @@ import io.swagger.client.model.Pet; import java.io.File; public interface PetApi { - + /** * Update an existing pet - * + * * @param body Pet object that needs to be added to the store * @return Void */ - - @PUT("/pet") + + @PUT("/pet") Void updatePet( @Body Pet body - ); - + ); + /** * Add a new pet to the store - * + * * @param body Pet object that needs to be added to the store * @return Void */ - - @POST("/pet") + + @POST("/pet") Void addPet( @Body Pet body - ); - + ); + /** * Finds Pets by status * Multiple status values can be provided with comma seperated strings * @param status Status values that need to be considered for filter * @return List */ - - @GET("/pet/findByStatus") + + @GET("/pet/findByStatus") List findPetsByStatus( @Query("status") List status - ); - + ); + /** * Finds Pets by tags * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by * @return List */ - - @GET("/pet/findByTags") + + @GET("/pet/findByTags") List findPetsByTags( @Query("tags") List tags - ); - + ); + /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions * @param petId ID of pet that needs to be fetched * @return Pet */ - - @GET("/pet/{petId}") + + @GET("/pet/{petId}") Pet getPetById( @Path("petId") Long petId - ); - + ); + /** * Updates a pet in the store with form data - * + * * @param petId ID of pet that needs to be updated * @param name Updated name of the pet * @param status Updated status of the pet * @return Void */ - + @FormUrlEncoded - @POST("/pet/{petId}") + @POST("/pet/{petId}") Void updatePetWithForm( - @Path("petId") String petId,@Field("name") String name,@Field("status") String status - ); - + @Path("petId") String petId, @Field("name") String name, @Field("status") String status + ); + /** * Deletes a pet - * - * @param apiKey + * * @param petId Pet id to delete + * @param apiKey * @return Void */ - - @DELETE("/pet/{petId}") + + @DELETE("/pet/{petId}") Void deletePet( - @Header("api_key") String apiKey,@Path("petId") Long petId - ); - + @Path("petId") Long petId, @Header("api_key") String apiKey + ); + /** * uploads an image - * + * * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload * @return Void */ - + @Multipart - @POST("/pet/{petId}/uploadImage") + @POST("/pet/{petId}/uploadImage") Void uploadFile( - @Path("petId") Long petId,@Part("additionalMetadata") String additionalMetadata,@Part("file") TypedFile file - ); - + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file + ); + } diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java index 4aa39c52e2c..b80f9e5fa20 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -57,7 +57,7 @@ public interface UserApi { @GET("/user/login") String loginUser( - @Query("username") String username,@Query("password") String password + @Query("username") String username, @Query("password") String password ); /** @@ -92,7 +92,7 @@ public interface UserApi { @PUT("/user/{username}") Void updateUser( - @Path("username") String username,@Body User body + @Path("username") String username, @Body User body ); /** diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java index af9ba8880e0..7d1368a74e0 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; @@ -34,13 +34,13 @@ public class Pet { **/ @ApiModelProperty(required = true, value = "") @SerializedName("photoUrls") - private List photoUrls = new ArrayList() ; + private List photoUrls = null; /** **/ @ApiModelProperty(value = "") @SerializedName("tags") - private List tags = new ArrayList() ; + private List tags = null; public enum StatusEnum { available, pending, sold, }; diff --git a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java index 5151c941cd4..e7613f189a3 100644 --- a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -120,7 +120,7 @@ public class PetApiTest { api.addPet(pet); Pet fetched = api.getPetById(pet.getId()); - api.deletePet(null, fetched.getId()); + api.deletePet(fetched.getId(), null); try { fetched = api.getPetById(fetched.getId()); diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala index 1f9d3c012d5..df067bdab8b 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/ApiInvoker.scala @@ -59,7 +59,7 @@ class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, if (cls == classOf[String]) { json match { case s: String => { - if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 2) + if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 1) else s } case _ => null diff --git a/samples/client/petstore/typescript-angular/.gitignore b/samples/client/petstore/typescript-angular/.gitignore new file mode 100644 index 00000000000..abfad1bf5e2 --- /dev/null +++ b/samples/client/petstore/typescript-angular/.gitignore @@ -0,0 +1,3 @@ +/node_modules +/typings +/client.js \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/api/Category.ts b/samples/client/petstore/typescript-angular/API/Client/Category.ts similarity index 87% rename from samples/client/petstore/typescript-angular/api/Category.ts rename to samples/client/petstore/typescript-angular/API/Client/Category.ts index e4a3caa208e..7faf87208eb 100644 --- a/samples/client/petstore/typescript-angular/api/Category.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Category.ts @@ -1,6 +1,6 @@ /// -module api { +module API.Client { 'use strict'; export class Category { diff --git a/samples/client/petstore/typescript-angular/api/Order.ts b/samples/client/petstore/typescript-angular/API/Client/Order.ts similarity index 91% rename from samples/client/petstore/typescript-angular/api/Order.ts rename to samples/client/petstore/typescript-angular/API/Client/Order.ts index 3f37c608758..abee3a2894b 100644 --- a/samples/client/petstore/typescript-angular/api/Order.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Order.ts @@ -1,6 +1,6 @@ /// -module api { +module API.Client { 'use strict'; export class Order { @@ -11,7 +11,7 @@ module api { quantity: number; - shipDate: DateTime; + shipDate: Date; /** * Order Status diff --git a/samples/client/petstore/typescript-angular/api/Pet.ts b/samples/client/petstore/typescript-angular/API/Client/Pet.ts similarity index 96% rename from samples/client/petstore/typescript-angular/api/Pet.ts rename to samples/client/petstore/typescript-angular/API/Client/Pet.ts index c34be9c3dbc..9523bef90b0 100644 --- a/samples/client/petstore/typescript-angular/api/Pet.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Pet.ts @@ -1,6 +1,6 @@ /// -module api { +module API.Client { 'use strict'; export class Pet { diff --git a/samples/client/petstore/typescript-angular/api/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts similarity index 74% rename from samples/client/petstore/typescript-angular/api/PetApi.ts rename to samples/client/petstore/typescript-angular/API/Client/PetApi.ts index d294cfbebbc..6bb4e10d387 100644 --- a/samples/client/petstore/typescript-angular/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -2,12 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ -module api { +module API.Client { 'use strict'; - export class PetApi { - private basePath = 'http://petstore.swagger.io/v2'; + private basePath = '/v2'; static $inject: string[] = ['$http']; @@ -16,15 +15,13 @@ module api { this.basePath = basePath; } } - - public updatePet (body: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'PUT', url: path, @@ -32,11 +29,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -45,15 +42,13 @@ module api { return this.$http(httpRequestParams); } - - public addPet (body: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public addPet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -61,11 +56,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -74,28 +69,28 @@ module api { return this.$http(httpRequestParams); } - - public findPetsByStatus (status: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + + public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { var path = this.basePath + '/pet/findByStatus'; - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + if (status !== undefined) { queryParameters['status'] = status; } - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -104,28 +99,28 @@ module api { return this.$http(httpRequestParams); } - - public findPetsByTags (tags: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + + public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { var path = this.basePath + '/pet/findByTags'; - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + if (tags !== undefined) { queryParameters['tags'] = tags; } - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -134,33 +129,31 @@ module api { return this.$http(httpRequestParams); } - - public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/pet/{petId}'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling getPetById'); } - - - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -169,33 +162,31 @@ module api { return this.$http(httpRequestParams); } - - public updatePetWithForm (petId: string, name: string, status: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet/{petId}'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } - - - + var httpRequestParams: any = { method: 'POST', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -204,33 +195,33 @@ module api { return this.$http(httpRequestParams); } - - public deletePet (apiKey: string, petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet/{petId}'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling deletePet'); } - - + headerParams['apiKey'] = apiKey; + var httpRequestParams: any = { method: 'DELETE', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -239,33 +230,31 @@ module api { return this.$http(httpRequestParams); } - - public uploadFile (petId: number, additionalMetadata: string, file: file, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet/{petId}/uploadImage'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling uploadFile'); } - - - + var httpRequestParams: any = { method: 'POST', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -274,9 +263,5 @@ module api { return this.$http(httpRequestParams); } - } - - angular.module('api_PetApi', ['$http']) - .service('PetApi', PetApi); } diff --git a/samples/client/petstore/typescript-angular/api/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts similarity index 72% rename from samples/client/petstore/typescript-angular/api/StoreApi.ts rename to samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index e8c85b00c45..948b6859381 100644 --- a/samples/client/petstore/typescript-angular/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -2,12 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ -module api { +module API.Client { 'use strict'; - export class StoreApi { - private basePath = 'http://petstore.swagger.io/v2'; + private basePath = '/v2'; static $inject: string[] = ['$http']; @@ -16,26 +15,24 @@ module api { this.basePath = basePath; } } - - public getInventory ( extraHttpRequestParams?: any ) : ng.IHttpPromise> { + + public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> { var path = this.basePath + '/store/inventory'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -44,15 +41,13 @@ module api { return this.$http(httpRequestParams); } - - public placeOrder (body: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public placeOrder (body?: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/store/order'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -60,11 +55,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -73,33 +68,31 @@ module api { return this.$http(httpRequestParams); } - - public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/store/order/{orderId}'; - + path = path.replace('{' + 'orderId' + '}', String(orderId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling getOrderById'); } - - - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -108,33 +101,31 @@ module api { return this.$http(httpRequestParams); } - - public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/store/order/{orderId}'; - + path = path.replace('{' + 'orderId' + '}', String(orderId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling deleteOrder'); } - - - + var httpRequestParams: any = { method: 'DELETE', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -143,9 +134,5 @@ module api { return this.$http(httpRequestParams); } - } - - angular.module('api_StoreApi', ['$http']) - .service('StoreApi', StoreApi); } diff --git a/samples/client/petstore/typescript-angular/api/Tag.ts b/samples/client/petstore/typescript-angular/API/Client/Tag.ts similarity index 86% rename from samples/client/petstore/typescript-angular/api/Tag.ts rename to samples/client/petstore/typescript-angular/API/Client/Tag.ts index 33f0ffaa1e2..2ec9b456f27 100644 --- a/samples/client/petstore/typescript-angular/api/Tag.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Tag.ts @@ -1,6 +1,6 @@ /// -module api { +module API.Client { 'use strict'; export class Tag { diff --git a/samples/client/petstore/typescript-angular/api/User.ts b/samples/client/petstore/typescript-angular/API/Client/User.ts similarity index 94% rename from samples/client/petstore/typescript-angular/api/User.ts rename to samples/client/petstore/typescript-angular/API/Client/User.ts index 57385044943..ca8ac57c7a3 100644 --- a/samples/client/petstore/typescript-angular/api/User.ts +++ b/samples/client/petstore/typescript-angular/API/Client/User.ts @@ -1,6 +1,6 @@ /// -module api { +module API.Client { 'use strict'; export class User { diff --git a/samples/client/petstore/typescript-angular/api/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts similarity index 73% rename from samples/client/petstore/typescript-angular/api/UserApi.ts rename to samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 40d82f73852..eb04f4b31f0 100644 --- a/samples/client/petstore/typescript-angular/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -2,12 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ -module api { +module API.Client { 'use strict'; - export class UserApi { - private basePath = 'http://petstore.swagger.io/v2'; + private basePath = '/v2'; static $inject: string[] = ['$http']; @@ -16,15 +15,13 @@ module api { this.basePath = basePath; } } - - public createUser (body: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public createUser (body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -32,11 +29,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -45,15 +42,13 @@ module api { return this.$http(httpRequestParams); } - - public createUsersWithArrayInput (body: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public createUsersWithArrayInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/createWithArray'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -61,11 +56,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -74,15 +69,13 @@ module api { return this.$http(httpRequestParams); } - - public createUsersWithListInput (body: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public createUsersWithListInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/createWithList'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -90,11 +83,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -103,30 +96,32 @@ module api { return this.$http(httpRequestParams); } - - public loginUser (username: string, password: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/user/login'; - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + if (username !== undefined) { queryParameters['username'] = username; - }if (password !== undefined) { + } + + if (password !== undefined) { queryParameters['password'] = password; } - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -135,26 +130,24 @@ module api { return this.$http(httpRequestParams); } - - public logoutUser ( extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public logoutUser (extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/logout'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -163,33 +156,31 @@ module api { return this.$http(httpRequestParams); } - - public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/user/{username}'; - + path = path.replace('{' + 'username' + '}', String(username)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling getUserByName'); } - - - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -198,22 +189,20 @@ module api { return this.$http(httpRequestParams); } - - public updateUser (username: string, body: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public updateUser (username: string, body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/{username}'; - + path = path.replace('{' + 'username' + '}', String(username)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling updateUser'); } - - - + var httpRequestParams: any = { method: 'PUT', url: path, @@ -221,11 +210,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -234,33 +223,31 @@ module api { return this.$http(httpRequestParams); } - - public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/{username}'; - + path = path.replace('{' + 'username' + '}', String(username)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling deleteUser'); } - - - + var httpRequestParams: any = { method: 'DELETE', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -269,9 +256,5 @@ module api { return this.$http(httpRequestParams); } - } - - angular.module('api_UserApi', ['$http']) - .service('UserApi', UserApi); } diff --git a/samples/client/petstore/typescript-angular/api/api.d.ts b/samples/client/petstore/typescript-angular/API/Client/api.d.ts similarity index 100% rename from samples/client/petstore/typescript-angular/api/api.d.ts rename to samples/client/petstore/typescript-angular/API/Client/api.d.ts diff --git a/samples/client/petstore/typescript-angular/README.md b/samples/client/petstore/typescript-angular/README.md new file mode 100644 index 00000000000..3a4e49be9e8 --- /dev/null +++ b/samples/client/petstore/typescript-angular/README.md @@ -0,0 +1,19 @@ +# SwaggerClient + +Sample of TypeScript AngularJS petstore client + +## Testing the generated code + +``` +npm install +npm test +``` + +To clean the workspace run: +``` +npm run clean +``` + +## Author + +mads@maetzke-tandrup.dk \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/package.json b/samples/client/petstore/typescript-angular/package.json new file mode 100644 index 00000000000..f50b782c09f --- /dev/null +++ b/samples/client/petstore/typescript-angular/package.json @@ -0,0 +1,20 @@ +{ + "name": "petstore-typescript-node-sample", + "version": "1.0.0", + "description": "Sample of generated TypeScript petstore client", + "main": "api.js", + "scripts": { + "postinstall": "tsd reinstall --overwrite", + "test": "tsc", + "clean": "rm -Rf node_modules/ typings/ *.js" + }, + "author": "Mads M. Tandrup", + "license": "Apache 2.0", + "dependencies": { + "angular": "^1.4.3" + }, + "devDependencies": { + "tsd": "^0.6.3", + "typescript": "^1.5.3" + } +} diff --git a/samples/client/petstore/typescript-angular/tsconfig.json b/samples/client/petstore/typescript-angular/tsconfig.json new file mode 100644 index 00000000000..c389d5011ff --- /dev/null +++ b/samples/client/petstore/typescript-angular/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "noImplicitAny": true, + "out": "client.js" + }, + "files": [ + "API/Client/Category.ts", + "API/Client/Pet.ts", + "API/Client/StoreApi.ts", + "API/Client/User.ts", + "API/Client/api.d.ts", + "API/Client/Order.ts", + "API/Client/PetApi.ts", + "API/Client/Tag.ts", + "API/Client/UserApi.ts", + "typings/tsd.d.ts" + ] +} diff --git a/samples/client/petstore/typescript-angular/tsd.json b/samples/client/petstore/typescript-angular/tsd.json new file mode 100644 index 00000000000..182b9f68fa2 --- /dev/null +++ b/samples/client/petstore/typescript-angular/tsd.json @@ -0,0 +1,15 @@ +{ + "version": "v4", + "repo": "borisyankov/DefinitelyTyped", + "ref": "master", + "path": "typings", + "bundle": "typings/tsd.d.ts", + "installed": { + "angularjs/angular.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "jquery/jquery.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + } + } +} diff --git a/samples/client/petstore/typescript-node/.gitignore b/samples/client/petstore/typescript-node/.gitignore new file mode 100644 index 00000000000..5c06ad7bc24 --- /dev/null +++ b/samples/client/petstore/typescript-node/.gitignore @@ -0,0 +1,3 @@ +/node_modules +/typings +/*.js diff --git a/samples/client/petstore/typescript-node/README.md b/samples/client/petstore/typescript-node/README.md new file mode 100644 index 00000000000..82225d3260a --- /dev/null +++ b/samples/client/petstore/typescript-node/README.md @@ -0,0 +1,22 @@ +# SwaggerClient + +Sample of TypeScript Node.js petstore client + +## Testing the generated code + +``` +npm install +npm test +``` + +This will compile the code and run a small test application that will do some simple test calls to the Swagger Petstore API. + +To clean the workspace run: +``` +npm run clean +``` + + +## Author + +mads@maetzke-tandrup.dk \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts new file mode 100644 index 00000000000..0b7089fdaae --- /dev/null +++ b/samples/client/petstore/typescript-node/api.ts @@ -0,0 +1,1199 @@ +import request = require('request'); +import promise = require('bluebird'); +import http = require('http'); + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +/* tslint:disable:no-unused-variable */ + +export class User { + id: number; + username: string; + firstName: string; + lastName: string; + email: string; + password: string; + phone: string; + /** + * User Status + */ + userStatus: number; +} + +export class Category { + id: number; + name: string; +} + +export class Pet { + id: number; + category: Category; + name: string; + photoUrls: Array; + tags: Array; + /** + * pet status in the store + */ + status: Pet.StatusEnum; +} + +export module Pet { + export enum StatusEnum { + available = 'available', + pending = 'pending', + sold = 'sold', + } +} +export class Tag { + id: number; + name: string; +} + +export class Order { + id: number; + petId: number; + quantity: number; + shipDate: Date; + /** + * Order Status + */ + status: Order.StatusEnum; + complete: boolean; +} + +export module Order { + export enum StatusEnum { + placed = 'placed', + approved = 'approved', + delivered = 'delivered', + } +} + +interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: request.Options): void; +} + +class HttpBasicAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + requestOptions.auth = { + username: this.username, password: this.password + } + } +} + +class ApiKeyAuth implements Authentication { + public apiKey: string; + + constructor(private location: string, private paramName: string) { + } + + applyToRequest(requestOptions: request.Options): void { + if (this.location == "query") { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + } +} + +class OAuth implements Authentication { + applyToRequest(requestOptions: request.Options): void { + // TODO: support oauth + } +} + +class VoidAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + // Do nothing + } +} + +export class UserApi { + private basePath = '/v2'; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + + public createUser (body?: User) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/createWithArray'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/createWithList'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { + var path = this.url + this.basePath + '/user/login'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + if (username !== undefined) { + queryParameters['username'] = username; + } + + if (password !== undefined) { + queryParameters['password'] = password; + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public logoutUser () : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/logout'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { + var path = this.url + this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling getUserByName'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling updateUser'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public deleteUser (username: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling deleteUser'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +} +export class PetApi { + private basePath = '/v2'; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + + public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { + var path = this.url + this.basePath + '/pet/findByStatus'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + if (status !== undefined) { + queryParameters['status'] = status; + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { + var path = this.url + this.basePath + '/pet/findByTags'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + if (tags !== undefined) { + queryParameters['tags'] = tags; + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling getPetById'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.api_key.applyToRequest(requestOptions); + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling updatePetWithForm'); + } + + var useFormData = false; + + if (name !== undefined) { + formParams['name'] = name; + } + + if (status !== undefined) { + formParams['status'] = status; + } + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + + headerParams['apiKey'] = apiKey; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}/uploadImage'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling uploadFile'); + } + + var useFormData = false; + + if (additionalMetadata !== undefined) { + formParams['additionalMetadata'] = additionalMetadata; + } + + if (file !== undefined) { + formParams['file'] = file; + } + useFormData = true; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +} +export class StoreApi { + private basePath = '/v2'; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + + public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { + var path = this.url + this.basePath + '/store/inventory'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.api_key.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +} diff --git a/samples/client/petstore/typescript-node/api/PetApi.ts b/samples/client/petstore/typescript-node/api/PetApi.ts deleted file mode 100644 index 02605f2c8a8..00000000000 --- a/samples/client/petstore/typescript-node/api/PetApi.ts +++ /dev/null @@ -1,378 +0,0 @@ -/* tslint:disable:no-unused-variable */ - -export class PetApi { - private basePath = 'http://petstore.swagger.io/v2'; - - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - - public updatePet (body: Pet ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'PUT', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public addPet (body: Pet ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public findPetsByStatus (status: Array ) : Promise<{ response: http.ClientResponse; body: Array; }> { - var path = this.url + this.basePath + '/pet/findByStatus'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - if (status !== undefined) { - queryParameters['status'] = status; - } - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public findPetsByTags (tags: Array ) : Promise<{ response: http.ClientResponse; body: Array; }> { - var path = this.url + this.basePath + '/pet/findByTags'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - if (tags !== undefined) { - queryParameters['tags'] = tags; - } - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public getPetById (petId: number ) : Promise<{ response: http.ClientResponse; body: Pet; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public updatePetWithForm (petId: string, name: string, status: string ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public deletePet (apiKey: string, petId: number ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - - - - - headerParams['apiKey'] = apiKey; - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'DELETE', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public uploadFile (petId: number, additionalMetadata: string, file: file ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}/uploadImage'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - -} diff --git a/samples/client/petstore/typescript-node/api/StoreApi.ts b/samples/client/petstore/typescript-node/api/StoreApi.ts deleted file mode 100644 index 71cfe106fca..00000000000 --- a/samples/client/petstore/typescript-node/api/StoreApi.ts +++ /dev/null @@ -1,192 +0,0 @@ -/* tslint:disable:no-unused-variable */ - -export class StoreApi { - private basePath = 'http://petstore.swagger.io/v2'; - - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - - public getInventory ( ) : Promise<{ response: http.ClientResponse; body: map; }> { - var path = this.url + this.basePath + '/store/inventory'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: map; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public placeOrder (body: Order ) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public getOrderById (orderId: string ) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; - - - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public deleteOrder (orderId: string ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; - - - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'DELETE', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - -} diff --git a/samples/client/petstore/typescript-node/api/UserApi.ts b/samples/client/petstore/typescript-node/api/UserApi.ts deleted file mode 100644 index ca6fd41c593..00000000000 --- a/samples/client/petstore/typescript-node/api/UserApi.ts +++ /dev/null @@ -1,372 +0,0 @@ -/* tslint:disable:no-unused-variable */ - -export class UserApi { - private basePath = 'http://petstore.swagger.io/v2'; - - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - - public createUser (body: User ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public createUsersWithArrayInput (body: Array ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/createWithArray'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public createUsersWithListInput (body: Array ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/createWithList'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public loginUser (username: string, password: string ) : Promise<{ response: http.ClientResponse; body: string; }> { - var path = this.url + this.basePath + '/user/login'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - if (username !== undefined) { - queryParameters['username'] = username; - } - if (password !== undefined) { - queryParameters['password'] = password; - } - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public logoutUser ( ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/logout'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public getUserByName (username: string ) : Promise<{ response: http.ClientResponse; body: User; }> { - var path = this.url + this.basePath + '/user/{username}'; - - - path = path.replace('{' + 'username' + '}', String(username)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public updateUser (username: string, body: User ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/{username}'; - - - path = path.replace('{' + 'username' + '}', String(username)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling updateUser'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'PUT', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public deleteUser (username: string ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/{username}'; - - - path = path.replace('{' + 'username' + '}', String(username)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'DELETE', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - -} diff --git a/samples/client/petstore/typescript-node/client.ts b/samples/client/petstore/typescript-node/client.ts new file mode 100644 index 00000000000..111c76f03c7 --- /dev/null +++ b/samples/client/petstore/typescript-node/client.ts @@ -0,0 +1,51 @@ +import api = require('./api'); +import fs = require('fs'); + +var petApi = new api.PetApi('http://petstore.swagger.io'); +petApi.apiKey = 'special-key'; + +var pet = new api.Pet(); +pet.name = 'TypeScriptDoggie'; + +var petId: any; + +var exitCode = 0; + +// Test various API calls to the petstore +petApi.addPet(pet) +.then((res) => { + var newPet = (res.response).body; + petId = (res.response).body.id; + console.log(`Created pet with ID ${petId}`); + newPet.status = api.Pet.StatusEnum.available; + return petApi.updatePet(newPet); +}) +.then((res) => { + console.log('Updated pet using POST body'); + return petApi.updatePetWithForm(petId, undefined, "pending"); +}) +.then((res) => { + console.log('Updated pet using POST form'); + return petApi.uploadFile(petId, undefined, fs.createReadStream('sample.png')); +}) +.then((res) => { + console.log('Uploaded image'); + return petApi.getPetById(petId); +}) +.then((res) => { + console.log('Got pet by ID: ' + JSON.stringify(res.body)); + if (res.body.status != api.Pet.StatusEnum.pending) { + throw new Error("Unexpected pet status"); + } +}) +.catch((err:any) => { + console.error(err); + exitCode = 1; +}) +.finally(() => { + return petApi.deletePet(petId); +}) +.then((res) => { + console.log('Deleted pet'); + process.exit(exitCode); +}); diff --git a/samples/client/petstore/typescript-node/model/Category.ts b/samples/client/petstore/typescript-node/model/Category.ts deleted file mode 100644 index fc4b2874e93..00000000000 --- a/samples/client/petstore/typescript-node/model/Category.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class Category { - - id: number; - - name: string; -} - diff --git a/samples/client/petstore/typescript-node/model/Order.ts b/samples/client/petstore/typescript-node/model/Order.ts deleted file mode 100644 index b46ad4570a0..00000000000 --- a/samples/client/petstore/typescript-node/model/Order.ts +++ /dev/null @@ -1,26 +0,0 @@ -export class Order { - - id: number; - - petId: number; - - quantity: number; - - shipDate: DateTime; - - /** - * Order Status - */ - status: Order.StatusEnum; - - complete: boolean; -} - -export module Order { - - export enum StatusEnum { - placed = 'placed', - approved = 'approved', - delivered = 'delivered', - } -} diff --git a/samples/client/petstore/typescript-node/model/Pet.ts b/samples/client/petstore/typescript-node/model/Pet.ts deleted file mode 100644 index 4a3faa129ed..00000000000 --- a/samples/client/petstore/typescript-node/model/Pet.ts +++ /dev/null @@ -1,26 +0,0 @@ -export class Pet { - - id: number; - - category: Category; - - name: string; - - photoUrls: Array; - - tags: Array; - - /** - * pet status in the store - */ - status: Pet.StatusEnum; -} - -export module Pet { - - export enum StatusEnum { - available = 'available', - pending = 'pending', - sold = 'sold', - } -} diff --git a/samples/client/petstore/typescript-node/model/Tag.ts b/samples/client/petstore/typescript-node/model/Tag.ts deleted file mode 100644 index 6ae0d4ef576..00000000000 --- a/samples/client/petstore/typescript-node/model/Tag.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class Tag { - - id: number; - - name: string; -} - diff --git a/samples/client/petstore/typescript-node/model/User.ts b/samples/client/petstore/typescript-node/model/User.ts deleted file mode 100644 index fee31563d13..00000000000 --- a/samples/client/petstore/typescript-node/model/User.ts +++ /dev/null @@ -1,22 +0,0 @@ -export class User { - - id: number; - - username: string; - - firstName: string; - - lastName: string; - - email: string; - - password: string; - - phone: string; - - /** - * User Status - */ - userStatus: number; -} - diff --git a/samples/client/petstore/typescript-node/package.json b/samples/client/petstore/typescript-node/package.json new file mode 100644 index 00000000000..ee598dcc6c2 --- /dev/null +++ b/samples/client/petstore/typescript-node/package.json @@ -0,0 +1,21 @@ +{ + "name": "petstore-typescript-node-sample", + "version": "1.0.0", + "description": "Sample of generated TypeScript petstore client", + "main": "api.js", + "scripts": { + "postinstall": "tsd reinstall --overwrite", + "test": "tsc && node client.js", + "clean": "rm -Rf node_modules/ typings/ *.js" + }, + "author": "Mads M. Tandrup", + "license": "Apache 2.0", + "dependencies": { + "bluebird": "^2.9.34", + "request": "^2.60.0" + }, + "devDependencies": { + "tsd": "^0.6.3", + "typescript": "^1.5.3" + } +} diff --git a/samples/client/petstore/typescript-node/sample.png b/samples/client/petstore/typescript-node/sample.png new file mode 100644 index 00000000000..c5916f28970 Binary files /dev/null and b/samples/client/petstore/typescript-node/sample.png differ diff --git a/samples/client/petstore/typescript-node/tsconfig.json b/samples/client/petstore/typescript-node/tsconfig.json new file mode 100644 index 00000000000..572228f6356 --- /dev/null +++ b/samples/client/petstore/typescript-node/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noImplicitAny": true, + "target": "ES5" + }, + "files": [ + "api.ts", + "client.ts", + "typings/tsd.d.ts" + ] +} diff --git a/samples/client/petstore/typescript-node/tsd.json b/samples/client/petstore/typescript-node/tsd.json new file mode 100644 index 00000000000..89e4861f949 --- /dev/null +++ b/samples/client/petstore/typescript-node/tsd.json @@ -0,0 +1,21 @@ +{ + "version": "v4", + "repo": "borisyankov/DefinitelyTyped", + "ref": "master", + "path": "typings", + "bundle": "typings/tsd.d.ts", + "installed": { + "bluebird/bluebird.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "request/request.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "form-data/form-data.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "node/node.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + } + } +}