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/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/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/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index b795f8e38e2..4f30cc01ccb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -30,6 +30,23 @@ public class CodegenOperation { public List> examples; public ExternalDocs externalDocs; + private boolean nonempty(List params) + { + return params != null && params.size() > 0; + } + public boolean getHasBodyParam() { + return nonempty(bodyParams); + } + public boolean getHasQueryParams() { + return nonempty(bodyParams); + } + public boolean getHasHeaderParams() { + return nonempty(bodyParams); + } + public boolean getHasPathParams() { + return nonempty(bodyParams); + } + // legacy support public String nickname; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index 7872da2c707..2f186816d1e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -34,4 +34,108 @@ public class CodegenProperty { public boolean isEnum; public List _enum; public Map allowableValues; + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final CodegenProperty other = (CodegenProperty) obj; + if ((this.baseName == null) ? (other.baseName != null) : !this.baseName.equals(other.baseName)) { + return false; + } + if ((this.complexType == null) ? (other.complexType != null) : !this.complexType.equals(other.complexType)) { + return false; + } + if ((this.getter == null) ? (other.getter != null) : !this.getter.equals(other.getter)) { + return false; + } + if ((this.setter == null) ? (other.setter != null) : !this.setter.equals(other.setter)) { + return false; + } + if ((this.description == null) ? (other.description != null) : !this.description.equals(other.description)) { + return false; + } + if ((this.datatype == null) ? (other.datatype != null) : !this.datatype.equals(other.datatype)) { + return false; + } + if ((this.datatypeWithEnum == null) ? (other.datatypeWithEnum != null) : !this.datatypeWithEnum.equals(other.datatypeWithEnum)) { + return false; + } + if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { + return false; + } + if ((this.min == null) ? (other.min != null) : !this.min.equals(other.min)) { + return false; + } + if ((this.max == null) ? (other.max != null) : !this.max.equals(other.max)) { + return false; + } + if ((this.defaultValue == null) ? (other.defaultValue != null) : !this.defaultValue.equals(other.defaultValue)) { + return false; + } + if ((this.baseType == null) ? (other.baseType != null) : !this.baseType.equals(other.baseType)) { + return false; + } + if ((this.containerType == null) ? (other.containerType != null) : !this.containerType.equals(other.containerType)) { + return false; + } + if (this.maxLength != other.maxLength && (this.maxLength == null || !this.maxLength.equals(other.maxLength))) { + return false; + } + if (this.minLength != other.minLength && (this.minLength == null || !this.minLength.equals(other.minLength))) { + return false; + } + if ((this.pattern == null) ? (other.pattern != null) : !this.pattern.equals(other.pattern)) { + return false; + } + if ((this.example == null) ? (other.example != null) : !this.example.equals(other.example)) { + return false; + } + if ((this.jsonSchema == null) ? (other.jsonSchema != null) : !this.jsonSchema.equals(other.jsonSchema)) { + return false; + } + if (this.minimum != other.minimum && (this.minimum == null || !this.minimum.equals(other.minimum))) { + return false; + } + if (this.maximum != other.maximum && (this.maximum == null || !this.maximum.equals(other.maximum))) { + return false; + } + if (this.exclusiveMinimum != other.exclusiveMinimum && (this.exclusiveMinimum == null || !this.exclusiveMinimum.equals(other.exclusiveMinimum))) { + return false; + } + if (this.exclusiveMaximum != other.exclusiveMaximum && (this.exclusiveMaximum == null || !this.exclusiveMaximum.equals(other.exclusiveMaximum))) { + return false; + } + if (this.required != other.required && (this.required == null || !this.required.equals(other.required))) { + return false; + } + if (this.secondaryParam != other.secondaryParam && (this.secondaryParam == null || !this.secondaryParam.equals(other.secondaryParam))) { + return false; + } + if (this.isPrimitiveType != other.isPrimitiveType && (this.isPrimitiveType == null || !this.isPrimitiveType.equals(other.isPrimitiveType))) { + return false; + } + if (this.isContainer != other.isContainer && (this.isContainer == null || !this.isContainer.equals(other.isContainer))) { + return false; + } + if (this.isNotContainer != other.isNotContainer && (this.isNotContainer == null || !this.isNotContainer.equals(other.isNotContainer))) { + return false; + } + if (this.isEnum != other.isEnum) { + return false; + } + if (this._enum != other._enum && (this._enum == null || !this._enum.equals(other._enum))) { + return false; + } + if (this.allowableValues != other.allowableValues && (this.allowableValues == null || !this.allowableValues.equals(other.allowableValues))) { + return false; + } + return true; + } + + } 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 4b878c40e6c..212358b9627 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; @@ -538,7 +539,7 @@ public class DefaultCodegen { final String parentRef = toModelName(parent.getSimpleRef()); m.parent = parentRef; addImport(m, parentRef); - if (allDefinitions != null) { + if (!supportsInheritance && allDefinitions != null) { final Model parentModel = allDefinitions.get(parentRef); if (parentModel instanceof ModelImpl) { final ModelImpl _parent = (ModelImpl) parentModel; @@ -635,7 +636,9 @@ public class DefaultCodegen { if (np.getMaximum() != null) { allowableValues.put("max", np.getMaximum()); } - property.allowableValues = allowableValues; + if(allowableValues.size() > 0) { + property.allowableValues = allowableValues; + } } if (p instanceof StringProperty) { 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 0cdfa30dc33..220571e4f9b 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 @@ -13,9 +13,11 @@ 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 org.joda.time.DateTime; import java.io.File; import java.io.FileInputStream; @@ -62,6 +64,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { List files = new ArrayList(); try { config.processOpts(); + + config.additionalProperties().put("generatedDate", DateTime.now().toString()); + config.additionalProperties().put("generatorClass", config.getClass().toString()); + if (swagger.getInfo() != null) { Info info = swagger.getInfo(); if (info.getTitle() != null) { @@ -111,10 +117,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(); @@ -125,7 +129,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { Map definitions = swagger.getDefinitions(); if (definitions != null) { List sortedModelKeys = sortModelsByInheritance(definitions); - + for (String name : sortedModelKeys) { Model model = definitions.get(name); Map modelMap = new HashMap(); @@ -333,7 +337,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.put(flagFieldName, true); } } - + private List sortModelsByInheritance(final Map definitions) { List sortedModelKeys = new ArrayList(definitions.keySet()); Comparator cmp = new Comparator() { @@ -341,10 +345,10 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { 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) { @@ -353,30 +357,30 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { 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; } @@ -385,12 +389,12 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { 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; } @@ -403,14 +407,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()); @@ -445,7 +470,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } authMethods.put(securityName, oauth2Operation); } else { - authMethods.put(securityName, securityDefinition); + authMethods.put(securityName, securityDefinition); } } } @@ -456,6 +481,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(" "); 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 index 883ad66ff7f..38c0c5307ba 100644 --- 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 @@ -14,6 +14,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp public AbstractTypeScriptClientCodegen() { super(); + supportsInheritance = true; reservedWords = new HashSet(Arrays.asList("abstract", "continue", "for", "new", "switch", "assert", "default", "if", "package", "synchronized", "do", "goto", "private", 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 f272343a795..be8d68507b5 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 @@ -1,17 +1,30 @@ package io.swagger.codegen.languages; +import com.google.common.base.Strings; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; +import io.swagger.models.ComposedModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.RefModel; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; import java.io.File; +import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import org.apache.commons.lang.StringUtils; @@ -21,7 +34,9 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String artifactId = "swagger-java-client"; protected String artifactVersion = "1.0.0"; protected String sourceFolder = "src/main/java"; - + protected String localVariablePrefix = ""; + protected Boolean serializableModel = false; + public JavaClientCodegen() { super(); outputFolder = "generated-code/java"; @@ -61,6 +76,8 @@ 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")); + cliOptions.add(new CliOption("serializableModel", "boolean - toggle \"implements Serializable\" for generated models")); } public CodegenType getTag() { @@ -78,7 +95,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public void processOpts() { super.processOpts(); - + if (additionalProperties.containsKey("invokerPackage")) { this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); } else { @@ -111,6 +128,19 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { this.setSourceFolder((String) additionalProperties.get("sourceFolder")); } + + if (additionalProperties.containsKey("localVariablePrefix")) { + this.setLocalVariablePrefix((String) additionalProperties.get("localVariablePrefix")); + } + + if (additionalProperties.containsKey("serializableModel")) { + this.setSerializableModel(Boolean.valueOf((String)additionalProperties.get("serializableModel"))); + } else { + additionalProperties.put("serializableModel", serializableModel); + } + + this.sanitizeConfig(); + 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")); @@ -127,7 +157,26 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); } - + private void sanitizeConfig() { + // Sanitize any config options here. We also have to update the additionalProperties because + // the whole additionalProperties object is injected into the main object passed to the mustache layer + + this.setApiPackage(sanitizePackageName(apiPackage)); + if (additionalProperties.containsKey("apiPackage")) { + this.additionalProperties.put("apiPackage", apiPackage); + } + + this.setModelPackage(sanitizePackageName(modelPackage)); + if (additionalProperties.containsKey("modelPackage")) { + this.additionalProperties.put("modelPackage", modelPackage); + } + + this.setInvokerPackage(sanitizePackageName(invokerPackage)); + if (additionalProperties.containsKey("invokerPackage")) { + this.additionalProperties.put("invokerPackage", invokerPackage); + } + } + @Override public String escapeReservedWord(String name) { return "_" + name; @@ -249,6 +298,57 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return camelize(operationId, true); } + @Override + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); + + if (allDefinitions != null && codegenModel != null && codegenModel.parent != null && codegenModel.hasEnums) { + final Model parentModel = allDefinitions.get(toModelName(codegenModel.parent)); + final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); + codegenModel = this.reconcileInlineEnums(codegenModel, parentCodegenModel); + } + + return codegenModel; + } + + private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + // This generator uses inline classes to define enums, which breaks when + // dealing with models that have subTypes. To clean this up, we will analyze + // the parent and child models, look for enums that match, and remove + // them from the child models and leave them in the parent. + // Because the child models extend the parents, the enums will be available via the parent. + + // Only bother with reconciliation if the parent model has enums. + if (parentCodegenModel.hasEnums) { + + // Get the properties for the parent and child models + final List parentModelCodegenProperties = parentCodegenModel.vars; + List codegenProperties = codegenModel.vars; + + // Iterate over all of the parent model properties + for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) { + // Look for enums + if (parentModelCodegenPropery.isEnum) { + // Now that we have found an enum in the parent class, + // and search the child class for the same enum. + Iterator iterator = codegenProperties.iterator(); + while (iterator.hasNext()) { + CodegenProperty codegenProperty = iterator.next(); + if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) { + // We found an enum in the child class that is + // a duplicate of the one in the parent, so remove it. + iterator.remove(); + } + } + } + } + + codegenModel.vars = codegenProperties; + } + + return codegenModel; + } + public void setInvokerPackage(String invokerPackage) { this.invokerPackage = invokerPackage; } @@ -268,4 +368,26 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { public void setSourceFolder(String sourceFolder) { this.sourceFolder = sourceFolder; } + + public void setLocalVariablePrefix(String localVariablePrefix) { + this.localVariablePrefix = localVariablePrefix; + } + + public Boolean getSerializableModel() { + return serializableModel; + } + + public void setSerializableModel(Boolean serializableModel) { + this.serializableModel = serializableModel; + } + + private String sanitizePackageName(String packageName) { + packageName = packageName.trim(); + packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_"); + if(Strings.isNullOrEmpty(packageName)) { + return "invalidPackageName"; + } + return packageName; + } + } 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 01a61b4e935..6d83ff56a3c 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 @@ -94,21 +94,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 887422cd490..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 @@ -215,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(); 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 80f83bc2d10..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 @@ -159,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 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 1b40cc0a30e..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 @@ -79,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() { @@ -284,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/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index e0e1bdc07f8..61dc431b8a7 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 @@ -119,7 +119,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String escapeReservedWord(String name) { - return name + "_"; + return "_" + name; } @Override @@ -179,14 +179,14 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig // petId => pet_id name = underscore(dropDots(name)); + // remove leading underscore + name = name.replaceAll("^_*", ""); + // for reserved word or word starting with number, append _ if (reservedWords.contains(name) || name.matches("^\\d.*")) { name = escapeReservedWord(name); } - // remove leading underscore - name = name.replaceAll("^_*", ""); - return 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/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/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index fb4351d444d..6930b548d42 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -40,6 +40,7 @@ import {{invokerPackage}}.auth.HttpBasicAuth; import {{invokerPackage}}.auth.ApiKeyAuth; import {{invokerPackage}}.auth.OAuth; +{{>generatedAnnotation}} public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); @@ -356,7 +357,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/Configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache index e936b423a91..4629c4e17be 100644 --- a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache @@ -1,5 +1,6 @@ package {{invokerPackage}}; +{{>generatedAnnotation}} public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache index 29d5f55ecee..4866f8c0fce 100644 --- a/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache @@ -7,6 +7,7 @@ import com.fasterxml.jackson.core.JsonGenerator.Feature; import com.fasterxml.jackson.datatype.joda.*; +{{>generatedAnnotation}} public class JsonUtil { public static ObjectMapper mapper; diff --git a/modules/swagger-codegen/src/main/resources/Java/Pair.mustache b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache index 9805c74903b..e2a47317afe 100644 --- a/modules/swagger-codegen/src/main/resources/Java/Pair.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache @@ -1,5 +1,6 @@ package {{invokerPackage}}; +{{>generatedAnnotation}} public class Pair { private String name = ""; private String value = ""; diff --git a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache index 035d6739dce..073966b0c21 100644 --- a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache @@ -1,5 +1,6 @@ package {{invokerPackage}}; +{{>generatedAnnotation}} public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 39b71dbff9a..f8464e79fd2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -21,24 +21,25 @@ import java.io.File; import java.util.Map; import java.util.HashMap; +{{>generatedAnnotation}} {{#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 +50,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 +59,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/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache index 9afe96c6ffb..bb3b53b0aeb 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache @@ -3,6 +3,7 @@ package {{invokerPackage}}; import java.util.Map; import java.util.List; +{{>generatedAnnotation}} public class ApiException extends Exception { private int code = 0; private String message = null; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache index a1824b551ca..04be4812292 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -5,6 +5,7 @@ import {{invokerPackage}}.Pair; import java.util.Map; import java.util.List; +{{>generatedAnnotation}} public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache index 265c74cb76f..037ef58ab90 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache @@ -5,6 +5,7 @@ import {{invokerPackage}}.Pair; import java.util.Map; import java.util.List; +{{>generatedAnnotation}} public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache index 032ea57d4e8..63813e2504e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache @@ -8,6 +8,7 @@ import java.util.List; import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; +{{>generatedAnnotation}} public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache index 66cf2ac8f0f..a1f1b6a827c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache @@ -5,6 +5,7 @@ import {{invokerPackage}}.Pair; import java.util.Map; import java.util.List; +{{>generatedAnnotation}} public class OAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { diff --git a/modules/swagger-codegen/src/main/resources/Java/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/Java/generatedAnnotation.mustache new file mode 100644 index 00000000000..49110fc1ad9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index 0e12f514c48..bc23f0187d5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -3,6 +3,9 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} +{{#serializableModel}} +import java.io.Serializable;{{/serializableModel}} + import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; {{#models}} @@ -12,7 +15,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; * {{description}} **/{{/description}} @ApiModel(description = "{{{description}}}") -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { +{{>generatedAnnotation}} +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { {{#vars}}{{#isEnum}} public enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache index 5f5b5b1df9a..829a9daeabc 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/api.mustache @@ -13,6 +13,7 @@ import {{modelPackage}}.*; {{#imports}}import {{import}}; {{/imports}} +{{>generatedAnnotation}} {{#operations}} public class {{classname}} { diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/generatedAnnotation.mustache new file mode 100644 index 00000000000..49110fc1ad9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache index 300d5e61dd9..db2480a8540 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache @@ -12,6 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * {{description}} **/{{/description}} @ApiModel(description = "{{{description}}}") +{{>generatedAnnotation}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}{{#isEnum}} public enum {{datatypeWithEnum}} { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache index ffab3b1088e..11b4036b832 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache @@ -1,5 +1,6 @@ package {{apiPackage}}; +{{>generatedAnnotation}} public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache index 68675432c64..5db3301b3d9 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache @@ -5,6 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; +{{>generatedAnnotation}} public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache index 94711b26efb..2b9a2b1f8c5 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache @@ -3,6 +3,7 @@ package {{apiPackage}}; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement +{{>generatedAnnotation}} public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache index 8ab2c99e4f8..1bd5e207d7b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache @@ -1,5 +1,6 @@ package {{apiPackage}}; +{{>generatedAnnotation}} public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index 3216b60d516..9e1f808806e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -26,6 +26,7 @@ import javax.ws.rs.*; {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} @io.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API") +{{>generatedAnnotation}} {{#operations}} public class {{classname}} { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache index 43e7cd8685c..a731da6c11c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache @@ -18,6 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; +{{>generatedAnnotation}} {{#operations}} public abstract class {{classname}}Service { {{#operation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache index a434311d285..1bb63bc0775 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache @@ -3,6 +3,7 @@ package {{package}}.factories; import {{package}}.{{classname}}Service; import {{package}}.impl.{{classname}}ServiceImpl; +{{>generatedAnnotation}} public class {{classname}}ServiceFactory { private final static {{classname}}Service service = new {{classname}}ServiceImpl(); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache index d49fa4952a2..0acd755745e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache @@ -18,6 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; +{{>generatedAnnotation}} {{#operations}} public class {{classname}}ServiceImpl extends {{classname}}Service { {{#operation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/generatedAnnotation.mustache new file mode 100644 index 00000000000..49110fc1ad9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache index 300d5e61dd9..db2480a8540 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -12,6 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * {{description}} **/{{/description}} @ApiModel(description = "{{{description}}}") +{{>generatedAnnotation}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}{{#isEnum}} public enum {{datatypeWithEnum}} { diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache index d6a24b69311..e6e8d6fc04c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache @@ -30,6 +30,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/{{baseName}}", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/{{baseName}}", description = "the {{baseName}} API") +{{>generatedAnnotation}} {{#operations}} public class {{classname}} { {{#operation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache index ffab3b1088e..11b4036b832 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiException.mustache @@ -1,5 +1,6 @@ package {{apiPackage}}; +{{>generatedAnnotation}} public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache index 68675432c64..5db3301b3d9 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiOriginFilter.mustache @@ -5,6 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; +{{>generatedAnnotation}} public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache index 94711b26efb..2b9a2b1f8c5 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/apiResponseMessage.mustache @@ -3,6 +3,7 @@ package {{apiPackage}}; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement +{{>generatedAnnotation}} public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/generatedAnnotation.mustache new file mode 100644 index 00000000000..49110fc1ad9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/generatedAnnotation.mustache @@ -0,0 +1 @@ +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache index 300d5e61dd9..db2480a8540 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache @@ -12,6 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * {{description}} **/{{/description}} @ApiModel(description = "{{{description}}}") +{{>generatedAnnotation}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}}{{#isEnum}} public enum {{datatypeWithEnum}} { diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache index 8ab2c99e4f8..1bd5e207d7b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/notFoundException.mustache @@ -1,5 +1,6 @@ package {{apiPackage}}; +{{>generatedAnnotation}} public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache index b33ee7fc994..4a6e6879df3 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerConfig.mustache @@ -18,6 +18,7 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 //Loads the spring beans required by the framework @PropertySource("classpath:swagger.properties") @Import(SwaggerUiConfiguration.class) +{{>generatedAnnotation}} public class SwaggerConfig { @Bean ApiInfo apiInfo() { diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache index 652dc310358..0b515fe2cc8 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/swaggerUiConfiguration.mustache @@ -8,6 +8,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableWebMvc +{{>generatedAnnotation}} public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache index 6910ad11b76..426f831582e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webApplication.mustache @@ -2,6 +2,7 @@ package {{configPackage}}; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; +{{>generatedAnnotation}} public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { @Override diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache index 03904e51e79..d60c126316e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/webMvcConfiguration.mustache @@ -3,6 +3,7 @@ package {{configPackage}}; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; +{{>generatedAnnotation}} public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 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 2e514436747..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,6 +1,7 @@ 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 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 50ac120c4ea..c93537a740d 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -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/Newtonsoft.Json.dll b/modules/swagger-codegen/src/main/resources/csharp/Newtonsoft.Json.dll new file mode 100644 index 00000000000..ae725c4b598 Binary files /dev/null and b/modules/swagger-codegen/src/main/resources/csharp/Newtonsoft.Json.dll differ diff --git a/modules/swagger-codegen/src/main/resources/csharp/RestSharp.dll b/modules/swagger-codegen/src/main/resources/csharp/RestSharp.dll new file mode 100644 index 00000000000..a7331ed6e23 Binary files /dev/null and b/modules/swagger-codegen/src/main/resources/csharp/RestSharp.dll differ 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/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index ce881084bc2..584db3b7a85 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -1,52 +1,158 @@ - + + + - - API Reference + {{{appName}}} + +

{{{appName}}}

-
{{{appDescription}}} for {{partner}}
+
{{{appDescription}}}
{{#infoUrl}}
More information: {{{infoUrl}}}
{{/infoUrl}} {{#infoEmail}}
Contact Info: {{{infoEmail}}}
{{/infoEmail}} {{#version}}
Version: {{{version}}}
{{/version}}
{{{licenseInfo}}}
{{{licenseUrl}}}

Access

-
Customize this message as you see fit!
-

Methods

+ {{access}} + +

Methods

+ [ Jump to Models ] + + {{! for the tables of content, I cheat and don't use CSS styles.... }} +

Table of Contents

+
{{access}}
+ {{#apiInfo}} +
    + {{#apis}} + {{#operations}} + {{#operation}} +
  1. {{httpMethod}} {{path}}
  2. + {{/operation}} + {{/operations}} + {{/apis}} +
+ {{/apiInfo}} + {{#apiInfo}} {{#apis}} - {{#operations}}{{#operation}} -
-
{{httpMethod}}: {{path}}
-
{{#tags}}{{this}}{{/tags}}
-
{{nickname}} {{summary}}
+ {{#operations}} + {{#operation}} +
+
+ Up +
{{httpMethod}} {{path}}
+
{{summary}} ({{nickname}})
+ {{! notes is operation.description. So why rename it and make it super confusing???? }}
{{notes}}
-

Parameters

+ {{#hasPathParams}} +

Path parameters

- {{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>headerParam}}{{>formParam}} - {{/allParams}} + {{#pathParams}}{{>pathParam}}{{/pathParams}}
+ {{/hasPathParams}} + + {{#hasConsumes}} +

Consumes

+ This API call consumes the following media types via the Content-Type request header: +
    + {{#consumes}} +
  • {{mediaType}}
  • + {{/consumes}} +
+ {{/hasConsumes}} + + {{#hasBodyParam}} +

Request body

+
+ {{#bodyParams}}{{>bodyParam}}{{/bodyParams}} +
+ {{/hasBodyParam}} + + {{#hasHeaderParam}} +

Request headers

+
+ {{#headerParam}}{{>headerParam}}{{/headerParam}} +
+ {{/hasHeaderParam}} + + {{#hasQueryParams}} +

Query parameters

+
+ {{#queryParams}}{{>queryParam}}{{/queryParams}} +
+ {{/hasQueryParams}} + + + + {{#hasExamples}} + {{#examples}} +

Example data

+
Content-Type: {{{contentType}}}
+
{{{example}}}
+ {{/examples}} + {{/hasExamples}} + + {{#hasProduces}} +

Produces

+ This API call produces the following media types according to the Accept request header; + the media type will be conveyed by the Content-Type response header. +
    + {{#produces}} +
  • {{mediaType}}
  • + {{/produces}} +
+ {{/hasProduces}} + +

Responses

+ {{#responses}} +

{{code}}

+ {{message}} {{#examples}}

Example data

Content-Type: {{{contentType}}}
{{example}}
{{/examples}} + {{/responses}}
-
- {{/operation}}{{/operations}} - {{/apis}}{{/apiInfo}} +
+ {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + + +

Models

+ [ Jump to Methods ] + +

Table of Contents

+
    + {{#models}} + {{#model}} +
  1. {{classname}}
  2. + {{/model}} + {{/models}} +
-

Models

{{#models}} {{#model}}
-

{{classname}}

+

{{classname}} Up

{{#vars}}
{{name}} {{#isNotRequired}}(optional){{/isNotRequired}}
{{datatype}} {{description}}
{{/vars}} @@ -54,8 +160,5 @@
{{/model}} {{/models}} - \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache index 14ab06a7f7e..d69f0e7b161 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache @@ -57,6 +57,10 @@ pre { margin-bottom: 2px; } +.http-method { + text-transform: uppercase; +} + pre.get { background-color: #0f6ab4; } @@ -96,6 +100,10 @@ code { background-color: #0f6ab4; } +.up { + float:right; +} + .parameter { width: 500px; } 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..b7643de6ddd 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,367 @@ 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 + pathParams: (NSDictionary *) pathParams + 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]; + } + + // sanitize parameters + pathParams = [self sanitizeForSerialization:pathParams]; + queryParams = [self sanitizeForSerialization:queryParams]; + headerParams = [self sanitizeForSerialization:headerParams]; + formParams = [self sanitizeForSerialization:formParams]; + body = [self sanitizeForSerialization:body]; + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + + NSMutableString *resourcePath = [NSMutableString stringWithString:path]; + [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] + withString:[SWGApiClient escape:obj]]; + }]; + + NSMutableURLRequest * request = nil; + + NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath 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]; + } + } + + // request cache + BOOL hasHeaderParams = false; + if(headerParams != nil && [headerParams count] > 0) { + hasHeaderParams = true; + } + if(offlineState) { + NSLog(@"%@ cache forced", resourcePath); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + NSLog(@"%@ cache enabled", resourcePath); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + NSLog(@"%@ cache disabled", resourcePath); + [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 +660,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 +681,49 @@ 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) { +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { return nil; } - - // remove "*" from class, if ends with "*" - if ([class hasSuffix:@"*"]) { - class = [class substringToIndex:[class length] - 1]; + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { + return object; } - - // pure object - if ([class isEqualToString:@"NSObject"]) { - return [[NSObject alloc] init]; + else if ([object isKindOfClass:[NSDate class]]) { + return [object ISO8601String]; } - - // 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]]; + else if ([object isKindOfClass:[NSArray class]]) { + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[object count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + if (obj) { + [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; } - ]; - - 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; + return sanitizedObjs; } - - // 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; + else if ([object isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[object count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + if (obj) { + [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; } - // 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); }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[SWGObject class]]) { + return [object toDictionary]; } else { - [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { - completionBlock([self deserialize:data class:responseType], error); - }]; + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; } - 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 a5871400352..eba62705879 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -15,6 +15,8 @@ {{#models}}{{#model}}#import "{{classname}}.h" {{/model}}{{/models}} +@class {{classPrefix}}Configuration; + /** * A key for `NSError` user info dictionaries. * @@ -29,22 +31,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; @property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, readonly) NSOperationQueue* queue; -/** - * Gets the Api Client instance from pool - * - * @param baseUrl The base url of api client. - * - * @return The {{classPrefix}}ApiClient instance. - */ -+({{classPrefix}}ApiClient *)sharedClientFromPool:(NSString *)baseUrl; - -/** - * Gets the operations queue - * - * @return The `shardQueue` static variable. - */ -+(NSOperationQueue*) sharedQueue; - /** * Clears Cache */ @@ -116,11 +102,9 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; /** - * Sets the client reachability strategy - * - * @param host The host of {{classPrefix}}ApiClient. + * Sets the api client reachability strategy */ -+(void) configureCacheReachibilityForHost:(NSString*)host; +- (void)configureCacheReachibility; /** * Detects Accept header from accepts NSArray @@ -184,6 +168,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * * @param path Request url. * @param method Request method. + * @param pathParams Request path parameters. * @param queryParams Request query parameters. * @param body Request body. * @param headerParams Request header parameters. @@ -196,6 +181,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ -(NSNumber*) requestWithCompletionBlock:(NSString*) path method:(NSString*) method + pathParams:(NSDictionary *) pathParams queryParams:(NSDictionary*) queryParams formParams:(NSDictionary *) formParams files:(NSDictionary *) files @@ -207,4 +193,11 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; responseType:(NSString *) responseType completionBlock:(void (^)(id, NSError *))completionBlock; +/** + * Sanitize object for request + * + * @param object The query/path/header/form/body param to be sanitized. + */ +- (id) sanitizeForSerialization:(id) object; + @end 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 75d73d6e414..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,7 +56,7 @@ NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - + return basicAuthCredentials; } @@ -81,7 +83,7 @@ if ([self.loggingFileHanlder isKindOfClass:[NSFileHandle class]]) { [self.loggingFileHanlder closeFile]; } - + _loggingFile = loggingFile; _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; if (_loggingFileHanlder == nil) { @@ -103,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 6b311e968b0..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,13 +1,26 @@ #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 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..534c887fe7b 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,17 @@ 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"]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } - {{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [{{classPrefix}}ApiClient escape:{{paramName}}]]; + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + {{#pathParams}}if ({{paramName}} != nil) { + pathParams[@"{{baseName}}"] = {{paramName}}; + } {{/pathParams}} NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -142,26 +135,12 @@ static NSString * basePath = @"{{basePath}}"; NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; {{#bodyParam}} bodyParam = {{paramName}}; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[({{classPrefix}}Object*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [({{classPrefix}}Object*)bodyParam toDictionary]; - } {{/bodyParam}}{{^bodyParam}} {{#formParams}} {{#notFile}} - formParams[@"{{paramName}}"] = {{paramName}}; + if ({{paramName}}) { + formParams[@"{{baseName}}"] = {{paramName}}; + } {{/notFile}}{{#isFile}} files[@"{{paramName}}"] = {{paramName}}; {{/isFile}} @@ -175,8 +154,9 @@ static NSString * basePath = @"{{basePath}}"; } {{/requiredParams}} {{/requiredParamCount}} - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"{{httpMethod}}" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files 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 6b85f753e45..d9f691f7227 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -20,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/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 1d63440b66f..2de1d556acb 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -191,7 +191,7 @@ class ObjectSerializer $values[] = $this->deserialize($value, $subClass); } $deserialized = $values; - } elseif ($class === 'DateTime') { + } elseif ($class === '\DateTime') { $deserialized = new \DateTime($data); } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { settype($data, $class); 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/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 9811288e929..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,10 +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 @@ -34,6 +31,10 @@ 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() 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 637bba9d765..02099f0ceb1 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 @@ -38,15 +48,27 @@ from .configuration import Configuration class ApiClient(object): """ - Generic API client for Swagger client library builds + 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 + 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. + + 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. """ def __init__(self, host=Configuration().host, header_name=None, header_value=None, cookie=None): + """ + Constructor of the class. + """ self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value @@ -57,10 +79,16 @@ class ApiClient(object): @property def user_agent(self): + """ + Gets user agent. + """ return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): + """ + Sets user agent. + """ self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): @@ -129,11 +157,12 @@ class ApiClient(object): def to_path_value(self, obj): """ - Convert a string or object to a path-friendly value + Takes value and turn it into a string suitable for inclusion in + the path, by url-encoding. - :param obj: object or string value + :param obj: object or string value. - :return string: quoted value + :return string: quoted value. """ if type(obj) == list: return ','.join(obj) @@ -142,7 +171,7 @@ class ApiClient(object): def sanitize_for_serialization(self, obj): """ - Sanitize an object for Request. + Builds a JSON POST object. If obj is None, return None. If obj is str, int, float, bool, return directly. @@ -151,6 +180,9 @@ class ApiClient(object): 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 obj: The data to serialize. + :return: The serialized form of data. """ if isinstance(obj, type(None)): return None @@ -170,24 +202,22 @@ class ApiClient(object): # 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} + obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in iteritems(obj.swagger_types) + if getattr(obj, attr) is not None} return {key: self.sanitize_for_serialization(val) for key, val in iteritems(obj_dict)} def deserialize(self, response, response_type): """ - Derialize response into an object. + Deserializes response into an object. - :param response: RESTResponse object to be deserialized + :param response: RESTResponse object to be deserialized. :param response_type: class literal for - deserialzied object, or string of class name + deserialzied object, or string of class name. - :return: deserialized object + :return: deserialized object. """ # handle file downloading # save response body into a tmp file and return the instance @@ -204,21 +234,23 @@ class ApiClient(object): def __deserialize(self, data, klass): """ - :param data: dict, list or str - :param klass: class literal, or string of class name + Deserializes dict, list, str into an object. - :return: object + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. """ if data is None: return None if type(klass) == str: - if 'list[' in klass: + 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 'dict(' in klass: + 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)} @@ -248,8 +280,7 @@ class ApiClient(object): body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None): """ - Perform http request and return deserialized data - + Makes the HTTP request and return the deserialized data. :param resource_path: Path to method endpoint. :param method: Method to call. @@ -293,7 +324,7 @@ class ApiClient(object): def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): """ - Perform http request using RESTClient. + Makes the HTTP request using RESTClient. """ if method == "GET": return RESTClient.GET(url, @@ -305,16 +336,19 @@ class ApiClient(object): headers=headers) elif method == "POST": return RESTClient.POST(url, + query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "PUT": return RESTClient.PUT(url, + query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "PATCH": return RESTClient.PATCH(url, + query_params=query_params, headers=headers, post_params=post_params, body=body) @@ -329,6 +363,13 @@ class ApiClient(object): ) 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: @@ -350,7 +391,10 @@ class ApiClient(object): def select_header_accept(self, accepts): """ - Return `Accept` based on an array of accepts provided + Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). """ if not accepts: return @@ -364,7 +408,10 @@ class ApiClient(object): def select_header_content_type(self, content_types): """ - Return `Content-Type` baseed on an array of content_types provided + 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' @@ -378,7 +425,11 @@ class ApiClient(object): def update_params_for_auth(self, headers, querys, auth_settings): """ - Update header and query params based on authentication setting + 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() @@ -399,12 +450,12 @@ class ApiClient(object): def __deserialize_file(self, response): """ - Save response body into a file in (the defined) temporary folder, + 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 + :param response: RESTResponse. + :return: file path. """ config = Configuration() @@ -426,12 +477,12 @@ class ApiClient(object): def __deserialize_primitive(self, data, klass): """ - Deserialize string to primitive type + Deserializes string to primitive type. - :param data: str - :param klass: class literal + :param data: str. + :param klass: class literal. - :return: int, float, str, bool + :return: int, float, str, bool. """ try: value = klass(data) @@ -443,16 +494,18 @@ class ApiClient(object): def __deserialize_object(self): """ - Deserialize empty object + Deserializes empty object. + + :return: object. """ return object() def __deserialize_date(self, string): """ - Deserialize string to date + Deserializes string to date. - :param string: str - :return: date + :param string: str. + :return: date. """ try: from dateutil.parser import parse @@ -468,12 +521,12 @@ class ApiClient(object): def __deserialize_datatime(self, string): """ - Deserialize string to datetime. + Deserializes string to datetime. The string should be in iso8601 datetime format. - :param string: str - :return: datetime + :param string: str. + :return: datetime. """ try: from dateutil.parser import parse @@ -489,10 +542,11 @@ class ApiClient(object): def __deserialize_model(self, data, klass): """ - Deserialize list or dict to model + Deserializes list or dict to model. - :param data: dict, list - :param klass: class literal + :param data: dict, list. + :param klass: class literal. + :return: model object. """ instance = klass() diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index bf26ab362b1..d6d94ff5a50 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -1,7 +1,31 @@ +# 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: + # for python3 + import http.client as httplib + import sys import logging @@ -18,26 +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 + # 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() @@ -82,20 +125,33 @@ 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 """ + """ + Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ return { {{#authMethods}} {{#isApiKey}} @@ -120,6 +176,11 @@ class Configuration(object): } 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"\ diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 7314e9ee9cd..4a93aeaf29d 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,6 +15,7 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ + {{#models}} {{#model}} from pprint import pformat @@ -47,16 +47,30 @@ class {{classname}}(object): } {{#vars}} - self._{{name}} = None{{#description}} # {{description}}{{/description}} + 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( @@ -72,18 +86,17 @@ class {{classname}}(object): """ 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( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index fab813a4cc9..f9f85f294dc 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 """ @@ -162,21 +176,24 @@ class RESTClientObject(object): headers=headers, query_params=query_params) - def POST(self, url, headers=None, post_params=None, body=None): + def POST(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("POST", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) - def PUT(self, url, headers=None, post_params=None, body=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("PUT", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) - def PATCH(self, url, headers=None, post_params=None, body=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("PATCH", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) @@ -202,10 +219,10 @@ 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 diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index 9c19e413e9c..a939ce01958 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -1,4 +1,5 @@ -# -*- coding: utf-8 -*- +# coding: utf-8 + import sys from setuptools import setup, find_packages @@ -34,11 +35,3 @@ setup( ) {{/hasMore}}{{/apis}}{{/apiInfo}} - - - - - - - - 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/test/scala/Java/JavaModelEnumTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala index e5191e1ae23..30a70ca6dfb 100644 --- a/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala +++ b/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala @@ -31,4 +31,55 @@ class JavaModelEnumTest extends FlatSpec with Matchers { enumVar.baseType should be("String") enumVar.isEnum should equal(true) } + + it should "not override identical parent enums" in { + + val identicalEnumProperty = new StringProperty() + identicalEnumProperty.setEnum(List("VALUE1", "VALUE2", "VALUE3").asJava) + + val subEnumProperty = new StringProperty() + subEnumProperty.setEnum(List("SUB1", "SUB2", "SUB3").asJava) + + // Add one enum ptoperty to the parent + val parentProperties = new java.util.HashMap[String, Property]() + parentProperties.put("sharedThing", identicalEnumProperty) + + // Add TWO enums to the subType model; one of which is identical to the one in parent class + val subProperties = new java.util.HashMap[String, Property]() + subProperties.put("sharedThing", identicalEnumProperty) + subProperties.put("unsharedThing", identicalEnumProperty) + + val parentModel = new ModelImpl(); + parentModel.setProperties(parentProperties); + parentModel.name("parentModel"); + + val subModel = new ModelImpl(); + subModel.setProperties(subProperties); + subModel.name("subModel"); + + val model = new ComposedModel() + .parent(new RefModel(parentModel.getName())) + .child(subModel) + .interfaces(new java.util.ArrayList[RefModel]()) + + val codegen = new JavaClientCodegen() + val allModels = new java.util.HashMap[String, Model]() + allModels.put(codegen.toModelName(parentModel.getName()), parentModel) + allModels.put(codegen.toModelName(subModel.getName()), subModel) + + val cm = codegen.fromModel("sample", model, allModels) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.parent should be("ParentModel") + cm.imports.asScala should be(Set("ParentModel")) + + // Assert that only the unshared/uninherited enum remains + cm.vars.size should be (1) + val enumVar = cm.vars.get(0) + enumVar.baseName should be("unsharedThing") + enumVar.datatype should be("String") + enumVar.datatypeWithEnum should be("UnsharedThingEnum") + enumVar.isEnum should equal(true) + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala index 81e252aa117..0043045a29d 100644 --- a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala @@ -2,6 +2,7 @@ package Java import io.swagger.codegen.languages.JavaClientCodegen import io.swagger.models._ +import io.swagger.models.parameters._ import io.swagger.models.properties._ import io.swagger.util.Json import org.junit.runner.RunWith @@ -382,7 +383,6 @@ class JavaModelTest2 extends FlatSpec with Matchers { cm.vars.size should be(1) val vars = cm.vars - Json.prettyPrint(vars.get(0)) vars.get(0).baseName should be("_") vars.get(0).getter should be("getU") vars.get(0).setter should be("setU") @@ -393,4 +393,17 @@ class JavaModelTest2 extends FlatSpec with Matchers { vars.get(0).hasMore should equal(null) vars.get(0).isNotContainer should equal(true) } + + it should "convert a parameter" in { + val parameter = new QueryParameter() + .property( + new IntegerProperty()) + .name("limit") + .required(true) + + val codegen = new JavaClientCodegen() + val cp = codegen.fromParameter(parameter, null) + + cp.allowableValues should be (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/pom.xml b/pom.xml index 7dc651146a3..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.9-SNAPSHOT + 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 index dea70c68364..5fe03fcb316 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md @@ -2,6 +2,9 @@ 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. -## Compilation dependencies +## 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/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 490e9e50cc1..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 @@ -235,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/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/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index ada8035e579..84f28faa8c6 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -19,6 +19,8 @@ #import "SWGOrder.h" +@class SWGConfiguration; + /** * A key for `NSError` user info dictionaries. * @@ -33,22 +35,6 @@ extern NSString *const SWGResponseObjectErrorKey; @property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, readonly) NSOperationQueue* queue; -/** - * Gets the Api Client instance from pool - * - * @param baseUrl The base url of api client. - * - * @return The SWGApiClient instance. - */ -+(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl; - -/** - * Gets the operations queue - * - * @return The `shardQueue` static variable. - */ -+(NSOperationQueue*) sharedQueue; - /** * Clears Cache */ @@ -120,11 +106,9 @@ extern NSString *const SWGResponseObjectErrorKey; +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; /** - * Sets the client reachability strategy - * - * @param host The host of SWGApiClient. + * Sets the api client reachability strategy */ -+(void) configureCacheReachibilityForHost:(NSString*)host; +- (void)configureCacheReachibility; /** * Detects Accept header from accepts NSArray @@ -188,6 +172,7 @@ extern NSString *const SWGResponseObjectErrorKey; * * @param path Request url. * @param method Request method. + * @param pathParams Request path parameters. * @param queryParams Request query parameters. * @param body Request body. * @param headerParams Request header parameters. @@ -200,6 +185,7 @@ extern NSString *const SWGResponseObjectErrorKey; */ -(NSNumber*) requestWithCompletionBlock:(NSString*) path method:(NSString*) method + pathParams:(NSDictionary *) pathParams queryParams:(NSDictionary*) queryParams formParams:(NSDictionary *) formParams files:(NSDictionary *) files @@ -211,4 +197,11 @@ extern NSString *const SWGResponseObjectErrorKey; responseType:(NSString *) responseType completionBlock:(void (^)(id, NSError *))completionBlock; +/** + * Sanitize object for request + * + * @param object The query/path/header/form/body param to be sanitized. + */ +- (id) sanitizeForSerialization:(id) object; + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index f51a012a811..906169f4d12 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,367 @@ 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 + pathParams: (NSDictionary *) pathParams + 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]; + } + + // sanitize parameters + pathParams = [self sanitizeForSerialization:pathParams]; + queryParams = [self sanitizeForSerialization:queryParams]; + headerParams = [self sanitizeForSerialization:headerParams]; + formParams = [self sanitizeForSerialization:formParams]; + body = [self sanitizeForSerialization:body]; + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + + NSMutableString *resourcePath = [NSMutableString stringWithString:path]; + [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] + withString:[SWGApiClient escape:obj]]; + }]; + + NSMutableURLRequest * request = nil; + + NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath 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]; + } + } + + // request cache + BOOL hasHeaderParams = false; + if(headerParams != nil && [headerParams count] > 0) { + hasHeaderParams = true; + } + if(offlineState) { + NSLog(@"%@ cache forced", resourcePath); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + NSLog(@"%@ cache enabled", resourcePath); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + NSLog(@"%@ cache disabled", resourcePath); + [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 +660,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 +681,49 @@ 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) { +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { return nil; } - - // remove "*" from class, if ends with "*" - if ([class hasSuffix:@"*"]) { - class = [class substringToIndex:[class length] - 1]; + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { + return object; } - - // pure object - if ([class isEqualToString:@"NSObject"]) { - return [[NSObject alloc] init]; + else if ([object isKindOfClass:[NSDate class]]) { + return [object ISO8601String]; } - - // 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]]; + else if ([object isKindOfClass:[NSArray class]]) { + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[object count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + if (obj) { + [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; } - ]; - - 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; + return sanitizedObjs; } - - // 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; + else if ([object isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[object count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + if (obj) { + [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; } - // 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); }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[SWGObject class]]) { + return [object toDictionary]; } else { - [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { - completionBlock([self deserialize:data class:responseType], error); - }]; + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; } - return requestId; } - + @end - - - - diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h index 0ccbe0cd8f6..99f97cdec1b 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h @@ -1,13 +1,26 @@ #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 diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m index 0e0e70e27ea..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,7 +56,7 @@ NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - + return basicAuthCredentials; } @@ -81,7 +83,7 @@ if ([self.loggingFileHanlder isKindOfClass:[NSFileHandle class]]) { [self.loggingFileHanlder closeFile]; } - + _loggingFile = loggingFile; _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; if (_loggingFileHanlder == nil) { @@ -103,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/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/SWGPet.h index d78baade81a..84f10969e5b 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.h @@ -7,8 +7,8 @@ * Do not edit the class manually. */ -#import "SWGTag.h" #import "SWGCategory.h" +#import "SWGTag.h" @protocol SWGPet @@ -23,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/SWGPetApi.h b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h index 929b16eab1f..f7e67d0aa1f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h @@ -18,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 @@ -59,7 +57,7 @@ /// /// /// @return NSArray* --(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status +-(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray* /* NSString */) status completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; @@ -74,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..d79584f90bf 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,14 @@ 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 *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -125,27 +116,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"PUT" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -176,12 +152,14 @@ 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 *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -216,27 +194,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -260,19 +223,21 @@ 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 *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -316,8 +281,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -341,19 +307,21 @@ 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 *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -397,8 +365,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -434,13 +403,17 @@ 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"]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (petId != nil) { + pathParams[@"petId"] = petId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -468,7 +441,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + NSArray *authSettings = @[@"petstore_auth", @"api_key"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -478,8 +451,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -521,13 +495,17 @@ 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"]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (petId != nil) { + pathParams[@"petId"] = petId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -563,18 +541,23 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - formParams[@"name"] = name; + if (name) { + formParams[@"name"] = name; + } - formParams[@"status"] = status; + if (status) { + formParams[@"status"] = status; + } - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -613,13 +596,17 @@ 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"]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (petId != nil) { + pathParams[@"petId"] = petId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -659,8 +646,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"DELETE" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -702,13 +690,17 @@ 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"]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (petId != nil) { + pathParams[@"petId"] = petId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -744,7 +736,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - formParams[@"additionalMetadata"] = additionalMetadata; + if (additionalMetadata) { + formParams[@"additionalMetadata"] = additionalMetadata; + } @@ -754,8 +748,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h index 7b4f99dea7b..09e67e38ed0 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h @@ -18,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..792147ebed1 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,14 @@ 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 *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -125,8 +116,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -157,12 +149,14 @@ 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 *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -197,27 +191,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -253,13 +232,17 @@ 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"]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (orderId != nil) { + pathParams[@"orderId"] = orderId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -297,8 +280,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -334,13 +318,17 @@ 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"]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (orderId != nil) { + pathParams[@"orderId"] = orderId; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -378,8 +366,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"DELETE" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h index 9a3dfd9d23d..a6e69a8947d 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h @@ -18,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..92dd00fa28d 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,14 @@ 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 *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -125,27 +116,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -176,12 +152,14 @@ 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 *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -216,27 +194,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -267,12 +230,14 @@ 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 *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -307,27 +272,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"POST" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -361,12 +311,14 @@ 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 *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -412,8 +364,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -441,12 +394,14 @@ 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 *pathParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -484,8 +439,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -521,13 +477,17 @@ 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"]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (username != nil) { + pathParams[@"username"] = username; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -565,8 +525,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"GET" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -605,13 +566,17 @@ 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"]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (username != nil) { + pathParams[@"username"] = username; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -646,27 +611,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; bodyParam = body; - - if(bodyParam != nil && [bodyParam isKindOfClass:[NSArray class]]){ - NSMutableArray *objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)bodyParam) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(SWGObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyParam = objs; - } - else if([bodyParam respondsToSelector:@selector(toDictionary)]) { - bodyParam = [(SWGObject*)bodyParam toDictionary]; - } - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"PUT" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files @@ -702,13 +652,17 @@ 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"]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + if (username != nil) { + pathParams[@"username"] = username; + } NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; @@ -746,8 +700,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - return [self.apiClient requestWithCompletionBlock: requestUrl + return [self.apiClient requestWithCompletionBlock: resourcePath method: @"DELETE" + pathParams: pathParams queryParams: queryParams formParams: formParams files: files diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m index 5fe98be055f..ab7f6e8f72e 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m @@ -7,7 +7,9 @@ // #import "SWGViewController.h" +#import #import +#import #import @interface SWGViewController () @@ -19,11 +21,6 @@ - (void)viewDidLoad { [super viewDidLoad]; - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - [config setApiKey:@"hello" forApiKeyIdentifier:@"world"]; - [config setApiKey:@"geekerzp" forApiKeyIdentifier:@"zp"]; - [config removeApiKey:@"zp"]; - NSLog(@"%@", config.apiKey); } - (void)didReceiveMemoryWarning diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m index 2650dde31d0..0460a4be4af 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m @@ -55,6 +55,14 @@ 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 = @[ @@ -116,4 +124,42 @@ 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/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/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 535c623118a..713f864a4a5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -191,7 +191,7 @@ class ObjectSerializer $values[] = $this->deserialize($value, $subClass); } $deserialized = $values; - } elseif ($class === 'DateTime') { + } elseif ($class === '\DateTime') { $deserialized = new \DateTime($data); } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { settype($data, $class); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php index 7672667a235..3eb0d11a9b2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php @@ -31,6 +31,31 @@ class OrderApiTest extends \PHPUnit_Framework_TestCase $order = new Swagger\Client\Model\Order(); $order->setStatus("invalid_value"); } + + // test deseralization of order + public function testDeserializationOfOrder() + { + $order_json = <<deserialize(json_decode($order_json), 'Swagger\Client\Model\Order'); + + $this->assertInstanceOf('Swagger\Client\Model\Order', $order); + $this->assertSame(10, $order->getId()); + $this->assertSame(20, $order->getPetId()); + $this->assertSame(30, $order->getQuantity()); + $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $order->getShipDate()); + $this->assertSame("placed", $order->getStatus()); + $this->assertSame(false, $order->getComplete()); + } } 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/__init__.py b/samples/client/petstore/python/swagger_client/__init__.py index f61c5d55262..6e7b59f36fd 100644 --- a/samples/client/petstore/python/swagger_client/__init__.py +++ b/samples/client/petstore/python/swagger_client/__init__.py @@ -9,8 +9,8 @@ from .models.order import Order # import apis into sdk package from .apis.user_api import UserApi -from .apis.pet_api import PetApi from .apis.store_api import StoreApi +from .apis.pet_api import PetApi # import ApiClient from .api_client import ApiClient diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index 37bf1be69c0..02099f0ceb1 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 @@ -38,29 +48,47 @@ from .configuration import Configuration class ApiClient(object): """ - Generic API client for Swagger client library builds + 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 + 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. + + 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. """ def __init__(self, host=Configuration().host, - header_name=None, header_value=None): + header_name=None, header_value=None, cookie=None): + """ + 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 = None + self.cookie = cookie # Set default User-Agent. self.user_agent = 'Python-Swagger' @property def user_agent(self): + """ + Gets user agent. + """ return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): + """ + Sets user agent. + """ self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): @@ -129,11 +157,12 @@ class ApiClient(object): def to_path_value(self, obj): """ - Convert a string or object to a path-friendly value + Takes value and turn it into a string suitable for inclusion in + the path, by url-encoding. - :param obj: object or string value + :param obj: object or string value. - :return string: quoted value + :return string: quoted value. """ if type(obj) == list: return ','.join(obj) @@ -142,7 +171,7 @@ class ApiClient(object): def sanitize_for_serialization(self, obj): """ - Sanitize an object for Request. + Builds a JSON POST object. If obj is None, return None. If obj is str, int, float, bool, return directly. @@ -151,6 +180,9 @@ class ApiClient(object): 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 obj: The data to serialize. + :return: The serialized form of data. """ if isinstance(obj, type(None)): return None @@ -170,24 +202,22 @@ class ApiClient(object): # 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} + obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in iteritems(obj.swagger_types) + if getattr(obj, attr) is not None} return {key: self.sanitize_for_serialization(val) for key, val in iteritems(obj_dict)} def deserialize(self, response, response_type): """ - Derialize response into an object. + Deserializes response into an object. - :param response: RESTResponse object to be deserialized + :param response: RESTResponse object to be deserialized. :param response_type: class literal for - deserialzied object, or string of class name + deserialzied object, or string of class name. - :return: deserialized object + :return: deserialized object. """ # handle file downloading # save response body into a tmp file and return the instance @@ -204,22 +234,24 @@ class ApiClient(object): def __deserialize(self, data, klass): """ - :param data: dict, list or str - :param klass: class literal, or string of class name + Deserializes dict, list, str into an object. - :return: object + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. """ if data is None: return None if type(klass) == str: - if 'list[' in klass: + 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 'dict(' in klass: - sub_kls = re.match('dict\((.*), (.*)\)', klass).group(2) + 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)} @@ -248,8 +280,7 @@ class ApiClient(object): body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None): """ - Perform http request and return deserialized data - + Makes the HTTP request and return the deserialized data. :param resource_path: Path to method endpoint. :param method: Method to call. @@ -293,7 +324,7 @@ class ApiClient(object): def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): """ - Perform http request using RESTClient. + Makes the HTTP request using RESTClient. """ if method == "GET": return RESTClient.GET(url, @@ -305,16 +336,19 @@ class ApiClient(object): headers=headers) elif method == "POST": return RESTClient.POST(url, + query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "PUT": return RESTClient.PUT(url, + query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "PATCH": return RESTClient.PATCH(url, + query_params=query_params, headers=headers, post_params=post_params, body=body) @@ -329,6 +363,13 @@ class ApiClient(object): ) 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: @@ -350,7 +391,10 @@ class ApiClient(object): def select_header_accept(self, accepts): """ - Return `Accept` based on an array of accepts provided + Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). """ if not accepts: return @@ -364,7 +408,10 @@ class ApiClient(object): def select_header_content_type(self, content_types): """ - Return `Content-Type` baseed on an array of content_types provided + 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' @@ -378,7 +425,11 @@ class ApiClient(object): def update_params_for_auth(self, headers, querys, auth_settings): """ - Update header and query params based on authentication setting + 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() @@ -399,12 +450,12 @@ class ApiClient(object): def __deserialize_file(self, response): """ - Save response body into a file in (the defined) temporary folder, + 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 + :param response: RESTResponse. + :return: file path. """ config = Configuration() @@ -426,12 +477,12 @@ class ApiClient(object): def __deserialize_primitive(self, data, klass): """ - Deserialize string to primitive type + Deserializes string to primitive type. - :param data: str - :param klass: class literal + :param data: str. + :param klass: class literal. - :return: int, float, str, bool + :return: int, float, str, bool. """ try: value = klass(data) @@ -443,16 +494,18 @@ class ApiClient(object): def __deserialize_object(self): """ - Deserialize empty object + Deserializes empty object. + + :return: object. """ return object() def __deserialize_date(self, string): """ - Deserialize string to date + Deserializes string to date. - :param string: str - :return: date + :param string: str. + :return: date. """ try: from dateutil.parser import parse @@ -468,12 +521,12 @@ class ApiClient(object): def __deserialize_datatime(self, string): """ - Deserialize string to datetime. + Deserializes string to datetime. The string should be in iso8601 datetime format. - :param string: str - :return: datetime + :param string: str. + :return: datetime. """ try: from dateutil.parser import parse @@ -489,10 +542,11 @@ class ApiClient(object): def __deserialize_model(self, data, klass): """ - Deserialize list or dict to model + Deserializes list or dict to model. - :param data: dict, list - :param klass: class literal + :param data: dict, list. + :param klass: class literal. + :return: model object. """ instance = klass() diff --git a/samples/client/petstore/python/swagger_client/apis/__init__.py b/samples/client/petstore/python/swagger_client/apis/__init__.py index 592a56e282d..c0e09458f95 100644 --- a/samples/client/petstore/python/swagger_client/apis/__init__.py +++ b/samples/client/petstore/python/swagger_client/apis/__init__.py @@ -2,5 +2,5 @@ from __future__ import absolute_import # import apis into api package from .user_api import UserApi -from .pet_api import PetApi from .store_api import StoreApi +from .pet_api import PetApi 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 3f3e523a15a..fa1db5801b6 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,10 +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 @@ -33,6 +30,10 @@ 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() @@ -407,7 +408,7 @@ class PetApi(object): select_header_content_type([]) # Authentication setting - auth_settings = ['api_key', 'petstore_auth'] + auth_settings = ['petstore_auth', 'api_key'] response = self.api_client.call_api(resource_path, method, path_params, 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 ac465f792ec..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,10 +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 @@ -33,6 +30,10 @@ 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() 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 0469e83ae2f..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,10 +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 @@ -33,6 +30,10 @@ 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() diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index 0fe945bee1b..6bc58c90aea 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -1,7 +1,31 @@ +# 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: + # for python3 + import http.client as httplib + import sys import logging @@ -18,26 +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 + # 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() @@ -82,20 +125,33 @@ 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 """ + """ + Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ return { 'api_key': { @@ -107,6 +163,11 @@ class Configuration(object): } 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"\ diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py index ae03bb7ec78..bf70a7d10fd 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 """ @@ -16,6 +15,7 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ + from pprint import pformat from six import iteritems @@ -49,18 +49,46 @@ class Category(object): @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): @@ -69,18 +97,17 @@ class Category(object): """ 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( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/swagger_client/models/order.py index 7498561372e..1a7612df190 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 """ @@ -16,6 +15,7 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ + from pprint import pformat from six import iteritems @@ -56,47 +56,117 @@ class Order(object): self._pet_id = None self._quantity = None self._ship_date = None - self._status = None # Order Status + 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( @@ -107,10 +177,24 @@ class Order(object): @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): @@ -119,18 +203,17 @@ class Order(object): """ 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( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py index 62f7bea7fd2..cda4fa1e8cd 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 """ @@ -16,6 +15,7 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ + from pprint import pformat from six import iteritems @@ -57,54 +57,138 @@ class Pet(object): self._name = None self._photo_urls = None self._tags = None - self._status = None # pet status in the store + 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( @@ -119,18 +203,17 @@ class Pet(object): """ 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( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py index ea07acacfdb..8108052aae3 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 """ @@ -16,6 +15,7 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ + from pprint import pformat from six import iteritems @@ -49,18 +49,46 @@ class Tag(object): @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): @@ -69,18 +97,17 @@ class Tag(object): """ 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( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/swagger_client/models/user.py index d81a73318e7..576473adcfa 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 """ @@ -16,6 +15,7 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ + from pprint import pformat from six import iteritems @@ -63,70 +63,182 @@ class User(object): self._email = None self._password = None self._phone = None - self._user_status = None # User Status + 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): @@ -135,18 +247,17 @@ class User(object): """ 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( + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - prop + value )) - elif hasattr(prop, "to_dict"): - result[name[1:]] = prop.to_dict() + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() else: - result[name[1:]] = prop + result[attr] = value return result diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/swagger_client/rest.py index fab813a4cc9..f9f85f294dc 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 """ @@ -162,21 +176,24 @@ class RESTClientObject(object): headers=headers, query_params=query_params) - def POST(self, url, headers=None, post_params=None, body=None): + def POST(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("POST", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) - def PUT(self, url, headers=None, post_params=None, body=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("PUT", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) - def PATCH(self, url, headers=None, post_params=None, body=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("PATCH", url, headers=headers, + query_params=query_params, post_params=post_params, body=body) @@ -202,10 +219,10 @@ 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 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/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