diff --git a/.gitignore b/.gitignore index 76ede9e0e7a..d55a8014a34 100644 --- a/.gitignore +++ b/.gitignore @@ -55,4 +55,9 @@ samples/client/petstore/python/.projectile samples/client/petstore/python/.venv/ */.settings -modules/*/.settings/ + +*.mustache~ +*.java~ +*.pm~ +*.xml~ +*.t~ \ No newline at end of file diff --git a/README.md b/README.md index a13c194837a..0eeb2a3065e 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ ## Overview This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server. -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. +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. # Table of contents @@ -14,50 +14,37 @@ Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additi - [Overview](#overview) - [Table of Contents](#table-of-contents) - Installation - - [Build and run using docker](#build-and-run-using-docker) - - [Build a nodejs server stub](#build-a-nodejs-server-stub) - [Compatibility](#compatibility) - [Prerequisites](#prerequisites) - - [OS X Users](#os-x-users) - - [Building](#building) + - [OS X Users](#os-x-users) + - [Building](#building) + - [Docker](#docker) + - [Build and run](#build-and-run-using-docker) + - [Build a Node.js server stub](#build-a-nodejs-server-stub) + - [Homebrew](#homebrew) - Generators - [To generate a sample client library](#to-generate-a-sample-client-library) - [Generating libraries from your server](#generating-libraries-from-your-server) - [Modifying the client library format](#modifying-the-client-library-format) - [Making your own codegen modules](#making-your-own-codegen-modules) - [Where is Javascript???](#where-is-javascript) - - [Generating a client from local files](#generating-a-client-from-local-files) + - [Generating a client from local files](#generating-a-client-from-local-files) - [Customizing the generator](#customizing-the-generator) - [Validating your swagger spec](#validating-your-swagger-spec) - [Generating dynamic html api documentation](#generating-dynamic-html-api-documentation) - [Generating static html api documentation](#generating-static-html-api-documentation) - [To build a server stub](#to-build-a-server-stub) - - [node.js](#nodejs) - - [rails-grape](#rails-grape) - - [scala scalatra](#scala-scalatra) - - [java jax-rs](#java-jax-rs) - - [java spring-mvc](#java-spring-mvc) + - [Node.js](#nodejs) + - [PHP Silex](#php-silex) + - [Ruby Sinatra](#ruby-sinatra) + - [Scala Scalatra](#scala-scalatra) + - [Java JAX-RS](#java-jax-rs) + - [Java Spring MVC](#java-spring-mvc) - [To build the codegen library](#to-build-the-codegen-library) + - [Online Generators](#online-generators) + - [Guidelines for Contribution](https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution) - [License](#license) -## 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: @@ -76,24 +63,52 @@ You need the following installed and available in your $PATH: * [Java 7](http://java.oracle.com) * [Apache maven 3.0.3 or greater](http://maven.apache.org/) - + #### OS X Users Don't forget to install Java 7. You probably have 1.6 or 1.8. -Export JAVA_HOME in order to user proper Java version: +Export JAVA_HOME in order to use the supported Java version: ``` export JAVA_HOME=`/usr/libexec/java_home -v 1.7` export PATH=${JAVA_HOME}/bin:$PATH ``` -#### Building +### Building After cloning the project, you can build it from source with this command: - ``` mvn package ``` +### Docker +#### 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 Node.js server stub + + ``` +./run-in-docker.sh generate \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l nodejs \ + -o samples/server/petstore/nodejs + ``` + +### Homebrew +To install, run `brew install swagger-codegen` + +Here is an example usage: +``` +swagger-codegen generate -i http://petstore.swagger.io/v2/swagger.json -l ruby -o /tmp/test/ +``` + + ### To generate a sample client library You can build a client against the swagger sample [petstore](http://petstore.swagger.io) API as follows: @@ -110,7 +125,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -o samples/client/petstore/java ``` -With a number of options. You can get the options with the `help generate` command: +with a number of options. You can get the options with the `help generate` command: ``` NAME @@ -158,10 +173,10 @@ OPTIONS -v, --verbose verbose mode - + -s , --skip-overwrite - specifies if the existing files should be overwritten during - the generation + specifies if the existing files should be overwritten during + the generation ``` You can then compile and run the client, as well as unit tests against it: @@ -190,7 +205,7 @@ You can look at `modules/swagger-codegen/src/main/resources/${your-language}` fo If you're starting a project with a new language and don't see what you need, swagger-codegen can help you create a project to generate your own libraries: ``` -java -jar modules/swagger-codegen-distribution/target/swagger-codegen-cli.jar meta \ +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar meta \ -o output/myLibrary -n myClientCodegen -p com.my.company.codegen ``` @@ -202,7 +217,7 @@ static code generation. There is a third-party component called [swagger-js-codegen](https://github.com/wcandillon/swagger-js-codegen) that can generate angularjs or nodejs source code from a swagger specification. -#### Generating a client from local files +### Generating a client from local files If you don't want to call your server, you can save the swagger spec files into a directory and pass an argument to the code generator like this: @@ -290,7 +305,8 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -o samples/client/petstore/java \ -c path/to/config.json ``` -Supported config options can be different per language. Running `config-help -l {lang}` will show available options. +Supported config options can be different per language. Running `config-help -l {lang}` will show available options. **These options are applied +by passing them with `-D{optionName}={optionValue}**. ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar config-help -l java @@ -336,6 +352,7 @@ CONFIG OPTIONS jersey2 - HTTP client: Jersey client 2.6 okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 retrofit - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0) + retrofit2 - HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2) ``` Your config file for java can look like @@ -350,7 +367,7 @@ Your config file for java can look like For all the unspecified options default values will be used. -Another way to override default options is to extend config class for specific language. +Another way to override default options is to extend the config class for the specific language. To change, for example, the prefix for the Objective-C generated files, simply subclass the ObjcClientCodegen.java: ``` @@ -406,7 +423,7 @@ open index.html You can also use the codegen to generate a server for a couple different frameworks. Take a look here: -### node.js +### Node.js ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ @@ -415,11 +432,25 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -o samples/server/petstore/nodejs ``` -### rails-grape +### PHP Silex -*Not yet migrated to this branch* +``` +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l silex \ + -o samples/server/petstore/silex +``` -### scala scalatra +### Ruby Sinatra + +``` +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l sinatra \ + -o samples/server/petstore/sinatra +``` + +### Scala Scalatra ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ @@ -427,7 +458,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -o samples/server/petstore/scalatra ``` -### java jax-rs +### Java JAX-RS ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ @@ -436,7 +467,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -o samples/server/petstore/jaxrs ``` -### java spring-mvc +### Java Spring MVC ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ @@ -444,6 +475,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -l spring-mvc \ -o samples/server/petstore/spring-mvc ``` + ### To build the codegen library This will create the swagger-codegen library from source. @@ -454,6 +486,21 @@ mvn package Note! The templates are included in the library generated. If you want to modify the templates, you'll need to either repackage the library OR specify a path to your scripts +## Online generators + +One can also generate API client or server using the online generators (https://generator.swagger.io) + +For example, to generate Ruby API client, simply send the following HTTP request using curl: +``` +curl -X POST -H "content-type:application/json" -d '{"swaggerUrl":"http://petstore.swagger.io/v2/swagger.json"}' https://generator.swagger.io/api/gen/clients/ruby +``` +Then you will receieve a JSON response with the URL to download the zipped code. + +Guidelines for Contribution +--------------------------- + +Please refer to this [page](https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution) + License ------- diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 2f9d4c0c0ff..a439d015337 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -20,6 +20,7 @@ fi cd $APP_DIR ./bin/akka-scala-petstore.sh ./bin/android-java-petstore.sh +./bin/clojure-petstore.sh ./bin/csharp-petstore.sh ./bin/dynamic-html.sh ./bin/html-petstore.sh @@ -27,6 +28,7 @@ cd $APP_DIR ./bin/java-petstore-jersey2.sh ./bin/java-petstore-okhttp-gson.sh ./bin/java-petstore-retrofit.sh ++./bin/java-petstore-retrofit2.sh ./bin/jaxrs-petstore-server.sh ./bin/nodejs-petstore-server.sh ./bin/objc-petstore.sh diff --git a/bin/clojure-petstore.sh b/bin/clojure-petstore.sh new file mode 100755 index 00000000000..1f53d9d386c --- /dev/null +++ b/bin/clojure-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l clojure -o samples/client/petstore/clojure" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/flaskConnexion.sh b/bin/flaskConnexion.sh new file mode 100755 index 00000000000..f300d3124b1 --- /dev/null +++ b/bin/flaskConnexion.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l flaskConnexion -o samples/server/petstore/flaskConnexion " + +java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/bin/java-petstore-retrofit2.json b/bin/java-petstore-retrofit2.json new file mode 100644 index 00000000000..4829fd6dd4b --- /dev/null +++ b/bin/java-petstore-retrofit2.json @@ -0,0 +1,4 @@ +{ + "library": "retrofit2", + "artifactId": "swagger-petstore-retrofit2" +} diff --git a/bin/java-petstore-retrofit2.sh b/bin/java-petstore-retrofit2.sh new file mode 100755 index 00000000000..fbd1f9779e4 --- /dev/null +++ b/bin/java-petstore-retrofit2.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-retrofit2.json -o samples/client/petstore/java/retrofit2" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java index f7a128613b9..eb2f8afea92 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/ConfigHelp.java @@ -20,7 +20,7 @@ public class ConfigHelp implements Runnable { System.out.println("CONFIG OPTIONS"); for (CliOption langCliOption : config.cliOptions()) { System.out.println("\t" + langCliOption.getOpt()); - System.out.println("\t " + langCliOption.getDescription().replaceAll("\n", "\n\t ")); + System.out.println("\t " + langCliOption.getOptionHelp().replaceAll("\n", "\n\t ")); System.out.println(); } } diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 116d6c0c986..fc51a41fcdf 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -103,6 +103,18 @@ maven-release-plugin 2.1 + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + test-jar + + + + diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java index 2c90f4255ec..d6bbb9fa526 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -70,14 +70,29 @@ public abstract class AbstractGenerator { String libTemplateFile = config.templateDir() + File.separator + "libraries" + File.separator + library + File.separator + templateFile; - if (templateExists(libTemplateFile)) { + + if (new File(libTemplateFile).exists()) { + return libTemplateFile; + } + + libTemplateFile = config.embeddedTemplateDir() + File.separator + + "libraries" + File.separator + library + File.separator + + templateFile; + if (embeddedTemplateExists(libTemplateFile)) { + // Fall back to the template file embedded/packaged in the JAR file... return libTemplateFile; } } - return config.templateDir() + File.separator + templateFile; + String template = config.templateDir() + File.separator + templateFile; + if (new File(template).exists()) { + return template; + } else { + // Fall back to the template file embedded/packaged in the JAR file... + return config.embeddedTemplateDir() + File.separator + templateFile; + } } - public boolean templateExists(String name) { + public boolean embeddedTemplateExists(String name) { return this.getClass().getClassLoader().getResource(getCPResourcePath(name)) != null; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java index 1aa0937b31b..b2732f9cd1e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CliOption.java @@ -1,14 +1,31 @@ package io.swagger.codegen; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.models.properties.StringProperty; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import java.util.LinkedHashMap; +import java.util.Map; + public class CliOption { private final String opt; private String description; + private String type; + private String defaultValue; + private Map enumValues; public CliOption(String opt, String description) { - this.opt = opt; - this.description = description; + this(opt, description, StringProperty.TYPE); } + public CliOption(String opt, String description, String type) { + this.opt = opt; + this.description = description; + this.type = type; + } + + @ApiModelProperty(name = "optionName") public String getOpt() { return opt; } @@ -20,4 +37,58 @@ public class CliOption { public void setDescription(String description) { this.description = description; } + + @ApiModelProperty(value = "Data type is based on the types supported by the JSON-Schema") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDefault() { + return defaultValue; + } + + public void setDefault(String defaultValue) { + this.defaultValue = defaultValue; + } + + public CliOption defaultValue(String defaultValue) { + this.defaultValue = defaultValue; + return this; + } + + public CliOption addEnum(String value, String description) { + if (this.enumValues == null) { + this.enumValues = new LinkedHashMap(); + } + if (!enumValues.containsKey(value)) { + enumValues.put(value, description); + } + return this; + } + + public Map getEnum() { + return enumValues; + } + + public void setEnum(Map enumValues) { + this.enumValues = enumValues; + } + + @JsonIgnore + public String getOptionHelp() { + StringBuilder sb = new StringBuilder(description); + if(defaultValue != null) { + sb.append(" (Default: ").append(defaultValue).append(")"); + } + if (enumValues != null) { + for (Map.Entry entry : enumValues.entrySet()) { + sb.append("\n ").append(entry.getKey()).append(" - ").append(entry.getValue()); + } + } + return sb.toString(); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index b50147a6ff3..c111a3af2fc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -29,6 +29,8 @@ public interface CodegenConfig { String templateDir(); + String embeddedTemplateDir(); + String modelFileFolder(); String modelPackage(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index b2ada4a1981..a5bb97e5a93 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -38,6 +38,12 @@ public class CodegenConstants { public static final String LIBRARY_DESC = "library template (sub-template)"; public static final String SORT_PARAMS_BY_REQUIRED_FLAG = "sortParamsByRequiredFlag"; - public static final String SORT_PARAMS_BY_REQUIRED_FLAG_DESC = "Sort method arguments to place required parameters before optional parameters. Default: true"; + public static final String SORT_PARAMS_BY_REQUIRED_FLAG_DESC = "Sort method arguments to place required parameters before optional parameters."; + public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams"; + public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not). Default: true"; + + public static final String PACKAGE_NAME = "packageName"; + public static final String PACKAGE_VERSION = "packageVersion"; + public static final String POD_VERSION = "podVersion"; } 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 871b3f261c0..c5b9231341e 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 @@ -10,9 +10,10 @@ import java.util.Set; public class CodegenOperation { public final List responseHeaders = new ArrayList(); - public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive, - returnSimpleType, subresourceOperation, isMapContainer, isListContainer, - hasMore = Boolean.TRUE, isMultipart, isResponseBinary = Boolean.FALSE; + public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, + returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer, + isListContainer, isMultipart, hasMore = Boolean.TRUE, + isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE; public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer, summary, notes, baseName, defaultResponse; public List> consumes, produces; 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 1107c4f0c88..8c2d0e72559 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 @@ -78,6 +78,7 @@ public class DefaultCodegen { protected Map apiTemplateFiles = new HashMap(); protected Map modelTemplateFiles = new HashMap(); protected String templateDir; + protected String embeddedTemplateDir; protected Map additionalProperties = new HashMap(); protected List supportingFiles = new ArrayList(); protected List cliOptions = new ArrayList(); @@ -86,6 +87,7 @@ public class DefaultCodegen { protected Map supportedLibraries = new LinkedHashMap(); protected String library = null; protected Boolean sortParamsByRequiredFlag = true; + protected Boolean ensureUniqueParams = true; public List cliOptions() { return cliOptions; @@ -105,7 +107,13 @@ public class DefaultCodegen { } if (additionalProperties.containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { - this.setSortParamsByRequiredFlag(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString())); + this.setSortParamsByRequiredFlag(Boolean.valueOf(additionalProperties + .get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString())); + } + + if (additionalProperties.containsKey(CodegenConstants.ENSURE_UNIQUE_PARAMS)) { + this.setEnsureUniqueParams(Boolean.valueOf(additionalProperties + .get(CodegenConstants.ENSURE_UNIQUE_PARAMS).toString())); } } @@ -183,6 +191,14 @@ public class DefaultCodegen { return templateDir; } + public String embeddedTemplateDir() { + if (embeddedTemplateDir != null) { + return embeddedTemplateDir; + } else { + return templateDir; + } + } + public Map apiTemplateFiles() { return apiTemplateFiles; } @@ -192,11 +208,11 @@ public class DefaultCodegen { } public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + "/" + apiPackage().replace('.', '/'); } public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + "/" + modelPackage().replace('.', '/'); } public Map additionalProperties() { @@ -235,6 +251,10 @@ public class DefaultCodegen { this.sortParamsByRequiredFlag = sortParamsByRequiredFlag; } + public void setEnsureUniqueParams(Boolean ensureUniqueParams) { + this.ensureUniqueParams = ensureUniqueParams; + } + /** * Return the file name of the Api * @@ -423,9 +443,9 @@ public class DefaultCodegen { importMapping.put("LocalDate", "org.joda.time.*"); importMapping.put("LocalTime", "org.joda.time.*"); - cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue("true")); + cliOptions.add(new CliOption(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants.ENSURE_UNIQUE_PARAMS_DESC)); } /** @@ -804,6 +824,7 @@ public class DefaultCodegen { LOGGER.error("unexpected missing property for name " + name); return null; } + CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); property.name = toVarName(name); @@ -1200,6 +1221,7 @@ public class DefaultCodegen { op.examples = new ExampleGenerator(definitions).generate(methodResponse.getExamples(), operation.getProduces(), responseProperty); op.defaultResponse = toDefaultValue(responseProperty); op.returnType = cm.datatype; + op.hasReference = definitions != null && definitions.containsKey(op.returnBaseType); if (cm.isContainer != null) { op.returnContainer = cm.containerType; if ("map".equals(cm.containerType)) { @@ -1233,6 +1255,23 @@ public class DefaultCodegen { if (parameters != null) { for (Parameter param : parameters) { CodegenParameter p = fromParameter(param, imports); + // rename parameters to make sure all of them have unique names + if (ensureUniqueParams) { + while (true) { + boolean exists = false; + for (CodegenParameter cp : allParams) { + if (p.paramName.equals(cp.paramName)) { + exists = true; + break; + } + } + if (exists) { + p.paramName = generateNextName(p.paramName); + } else { + break; + } + } + } allParams.add(p); if (param instanceof QueryParameter) { p.isQueryParam = new Boolean(true); @@ -1260,6 +1299,9 @@ public class DefaultCodegen { p.isFormParam = new Boolean(true); formParams.add(p.copy()); } + if (p.required == null || !p.required) { + op.hasOptionalParams = true; + } } } for (String i : imports) { @@ -1271,7 +1313,7 @@ public class DefaultCodegen { op.httpMethod = httpMethod.toUpperCase(); // move "required" parameters in front of "optional" parameters - if(sortParamsByRequiredFlag) { + if (sortParamsByRequiredFlag) { Collections.sort(allParams, new Comparator() { @Override public int compare(CodegenParameter one, CodegenParameter another) { @@ -1406,6 +1448,9 @@ public class DefaultCodegen { } property = new ArrayProperty(inner); collectionFormat = qp.getCollectionFormat(); + if (collectionFormat == null) { + collectionFormat = "csv"; + } CodegenProperty pr = fromProperty("inner", inner); p.baseType = pr.datatype; p.isContainer = true; @@ -1713,6 +1758,28 @@ public class DefaultCodegen { return word; } + /** + * Generate the next name for the given name, i.e. append "2" to the base name if not ending with a number, + * otherwise increase the number by 1. For example: + * status => status2 + * status2 => status3 + * myName100 => myName101 + * + * @param name The base name + * @return The next name for the base name + */ + private String generateNextName(String name) { + Pattern pattern = Pattern.compile("\\d+\\z"); + Matcher matcher = pattern.matcher(name); + if (matcher.find()) { + String numStr = matcher.group(); + int num = Integer.parseInt(numStr) + 1; + return name.substring(0, name.length() - numStr.length()) + num; + } else { + return name + "2"; + } + } + private void addImport(CodegenModel m, String type) { if (type != null && needToImport(type)) { m.imports.add(type); @@ -1856,7 +1923,7 @@ public class DefaultCodegen { public String apiFilename(String templateName, String tag) { String suffix = apiTemplateFiles().get(templateName); - return apiFileFolder() + File.separator + toApiFilename(tag) + suffix; + return apiFileFolder() + '/' + toApiFilename(tag) + suffix; } public boolean shouldOverwrite(String filename) { @@ -1911,6 +1978,12 @@ public class DefaultCodegen { // character with _ or empty character. Below aims to spell out different cases we've // encountered so far and hopefully make it easier for others to add more special // cases in the future. + + // better error handling when map/array type is invalid + if (name == null) { + LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN"); + return "ERROR_UNKNOWN"; + } // input[] => input name = name.replaceAll("\\[\\]", ""); 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 9a2a47853ea..3623361387e 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 @@ -1,19 +1,8 @@ package io.swagger.codegen; -import static org.apache.commons.lang3.StringUtils.capitalize; -import static org.apache.commons.lang3.StringUtils.isNotEmpty; - import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; -import io.swagger.models.ComposedModel; -import io.swagger.models.Contact; -import io.swagger.models.Info; -import io.swagger.models.License; -import io.swagger.models.Model; -import io.swagger.models.Operation; -import io.swagger.models.Path; -import io.swagger.models.SecurityRequirement; -import io.swagger.models.Swagger; +import io.swagger.models.*; import io.swagger.models.auth.OAuth2Definition; import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.models.parameters.Parameter; @@ -23,14 +12,12 @@ import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; +import java.io.*; import java.util.*; +import static org.apache.commons.lang3.StringUtils.capitalize; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + public class DefaultGenerator extends AbstractGenerator implements Generator { Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class); @@ -216,7 +203,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { .withLoader(new Mustache.TemplateLoader() { @Override public Reader getTemplate(String name) { - return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); } }) .defaultValue("") @@ -262,6 +249,13 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.put("classVarName", config.toApiVarName(tag)); operation.put("importPath", config.toApiImport(tag)); + // Pass sortParamsByRequiredFlag through to the Mustache template... + boolean sortParamsByRequiredFlag = true; + if (this.config.additionalProperties().containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { + sortParamsByRequiredFlag = Boolean.valueOf((String)this.config.additionalProperties().get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString()); + } + operation.put("sortParamsByRequiredFlag", sortParamsByRequiredFlag); + processMimeTypes(swagger.getConsumes(), operation, "consumes"); processMimeTypes(swagger.getProduces(), operation, "produces"); @@ -285,7 +279,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { .withLoader(new Mustache.TemplateLoader() { @Override public Reader getTemplate(String name) { - return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); } }) .defaultValue("") @@ -314,6 +308,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (swagger.getHost() != null) { bundle.put("host", swagger.getHost()); } + bundle.put("swagger", this.swagger); bundle.put("basePath", basePath); bundle.put("scheme", scheme); bundle.put("contextPath", contextPath); @@ -376,7 +371,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { .withLoader(new Mustache.TemplateLoader() { @Override public Reader getTemplate(String name) { - return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); } }) .defaultValue("") diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java index 6be69b85d54..53c6ca5ab9b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/SupportingFile.java @@ -10,4 +10,14 @@ public class SupportingFile { this.folder = folder; this.destinationFilename = destinationFilename; } + + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("SupportingFile:").append("\n"); + builder.append("\ttemplateFile: ").append(templateFile).append("\n"); + builder.append("\tfolder: ").append(folder).append("\n"); + builder.append("\tdestinationFilename: ").append(destinationFilename).append("\n"); + + return builder.toString(); + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index 27a6716eceb..ad892917c70 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -339,6 +339,9 @@ public class CodegenConfigurator { if (dynamicProperties.containsKey(opt)) { codegenConfig.additionalProperties().put(opt, dynamicProperties.get(opt)); } + else if(systemProperties.containsKey(opt)) { + codegenConfig.additionalProperties().put(opt, systemProperties.get(opt).toString()); + } } } 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 38c0c5307ba..a8d66491851 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 @@ -6,6 +6,8 @@ import io.swagger.models.properties.*; import java.util.*; import java.io.File; +import org.apache.commons.lang.StringUtils; + public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public CodegenType getTag() { @@ -15,14 +17,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", - "this", "break", "double", "implements", "protected", "throw", - "byte", "else", "import", "public", "throws", "case", "enum", - "instanceof", "return", "transient", "catch", "extends", "int", - "short", "try", "char", "final", "interface", "static", "void", - "class", "finally", "const", "super", "while")); + reservedWords = new HashSet(Arrays.asList("abstract", "await", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield")); languageSpecificPrimitives = new HashSet(Arrays.asList( "String", @@ -79,7 +74,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp return name; // camelize the variable name - // pet_id => PetId + // pet_id => petId name = camelize(name, true); // for reserved word or word starting with number, append _ @@ -141,4 +136,20 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp type = swaggerType; return type; } + + @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 + // append _ at the beginning, e.g. _return + if (reservedWords.contains(operationId)) { + return escapeReservedWord(camelize(sanitizeName(operationId), true)); + } + + return camelize(sanitizeName(operationId), true); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java index c40eb653543..29732f1d45a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -3,6 +3,8 @@ package io.swagger.codegen.languages; import com.google.common.base.CaseFormat; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; + +import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; @@ -68,7 +70,7 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon outputFolder = "generated-code/scala"; modelTemplateFiles.put("model.mustache", ".scala"); apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "akka-scala"; + embeddedTemplateDir = templateDir = "akka-scala"; apiPackage = mainPackage + ".api"; modelPackage = mainPackage + ".model"; @@ -147,6 +149,9 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon ); instantiationTypes.put("array", "ListBuffer"); instantiationTypes.put("map", "Map"); + + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); } public CodegenType getTag() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 9c55053e59c..7983d83cea1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -17,6 +17,7 @@ import java.util.HashSet; import org.apache.commons.lang.StringUtils; public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String USE_ANDROID_MAVEN_GRADLE_PLUGIN = "useAndroidMavenGradlePlugin"; protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-android-client"; @@ -30,7 +31,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi outputFolder = "generated-code/android"; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "android-java"; + embeddedTemplateDir = templateDir = "android-java"; apiPackage = "io.swagger.client.api"; modelPackage = "io.swagger.client.model"; @@ -59,12 +60,15 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, "groupId for use in the generated build.gradle and pom.xml")); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, "artifactId for use in the generated build.gradle and pom.xml")); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "artifact version for use in the generated build.gradle and pom.xml")); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); - cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true.")); + cliOptions.add(new CliOption(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin.") + .defaultValue("true")); } public CodegenType getTag() { @@ -220,14 +224,15 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } - if (additionalProperties.containsKey("useAndroidMavenGradlePlugin")) { - this.setUseAndroidMavenGradlePlugin((Boolean) additionalProperties.get("useAndroidMavenGradlePlugin")); + if (additionalProperties.containsKey(USE_ANDROID_MAVEN_GRADLE_PLUGIN)) { + this.setUseAndroidMavenGradlePlugin(Boolean.valueOf((String) additionalProperties + .get(USE_ANDROID_MAVEN_GRADLE_PLUGIN))); } else { - additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + additionalProperties.put(USE_ANDROID_MAVEN_GRADLE_PLUGIN, useAndroidMavenGradlePlugin); } supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + additionalProperties.put(USE_ANDROID_MAVEN_GRADLE_PLUGIN, useAndroidMavenGradlePlugin); supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java index 38e6328a8e5..5e85712ffcd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java @@ -1,5 +1,6 @@ package io.swagger.codegen.languages; +import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; @@ -40,7 +41,7 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo outputFolder = "generated-code/async-scala"; modelTemplateFiles.put("model.mustache", ".scala"); apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "asyncscala"; + embeddedTemplateDir = templateDir = "asyncscala"; apiPackage = "io.swagger.client.api"; modelPackage = "io.swagger.client.model"; @@ -105,6 +106,9 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo ); instantiationTypes.put("array", "ListBuffer"); instantiationTypes.put("map", "HashMap"); + + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); } public CodegenType getTag() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index bd3487d06df..3ab152cf66d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -1,9 +1,12 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenModel; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; @@ -13,10 +16,15 @@ import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.List; +import java.util.Map; import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { + private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); protected String packageName = "IO.Swagger"; protected String packageVersion = "1.0.0"; protected String clientPackage = "IO.Swagger.Client"; @@ -27,7 +35,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig outputFolder = "generated-code" + File.separator + "csharp"; modelTemplateFiles.put("model.mustache", ".cs"); apiTemplateFiles.put("api.mustache", ".cs"); - templateDir = "csharp"; + embeddedTemplateDir = templateDir = "csharp"; apiPackage = "IO.Swagger.Api"; modelPackage = "IO.Swagger.Model"; @@ -79,28 +87,29 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.put("object", "Object"); cliOptions.clear(); - cliOptions.add(new CliOption("packageName", "C# package name (convention: Camel.Case), default: IO.Swagger")); - cliOptions.add(new CliOption("packageVersion", "C# package version, default: 1.0.0")); - + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case).") + .defaultValue("IO.Swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "C# package version.").defaultValue("1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC)); } @Override public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("packageVersion")) { - packageVersion = (String) additionalProperties.get("packageVersion"); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); } else { - additionalProperties.put("packageVersion", packageVersion); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); } - if (additionalProperties.containsKey("packageName")) { - packageName = (String) additionalProperties.get("packageName"); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); apiPackage = packageName + ".Api"; modelPackage = packageName + ".Model"; clientPackage = packageName + ".Client"; } else { - additionalProperties.put("packageName", packageName); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); } additionalProperties.put("clientPackage", clientPackage); @@ -252,4 +261,29 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig return camelize(sanitizeName(operationId)); } + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + @Override + public Map postProcessModels(Map objs) { + List models = (List) objs.get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + for (CodegenProperty var : cm.vars) { + // check to see if model name is same as the property name + // which will result in compilation error + // if found, prepend with _ to workaround the limitation + if (var.name.equals(cm.name)) { + var.name = "_" + var.name; + } + } + } + return objs; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java new file mode 100644 index 00000000000..0277c2d9077 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java @@ -0,0 +1,178 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.Contact; +import io.swagger.models.Info; +import io.swagger.models.License; +import io.swagger.models.Swagger; +import org.apache.commons.lang.StringUtils; + +import java.io.File; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.List; + +public class ClojureClientCodegen extends DefaultCodegen implements CodegenConfig { + private static final String PROJECT_NAME = "projectName"; + private static final String PROJECT_DESCRIPTION = "projectDescription"; + private static final String PROJECT_VERSION = "projectVersion"; + private static final String PROJECT_URL = "projectUrl"; + private static final String LICENSE_NAME = "licenseName"; + private static final String LICENSE_URL = "licenseUrl"; + private static final String BASE_NAMESPACE = "baseNamespace"; + + protected String projectName = null; + protected String projectDescription = null; + protected String projectVersion = null; + protected String sourceFolder = "src"; + + public ClojureClientCodegen() { + super(); + outputFolder = "generated-code" + File.separator + "clojure"; + apiTemplateFiles.put("api.mustache", ".clj"); + embeddedTemplateDir = templateDir = "clojure"; + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "clojure"; + } + + @Override + public String getHelp() { + return "Generates a Clojure client library."; + } + + @Override + public void preprocessSwagger(Swagger swagger) { + super.preprocessSwagger(swagger); + + if (additionalProperties.containsKey(PROJECT_NAME)) { + projectName = ((String) additionalProperties.get(PROJECT_NAME)); + } + if (additionalProperties.containsKey(PROJECT_DESCRIPTION)) { + projectDescription = ((String) additionalProperties.get(PROJECT_DESCRIPTION)); + } + if (additionalProperties.containsKey(PROJECT_VERSION)) { + projectVersion = ((String) additionalProperties.get(PROJECT_VERSION)); + } + + if (swagger.getInfo() != null) { + Info info = swagger.getInfo(); + if (projectName == null && info.getTitle() != null) { + // when projectName is not specified, generate it from info.title + projectName = dashize(info.getTitle()); + } + if (projectVersion == null) { + // when projectVersion is not specified, use info.version + projectVersion = info.getVersion(); + } + if (projectDescription == null) { + // when projectDescription is not specified, use info.description + projectDescription = info.getDescription(); + } + + if (info.getContact() != null) { + Contact contact = info.getContact(); + if (additionalProperties.get(PROJECT_URL) == null) { + additionalProperties.put(PROJECT_URL, contact.getUrl()); + } + } + if (info.getLicense() != null) { + License license = info.getLicense(); + if (additionalProperties.get(LICENSE_NAME) == null) { + additionalProperties.put(LICENSE_NAME, license.getName()); + } + if (additionalProperties.get(LICENSE_URL) == null) { + additionalProperties.put(LICENSE_URL, license.getUrl()); + } + } + } + + // default values + if (projectName == null) { + projectName = "swagger-clj-client"; + } + if (projectVersion == null) { + projectVersion = "1.0.0"; + } + if (projectDescription == null) { + projectDescription = "Client library of " + projectName; + } + + final String baseNamespace = dashize(projectName); + apiPackage = baseNamespace + ".api"; + + additionalProperties.put(PROJECT_NAME, projectName); + additionalProperties.put(PROJECT_DESCRIPTION, escapeText(projectDescription)); + additionalProperties.put(PROJECT_VERSION, projectVersion); + additionalProperties.put(BASE_NAMESPACE, baseNamespace); + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); + + final String baseNamespaceFolder = sourceFolder + File.separator + namespaceToFolder(baseNamespace); + supportingFiles.add(new SupportingFile("project.mustache", "", "project.clj")); + supportingFiles.add(new SupportingFile("core.mustache", baseNamespaceFolder, "core.clj")); + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + namespaceToFolder(apiPackage); + } + + @Override + public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method/operation name (operationId) not allowed"); + } + + return dashize(sanitizeName(operationId)); + } + + @Override + public String toApiName(String name) { + return dashize(name); + } + + @Override + public String toParamName(String name) { + return toVarName(name); + } + + @Override + public String toVarName(String name) { + name = name.replaceAll("[^a-zA-Z0-9_-]+", ""); + name = dashize(name); + return name; + } + + @Override + public Map postProcessOperations(Map operations) { + Map objs = (Map) operations.get("operations"); + List ops = (List) objs.get("operation"); + for (CodegenOperation op : ops) { + // Convert httpMethod to lower case, e.g. "get", "post" + op.httpMethod = op.httpMethod.toLowerCase(); + } + return operations; + } + + protected String namespaceToFolder(String ns) { + return ns.replace(".", File.separator).replace("-", "_"); + } + + protected String dashize(String s) { + return underscore(s).replaceAll("[_ ]", "-"); + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java index 9d9757a9131..7b6bf5e7844 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -15,6 +16,7 @@ import java.util.HashMap; import java.util.HashSet; public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String CLIENT_PACKAGE = "clientPackage"; protected String packageName = "IO.Swagger"; protected String packageVersion = "1.0.0"; protected String clientPackage = "IO.Swagger.Client"; @@ -25,7 +27,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege outputFolder = "generated-code" + File.separator + "CsharpDotNet2"; modelTemplateFiles.put("model.mustache", ".cs"); apiTemplateFiles.put("api.mustache", ".cs"); - templateDir = "CsharpDotNet2"; + embeddedTemplateDir = templateDir = "CsharpDotNet2"; apiPackage = "IO.Swagger.Api"; modelPackage = "IO.Swagger.Model"; @@ -77,34 +79,36 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege typeMapping.put("object", "Object"); cliOptions.clear(); - cliOptions.add(new CliOption("packageName", "C# package name (convention: Camel.Case), default: IO.Swagger")); - cliOptions.add(new CliOption("packageVersion", "C# package version, default: 1.0.0")); - + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case).") + .defaultValue("IO.Swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "C# package version.").defaultValue("1.0.0")); + cliOptions.add(new CliOption(CLIENT_PACKAGE, "C# client package name (convention: Camel.Case).") + .defaultValue("IO.Swagger.Client")); } @Override public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("packageVersion")) { - packageVersion = (String) additionalProperties.get("packageVersion"); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); } else { - additionalProperties.put("packageVersion", packageVersion); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); } - if (additionalProperties.containsKey("packageName")) { - packageName = (String) additionalProperties.get("packageName"); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); apiPackage = packageName + ".Api"; modelPackage = packageName + ".Model"; clientPackage = packageName + ".Client"; } else { - additionalProperties.put("packageName", packageName); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); } - if (additionalProperties.containsKey("clientPackage")) { - this.setClientPackage((String) additionalProperties.get("clientPackage")); + if (additionalProperties.containsKey(CLIENT_PACKAGE)) { + this.setClientPackage((String) additionalProperties.get(CLIENT_PACKAGE)); } else { - additionalProperties.put("clientPackage", clientPackage); + additionalProperties.put(CLIENT_PACKAGE, clientPackage); } supportingFiles.add(new SupportingFile("Configuration.mustache", @@ -123,6 +127,14 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege this.clientPackage = clientPackage; } + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + public CodegenType getTag() { return CodegenType.CLIENT; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index ede4505d4dd..e18b9eac0a2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -2,6 +2,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -15,6 +16,10 @@ import java.util.HashSet; import java.util.HashMap; public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String BROWSER_CLIENT = "browserClient"; + public static final String PUB_NAME = "pubName"; + public static final String PUB_VERSION = "pubVersion"; + public static final String PUB_DESCRIPTION = "pubDescription"; protected boolean browserClient = true; protected String pubName = "swagger"; protected String pubVersion = "1.0.0"; @@ -26,7 +31,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { outputFolder = "generated-code/dart"; modelTemplateFiles.put("model.mustache", ".dart"); apiTemplateFiles.put("api.mustache", ".dart"); - templateDir = "dart"; + embeddedTemplateDir = templateDir = "dart"; apiPackage = "lib.api"; modelPackage = "lib.model"; @@ -72,10 +77,11 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("date", "DateTime"); typeMapping.put("File", "MultipartFile"); - cliOptions.add(new CliOption("browserClient", "Is the client browser based")); - cliOptions.add(new CliOption("pubName", "Name in generated pubspec")); - cliOptions.add(new CliOption("pubVersion", "Version in generated pubspec")); - cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); + cliOptions.add(new CliOption(BROWSER_CLIENT, "Is the client browser based")); + cliOptions.add(new CliOption(PUB_NAME, "Name in generated pubspec")); + cliOptions.add(new CliOption(PUB_VERSION, "Version in generated pubspec")); + cliOptions.add(new CliOption(PUB_DESCRIPTION, "Description in generated pubspec")); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated code")); } public CodegenType getTag() { @@ -94,37 +100,37 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("browserClient")) { - this.setBrowserClient(Boolean.parseBoolean((String) additionalProperties.get("browserClient"))); - additionalProperties.put("browserClient", browserClient); + if (additionalProperties.containsKey(BROWSER_CLIENT)) { + this.setBrowserClient(Boolean.parseBoolean((String) additionalProperties.get(BROWSER_CLIENT))); + additionalProperties.put(BROWSER_CLIENT, browserClient); } else { //not set, use to be passed to template - additionalProperties.put("browserClient", browserClient); + additionalProperties.put(BROWSER_CLIENT, browserClient); } - if (additionalProperties.containsKey("pubName")) { - this.setPubName((String) additionalProperties.get("pubName")); + if (additionalProperties.containsKey(PUB_NAME)) { + this.setPubName((String) additionalProperties.get(PUB_NAME)); } else { //not set, use to be passed to template - additionalProperties.put("pubName", pubName); + additionalProperties.put(PUB_NAME, pubName); } - if (additionalProperties.containsKey("pubVersion")) { - this.setPubVersion((String) additionalProperties.get("pubVersion")); + if (additionalProperties.containsKey(PUB_VERSION)) { + this.setPubVersion((String) additionalProperties.get(PUB_VERSION)); } else { //not set, use to be passed to template - additionalProperties.put("pubVersion", pubVersion); + additionalProperties.put(PUB_VERSION, pubVersion); } - if (additionalProperties.containsKey("pubDescription")) { - this.setPubDescription((String) additionalProperties.get("pubDescription")); + if (additionalProperties.containsKey(PUB_DESCRIPTION)) { + this.setPubDescription((String) additionalProperties.get(PUB_DESCRIPTION)); } else { //not set, use to be passed to template - additionalProperties.put("pubDescription", pubDescription); + additionalProperties.put(PUB_DESCRIPTION, pubDescription); } - if (additionalProperties.containsKey("sourceFolder")) { - this.setSourceFolder((String) additionalProperties.get("sourceFolder")); + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { + this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } final String libFolder = sourceFolder + File.separator + "lib"; 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 index 7c484c38a0b..8608cbe8924 100755 --- 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 @@ -40,7 +40,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig modelTemplateFiles.put("model.mustache", ".as"); modelTemplateFiles.put("modelList.mustache", "List.as"); apiTemplateFiles.put("api.mustache", ".as"); - templateDir = "flash"; + embeddedTemplateDir = templateDir = "flash"; languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("Number"); @@ -68,15 +68,19 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig 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")); + 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(CodegenConstants.PACKAGE_NAME, "flash package name (convention:" + + " package.name)").defaultValue("io.swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "flash package version") + .defaultValue("1.0.0")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); - cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated code. e.g. src/main/flex")); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, "source folder for generated " + + "code. e.g. src/main/flex")); } @@ -95,8 +99,8 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } - if (additionalProperties.containsKey("packageName")) { - setPackageName((String) additionalProperties.get("packageName")); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); apiPackage = packageName + ".client.api"; modelPackage = packageName + ".client.model"; } @@ -104,20 +108,21 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig setPackageName("io.swagger"); } - if (additionalProperties.containsKey("packageVersion")) { - setPackageVersion((String) additionalProperties.get("packageVersion")); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); } else { setPackageVersion("1.0.0"); } - additionalProperties.put("packageName", packageName); - additionalProperties.put("packageVersion", packageVersion); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, 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); + 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")); @@ -131,13 +136,20 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig 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")); + 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) { @@ -163,11 +175,13 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String apiFileFolder() { - return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); + 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); + return (outputFolder + File.separatorChar + sourceFolder + File.separatorChar + + modelPackage().replace('.', File.separatorChar)).replace('/', File.separatorChar); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java new file mode 100644 index 00000000000..b3de913501a --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -0,0 +1,295 @@ +package io.swagger.codegen.languages; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Lists; +import com.google.common.collect.Multimap; +import io.swagger.codegen.*; +import io.swagger.models.Operation; +import io.swagger.models.Path; +import io.swagger.models.Swagger; +import io.swagger.util.Yaml; + +import java.io.File; +import java.util.*; + +public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConfig { + public static final String CONTROLLER_PACKAGE = "controllerPackage"; + public static final String DEFAULT_CONTROLLER = "defaultController"; + + protected String apiVersion = "1.0.0"; + protected int serverPort = 8080; + protected String projectName = "swagger-server"; + protected String controllerPackage; + protected String defaultController; + + public FlaskConnexionCodegen() { + super(); + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("float"); + languageSpecificPrimitives.add("list"); + languageSpecificPrimitives.add("bool"); + languageSpecificPrimitives.add("str"); + languageSpecificPrimitives.add("datetime"); + languageSpecificPrimitives.add("date"); + + typeMapping.clear(); + typeMapping.put("integer", "int"); + typeMapping.put("float", "float"); + typeMapping.put("number", "float"); + typeMapping.put("long", "int"); + typeMapping.put("double", "float"); + typeMapping.put("array", "list"); + typeMapping.put("map", "dict"); + typeMapping.put("boolean", "bool"); + typeMapping.put("string", "str"); + typeMapping.put("date", "date"); + typeMapping.put("DateTime", "datetime"); + typeMapping.put("object", "object"); + typeMapping.put("file", "file"); + + // set the output folder here + outputFolder = "generated-code/connexion"; + + modelTemplateFiles.clear(); + + apiTemplateFiles.clear(); + + /** + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + embeddedTemplateDir = templateDir = "flaskConnexion"; + + // from https://docs.python.org/release/2.5.4/ref/keywords.html + reservedWords = new HashSet( + Arrays.asList( + "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", + "assert", "else", "if", "pass", "yield", "break", "except", "import", + "print", "class", "exec", "in", "raise", "continue", "finally", "is", + "return", "def", "for", "lambda", "try")); + + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + additionalProperties.put("serverPort", serverPort); + + /** + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + + supportingFiles.add(new SupportingFile("swagger.mustache", + "swagger", + "swagger.yaml") + ); + supportingFiles.add(new SupportingFile("app.mustache", + "", + "app.py") + ); + supportingFiles.add(new SupportingFile("README.mustache", + "", + "README.md") + ); + + cliOptions.add(new CliOption(CONTROLLER_PACKAGE, "controller package"). + defaultValue("controllers")); + cliOptions.add(new CliOption(DEFAULT_CONTROLLER, "default controller"). + defaultValue("default_controller")); + } + + @Override + public void processOpts() { + super.processOpts(); + apiTemplateFiles.clear(); + + if (additionalProperties.containsKey(CONTROLLER_PACKAGE)) { + this.controllerPackage = additionalProperties.get(CONTROLLER_PACKAGE).toString(); + } + else { + this.controllerPackage = "controllers"; + additionalProperties.put(CONTROLLER_PACKAGE, this.controllerPackage); + } + if (additionalProperties.containsKey(DEFAULT_CONTROLLER)) { + this.defaultController = additionalProperties.get(DEFAULT_CONTROLLER).toString(); + } + else { + this.defaultController = "default_controller"; + additionalProperties.put(DEFAULT_CONTROLLER, this.defaultController); + } + + if(!new java.io.File(controllerPackage + File.separator + defaultController + ".py").exists()) { + supportingFiles.add(new SupportingFile("controller.mustache", + controllerPackage, + defaultController + ".py") + ); + } + } + + public String apiPackage() { + return controllerPackage; + } + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + public CodegenType getTag() { + return CodegenType.SERVER; + } + + /** + * Configures a friendly name for the generator. This will be used by the generator + * to select the library with the -l flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "python-flask"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a python server library using the connexion project. By default, " + + "it will also generate service classes--which you can disable with the `-Dnoservice` environment variable."; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultController"; + } + return initialCaps(name); + } + + @Override + public String toApiFilename(String name) { + return toApiName(name); + } + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reseved words + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public void preprocessSwagger(Swagger swagger) { + if(swagger != null && swagger.getPaths() != null) { + for(String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if(path.getOperations() != null) { + for(Operation operation : path.getOperations()) { + String operationId = operation.getOperationId(); + if(operationId != null && operationId.indexOf(".") == -1) { + operation.setVendorExtension("x-operationId", underscore(sanitizeName(operationId))); + operationId = controllerPackage + "." + defaultController + "." + underscore(sanitizeName(operationId)); + operation.setOperationId(operationId); + } + if(operation.getTags() != null) { + List> tags = new ArrayList>(); + for(String tag : operation.getTags()) { + Map value = new HashMap(); + value.put("tag", tag); + value.put("hasMore", "true"); + tags.add(value); + } + if(tags.size() > 0) { + tags.get(tags.size() - 1).remove("hasMore"); + } + if(operation.getTags().size() > 0) { + String tag = operation.getTags().get(0); + operation.setTags(Arrays.asList(tag)); + } + operation.setVendorExtension("x-tags", tags); + } + else { + String tag = "default_controller"; + operation.setTags(Arrays.asList(tag)); + } + } + } + } + } + } + + @SuppressWarnings("unchecked") + private List> getOperations(Map objs) { + List> result = new ArrayList>(); + Map apiInfo = (Map) objs.get("apiInfo"); + List> apis = (List>) apiInfo.get("apis"); + for (Map api : apis) { + result.add((Map) api.get("operations")); + } + return result; + } + + private List> sortOperationsByPath(List ops) { + Multimap opsByPath = ArrayListMultimap.create(); + + for (CodegenOperation op : ops) { + opsByPath.put(op.path, op); + } + + List> opsByPathList = new ArrayList>(); + for (Map.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) { + Swagger swagger = (Swagger)objs.get("swagger"); + if(swagger != null) { + try { + objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + } + for (Map operations : getOperations(objs)) { + @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/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index 658b0ca9602..636f0157a52 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 @@ -12,9 +12,14 @@ import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.models.Model; import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BooleanProperty; +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.StringProperty; import java.io.File; import java.util.ArrayList; @@ -31,12 +36,15 @@ import org.slf4j.LoggerFactory; public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); + public static final String FULL_JAVA_UTIL = "fullJavaUtil"; + public static final String DEFAULT_LIBRARY = ""; protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-java-client"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/java"; + protected String projectFolder = "src" + File.separator + "main"; + protected String sourceFolder = projectFolder + File.separator + "java"; protected String localVariablePrefix = ""; protected boolean fullJavaUtil = false; protected String javaUtilPrefix = ""; @@ -44,10 +52,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { public JavaClientCodegen() { super(); - outputFolder = "generated-code/java"; + outputFolder = "generated-code" + File.separator + "java"; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "Java"; + embeddedTemplateDir = templateDir = "Java"; apiPackage = "io.swagger.client.api"; modelPackage = "io.swagger.client.model"; @@ -77,6 +85,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); @@ -84,13 +94,19 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); cliOptions.add(new CliOption(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); - cliOptions.add(new CliOption("fullJavaUtil", "whether to use fully qualified name for classes under java.util (default to false)")); + cliOptions.add(new CliOption(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util") + .defaultValue("false")); - supportedLibraries.put("", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); + supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); supportedLibraries.put("retrofit", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); - cliOptions.add(buildLibraryCliOption(supportedLibraries)); + supportedLibraries.put("retrofit2", "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2)"); + CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use"); + library.setDefault(DEFAULT_LIBRARY); + library.setEnum(supportedLibraries); + library.setDefault(DEFAULT_LIBRARY); + cliOptions.add(library); } @Override @@ -150,7 +166,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { } if (additionalProperties.containsKey(CodegenConstants.SERIALIZABLE_MODEL)) { - this.setSerializableModel(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); + this.setSerializableModel(Boolean.valueOf(additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); } if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) { @@ -160,13 +176,13 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); - if (additionalProperties.containsKey("fullJavaUtil")) { - fullJavaUtil = Boolean.valueOf(additionalProperties.get("fullJavaUtil").toString()); + if (additionalProperties.containsKey(FULL_JAVA_UTIL)) { + this.setFullJavaUtil(Boolean.valueOf(additionalProperties.get(FULL_JAVA_UTIL).toString())); } if (fullJavaUtil) { javaUtilPrefix = "java.util."; } - additionalProperties.put("fullJavaUtil", fullJavaUtil); + additionalProperties.put(FULL_JAVA_UTIL, fullJavaUtil); additionalProperties.put("javaUtilPrefix", javaUtilPrefix); if (fullJavaUtil) { @@ -188,21 +204,23 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { this.sanitizeConfig(); - final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); + final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); + supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); - final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); + final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); - if (!"retrofit".equals(getLibrary())) { + if (!("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) { supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); @@ -216,7 +234,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); // "build.sbt" is for development with SBT supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); - } else if ("retrofit".equals(getLibrary())) { + } else if ("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); } else { @@ -251,12 +269,12 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/'); } @Override public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/'); } @Override @@ -346,12 +364,48 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { pattern = "new HashMap()"; } return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties())); + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + return "null"; } else if (p instanceof LongProperty) { LongProperty dp = (LongProperty) p; if (dp.getDefault() != null) { return dp.getDefault().toString()+"l"; } return "null"; + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString() + "d"; + } + return "null"; + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString() + "f"; + } + return "null"; + } else if (p instanceof BooleanProperty) { + BooleanProperty bp = (BooleanProperty) p; + if (bp.getDefault() != null) { + return bp.getDefault().toString(); + } + return "null"; + } else if (p instanceof StringProperty) { + StringProperty sp = (StringProperty) p; + if (sp.getDefault() != null) { + String _default = sp.getDefault(); + if (sp.getEnum() == null) { + return "\"" + escapeText(_default) + "\""; + } else { + // convert to enum var name later in postProcessModels + return _default; + } + } + return "null"; } return super.toDefaultValue(p); } @@ -444,13 +498,26 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { enumVars.add(enumVar); } allowableValues.put("enumVars", enumVars); + // handle default value for enum, e.g. available => StatusEnum.AVAILABLE + if (var.defaultValue != null) { + String enumName = null; + for (Map enumVar : enumVars) { + if (var.defaultValue.equals(enumVar.get("value"))) { + enumName = enumVar.get("name"); + break; + } + } + if (enumName != null) { + var.defaultValue = var.datatypeWithEnum + "." + enumName; + } + } } } return objs; } public Map postProcessOperations(Map objs) { - if("retrofit".equals(getLibrary())) { + if("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) { Map operations = (Map) objs.get("operations"); if (operations != null) { List ops = (List) operations.get("operation"); @@ -466,6 +533,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { if (operation.returnType == null) { operation.returnType = "Void"; } + if ("retrofit2".equals(getLibrary()) && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) + operation.path = operation.path.substring(1); } } } @@ -582,4 +651,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return packageName; } + public void setFullJavaUtil(boolean fullJavaUtil) { + this.fullJavaUtil = fullJavaUtil; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java index d678515f4cb..c0061bf39e7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java @@ -2,7 +2,9 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.SupportingFile; import io.swagger.models.Operation; @@ -30,7 +32,7 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod sourceFolder = "src/main/java"; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "JavaInflector"; + embeddedTemplateDir = templateDir = "JavaInflector"; invokerPackage = "io.swagger.handler"; artifactId = "swagger-inflector-server"; @@ -121,6 +123,22 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod co.baseName = basePath; } + @Override + public Map postProcessModels(Map objs) { + List models = (List) objs.get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + for (CodegenProperty var : cm.vars) { + // handle default value for enum, e.g. available => StatusEnum.available + if (var.isEnum && var.defaultValue != null && !"null".equals(var.defaultValue)) { + var.defaultValue = var.datatypeWithEnum + "." + var.defaultValue; + } + } + } + return objs; + } + public Map postProcessOperations(Map objs) { Map operations = (Map) objs.get("operations"); if (operations != null) { 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 883b08d8dfa..375f5d72bff 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 @@ -1,19 +1,12 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; -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.Path; +import io.swagger.models.Swagger; import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; +import java.util.*; public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig { protected String title = "Swagger Server"; @@ -31,7 +24,7 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf apiTemplateFiles.put("apiService.mustache", ".java"); apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); apiTemplateFiles.put("apiServiceFactory.mustache", ".java"); - templateDir = "JavaJaxRS"; + embeddedTemplateDir = templateDir = "JavaJaxRS"; apiPackage = System.getProperty("swagger.codegen.jaxrs.apipackage", "io.swagger.api"); modelPackage = System.getProperty("swagger.codegen.jaxrs.modelpackage", "io.swagger.model"); @@ -74,13 +67,13 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("ApiException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); + (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java")); supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); + (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiOriginFilter.java")); supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); + (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiResponseMessage.java")); supportingFiles.add(new SupportingFile("NotFoundException.mustache", - (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); + (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); supportingFiles.add(new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); @@ -114,6 +107,52 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf co.baseName = basePath; } + @Override + public void preprocessSwagger(Swagger swagger) { + if(swagger != null && swagger.getPaths() != null) { + for(String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if(path.getOperations() != null) { + for(Operation operation : path.getOperations()) { + if(operation.getTags() != null) { + List> tags = new ArrayList>(); + for(String tag : operation.getTags()) { + Map value = new HashMap(); + value.put("tag", tag); + value.put("hasMore", "true"); + tags.add(value); + } + if(tags.size() > 0) { + tags.get(tags.size() - 1).remove("hasMore"); + } + if(operation.getTags().size() > 0) { + String tag = operation.getTags().get(0); + operation.setTags(Arrays.asList(tag)); + } + operation.setVendorExtension("x-tags", tags); + } + } + } + } + } + } + + @Override + public Map postProcessModels(Map objs) { + List models = (List) objs.get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + for (CodegenProperty var : cm.vars) { + // handle default value for enum, e.g. available => StatusEnum.available + if (var.isEnum && var.defaultValue != null && !"null".equals(var.defaultValue)) { + var.defaultValue = var.datatypeWithEnum + "." + var.defaultValue; + } + } + } + return objs; + } + public Map postProcessOperations(Map objs) { Map operations = (Map) objs.get("operations"); if (operations != null) { @@ -175,9 +214,10 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf result = result.substring(0, ix) + "/impl" + result.substring(ix, result.length() - 5) + "ServiceImpl.java"; String output = System.getProperty("swagger.codegen.jaxrs.impl.source"); - if (output != null) { - result = result.replace(apiFileFolder(), implFileFolder(output)); + if(output == null) { + output = "src" + File.separator + "main" + File.separator + "java"; } + result = result.replace(apiFileFolder(), implFileFolder(output)); } else if (templateName.endsWith("Factory.mustache")) { int ix = result.lastIndexOf('/'); result = result.substring(0, ix) + "/factories" + result.substring(ix, result.length() - 5) + "ServiceFactory.java"; @@ -195,7 +235,7 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf } private String implFileFolder(String output) { - return outputFolder + "/" + output + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/'); } public boolean shouldOverwrite(String filename) { 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 10070ece512..4dee5f6f2df 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 @@ -1,27 +1,16 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.CodegenParameter; -import io.swagger.codegen.CodegenResponse; -import io.swagger.codegen.CodegenType; -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.fasterxml.jackson.core.JsonProcessingException; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; +import io.swagger.codegen.*; +import io.swagger.models.Swagger; +import io.swagger.util.Yaml; + +import java.io.File; +import java.util.*; +import java.util.Map.Entry; public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { protected String apiVersion = "1.0.0"; @@ -55,7 +44,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig * Template Location. This is the location which templates will be read from. The generator * will use the resource stream to attempt to read the templates. */ - templateDir = "nodejs"; + embeddedTemplateDir = templateDir = "nodejs"; /** * Reserved words. Override this with reserved words specific to your language @@ -87,7 +76,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig // ); supportingFiles.add(new SupportingFile("swagger.mustache", "api", - "swagger.json") + "swagger.yaml") ); supportingFiles.add(new SupportingFile("index.mustache", "", @@ -97,6 +86,10 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig "", "package.json") ); + supportingFiles.add(new SupportingFile("README.mustache", + "", + "README.md") + ); if (System.getProperty("noservice") == null) { apiTemplateFiles.put( "service.mustache", // the template to use @@ -242,6 +235,14 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig @Override public Map postProcessSupportingFileData(Map objs) { + Swagger swagger = (Swagger)objs.get("swagger"); + if(swagger != null) { + try { + objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + } for (Map operations : getOperations(objs)) { @SuppressWarnings("unchecked") List ops = (List) operations.get("operation"); 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 ef369169827..4555aa5f216 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 @@ -2,6 +2,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; @@ -19,6 +20,12 @@ import java.util.Set; import org.apache.commons.lang.StringUtils; public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String CLASS_PREFIX = "classPrefix"; + public static final String POD_NAME = "podName"; + public static final String AUTHOR_NAME = "authorName"; + public static final String AUTHOR_EMAIL = "authorEmail"; + public static final String GIT_REPO_URL = "gitRepoURL"; + public static final String LICENSE = "license"; protected Set foundationClasses = new HashSet(); protected String podName = "SwaggerClient"; protected String podVersion = "1.0.0"; @@ -36,7 +43,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { modelTemplateFiles.put("model-body.mustache", ".m"); apiTemplateFiles.put("api-header.mustache", ".h"); apiTemplateFiles.put("api-body.mustache", ".m"); - templateDir = "objc"; + embeddedTemplateDir = templateDir = "objc"; defaultIncludes.clear(); defaultIncludes.add("bool"); @@ -113,13 +120,17 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { instantiationTypes.put("map", "NSMutableDictionary"); cliOptions.clear(); - cliOptions.add(new CliOption("classPrefix", "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`), default: `SWG`")); - cliOptions.add(new CliOption("podName", "cocoapods package name (convention: CameCase), default: `SwaggerClient`")); - cliOptions.add(new CliOption("podVersion", "cocoapods package version, default: `1.0.0`")); - cliOptions.add(new CliOption("authorName", "Name to use in the podspec file, default: `Swagger`")); - cliOptions.add(new CliOption("authorEmail", "Email to use in the podspec file, default: `apiteam@swagger.io`")); - cliOptions.add(new CliOption("gitRepoURL", "URL for the git repo where this podspec should point to, default: `https://github.com/swagger-api/swagger-codegen`")); - cliOptions.add(new CliOption("license", "License to use in the podspec file, default: `MIT`")); + cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`).`") + .defaultValue("SWG")); + cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase).") + .defaultValue("SwaggerClient")); + cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file.").defaultValue("Swagger")); + cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file.").defaultValue("apiteam@swagger.io")); + cliOptions.add(new CliOption(GIT_REPO_URL, "URL for the git repo where this podspec should point to.") + .defaultValue("https://github.com/swagger-api/swagger-codegen")); + cliOptions.add(new CliOption(LICENSE, "License to use in the podspec file.").defaultValue("MIT")); } public CodegenType getTag() { @@ -138,41 +149,41 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("podName")) { - setPodName((String) additionalProperties.get("podName")); + if (additionalProperties.containsKey(POD_NAME)) { + setPodName((String) additionalProperties.get(POD_NAME)); } - if (additionalProperties.containsKey("podVersion")) { - setPodVersion((String) additionalProperties.get("podVersion")); + if (additionalProperties.containsKey(CodegenConstants.POD_VERSION)) { + setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION)); } - if (additionalProperties.containsKey("classPrefix")) { - setClassPrefix((String) additionalProperties.get("classPrefix")); + if (additionalProperties.containsKey(CLASS_PREFIX)) { + setClassPrefix((String) additionalProperties.get(CLASS_PREFIX)); } - if (additionalProperties.containsKey("authorName")) { - setAuthorName((String) additionalProperties.get("authorName")); + if (additionalProperties.containsKey(AUTHOR_NAME)) { + setAuthorName((String) additionalProperties.get(AUTHOR_NAME)); } - if (additionalProperties.containsKey("authorEmail")) { - setAuthorEmail((String) additionalProperties.get("authorEmail")); + if (additionalProperties.containsKey(AUTHOR_EMAIL)) { + setAuthorEmail((String) additionalProperties.get(AUTHOR_EMAIL)); } - if (additionalProperties.containsKey("gitRepoURL")) { - setGitRepoURL((String) additionalProperties.get("gitRepoURL")); + if (additionalProperties.containsKey(GIT_REPO_URL)) { + setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL)); } - if (additionalProperties.containsKey("license")) { - setLicense((String) additionalProperties.get("license")); + if (additionalProperties.containsKey(LICENSE)) { + setLicense((String) additionalProperties.get(LICENSE)); } - additionalProperties.put("podName", podName); - additionalProperties.put("podVersion", podVersion); - additionalProperties.put("classPrefix", classPrefix); - additionalProperties.put("authorName", authorName); - additionalProperties.put("authorEmail", authorEmail); - additionalProperties.put("gitRepoURL", gitRepoURL); - additionalProperties.put("license", license); + additionalProperties.put(POD_NAME, podName); + additionalProperties.put(CodegenConstants.POD_VERSION, podVersion); + additionalProperties.put(CLASS_PREFIX, classPrefix); + additionalProperties.put(AUTHOR_NAME, authorName); + additionalProperties.put(AUTHOR_EMAIL, authorEmail); + additionalProperties.put(GIT_REPO_URL, gitRepoURL); + additionalProperties.put(LICENSE, license); String swaggerFolder = podName; 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 d54c44a9bdd..27f39f11ed0 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 @@ -4,10 +4,11 @@ import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CliOption; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; -import io.swagger.codegen.CliOption; import java.io.File; import java.util.Arrays; @@ -16,6 +17,8 @@ import java.util.HashSet; import org.apache.commons.lang.StringUtils; public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String MODULE_NAME = "moduleName"; + public static final String MODULE_VERSION = "moduleVersion"; protected String moduleName = "SwaggerClient"; protected String moduleVersion = "1.0.0"; @@ -25,7 +28,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { outputFolder = "generated-code" + File.separatorChar + "perl"; modelTemplateFiles.put("object.mustache", ".pm"); apiTemplateFiles.put("api.mustache", ".pm"); - templateDir = "perl"; + embeddedTemplateDir = templateDir = "perl"; reservedWords = new HashSet( @@ -68,8 +71,11 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "object"); cliOptions.clear(); - cliOptions.add(new CliOption("moduleName", "perl module name (convention: CamelCase), default: SwaggerClient")); - cliOptions.add(new CliOption("moduleVersion", "perl module version, default: 1.0.0")); + cliOptions.add(new CliOption(MODULE_NAME, "Perl module name (convention: CamelCase).").defaultValue("SwaggerClient")); + cliOptions.add(new CliOption(MODULE_VERSION, "Perl module version.").defaultValue("1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants.ENSURE_UNIQUE_PARAMS_DESC)); + } @@ -77,21 +83,25 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("moduleVersion")) { - moduleVersion = (String) additionalProperties.get("moduleVersion"); + if (additionalProperties.containsKey(MODULE_VERSION)) { + setModuleVersion((String) additionalProperties.get(MODULE_VERSION)); } else { - additionalProperties.put("moduleVersion", moduleVersion); + additionalProperties.put(MODULE_VERSION, moduleVersion); } - if (additionalProperties.containsKey("moduleName")) { - moduleName = (String) additionalProperties.get("moduleName"); + if (additionalProperties.containsKey(MODULE_NAME)) { + setModuleName((String) additionalProperties.get(MODULE_NAME)); } else { - additionalProperties.put("moduleName", moduleName); + additionalProperties.put(MODULE_NAME, moduleName); } supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "ApiClient.pm")); supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "Configuration.pm")); supportingFiles.add(new SupportingFile("BaseObject.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "Object/BaseObject.pm")); + supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "ApiFactory.pm")); + supportingFiles.add(new SupportingFile("Role.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "Role.pm")); + supportingFiles.add(new SupportingFile("AutoDoc.mustache", ("lib/WWW/" + moduleName + "/Role").replace('/', File.separatorChar), "AutoDoc.pm")); + supportingFiles.add(new SupportingFile("autodoc.script.mustache", ("bin/").replace('/', File.separatorChar), "autodoc")); } public CodegenType getTag() { @@ -229,5 +239,11 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { return underscore(operationId); } + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + public void setModuleVersion(String moduleVersion) { + this.moduleVersion = moduleVersion; + } } 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 538a5c494a6..5b22fbdbadb 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 @@ -19,6 +19,11 @@ import java.util.HashSet; import org.apache.commons.lang3.StringUtils; public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String VARIABLE_NAMING_CONVENTION = "variableNamingConvention"; + public static final String PACKAGE_PATH = "packagePath"; + public static final String SRC_BASE_PATH = "srcBasePath"; + public static final String COMPOSER_VENDOR_NAME = "composerVendorName"; + public static final String COMPOSER_PROJECT_NAME = "composerProjectName"; protected String invokerPackage = "Swagger\\Client"; protected String composerVendorName = "swagger"; protected String composerProjectName = "swagger-client"; @@ -33,7 +38,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { outputFolder = "generated-code" + File.separator + "php"; modelTemplateFiles.put("model.mustache", ".php"); apiTemplateFiles.put("api.mustache", ".php"); - templateDir = "php"; + embeddedTemplateDir = templateDir = "php"; apiPackage = invokerPackage + "\\Api"; modelPackage = invokerPackage + "\\Model"; @@ -86,12 +91,15 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "object"); typeMapping.put("DateTime", "\\DateTime"); - cliOptions.add(new CliOption("variableNamingConvention", "naming convention of variable name, e.g. camelCase. Default: snake_case")); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + cliOptions.add(new CliOption(VARIABLE_NAMING_CONVENTION, "naming convention of variable name, e.g. camelCase.") + .defaultValue("snake_case")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, "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. 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(PACKAGE_PATH, "The main package name for classes. e.g. GeneratedPetstore")); + cliOptions.add(new CliOption(SRC_BASE_PATH, "The directory under packagePath to serve as source root.")); + cliOptions.add(new CliOption(COMPOSER_VENDOR_NAME, "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(COMPOSER_PROJECT_NAME, "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(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3")); } @@ -144,16 +152,16 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("packagePath")) { - this.setPackagePath((String) additionalProperties.get("packagePath")); + if (additionalProperties.containsKey(PACKAGE_PATH)) { + this.setPackagePath((String) additionalProperties.get(PACKAGE_PATH)); } else { - additionalProperties.put("packagePath", packagePath); + additionalProperties.put(PACKAGE_PATH, packagePath); } - if (additionalProperties.containsKey("srcBasePath")) { - this.setSrcBasePath((String) additionalProperties.get("srcBasePath")); + if (additionalProperties.containsKey(SRC_BASE_PATH)) { + this.setSrcBasePath((String) additionalProperties.get(SRC_BASE_PATH)); } else { - additionalProperties.put("srcBasePath", srcBasePath); + additionalProperties.put(SRC_BASE_PATH, srcBasePath); } if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { @@ -162,28 +170,24 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); } - if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { - this.setModelPackage((String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE)); - } else { + if (!additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); } - if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { - this.setApiPackage((String) additionalProperties.get(CodegenConstants.API_PACKAGE)); - } else { + if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); } - if (additionalProperties.containsKey("composerProjectName")) { - this.setComposerProjectName((String) additionalProperties.get("composerProjectName")); + if (additionalProperties.containsKey(COMPOSER_PROJECT_NAME)) { + this.setComposerProjectName((String) additionalProperties.get(COMPOSER_PROJECT_NAME)); } else { - additionalProperties.put("composerProjectName", composerProjectName); + additionalProperties.put(COMPOSER_PROJECT_NAME, composerProjectName); } - if (additionalProperties.containsKey("composerVendorName")) { - this.setComposerVendorName((String) additionalProperties.get("composerVendorName")); + if (additionalProperties.containsKey(COMPOSER_VENDOR_NAME)) { + this.setComposerVendorName((String) additionalProperties.get(COMPOSER_VENDOR_NAME)); } else { - additionalProperties.put("composerVendorName", composerVendorName); + additionalProperties.put(COMPOSER_VENDOR_NAME, composerVendorName); } if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) { @@ -191,6 +195,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { } else { additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } + + if (additionalProperties.containsKey(VARIABLE_NAMING_CONVENTION)) { + this.setParameterNamingConvention((String) additionalProperties.get(VARIABLE_NAMING_CONVENTION)); + } additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); @@ -286,7 +294,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { this.variableNamingConvention = variableNamingConvention; } - private void setComposerVendorName(String composerVendorName) { + public void setComposerVendorName(String composerVendorName) { this.composerVendorName = composerVendorName; } @@ -296,10 +304,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { - if (additionalProperties.containsKey("variableNamingConvention")) { - this.setParameterNamingConvention((String) additionalProperties.get("variableNamingConvention")); - } - // sanitize name name = sanitizeName(name); @@ -333,6 +337,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { // Note: backslash ("\\") is allowed for e.g. "\\DateTime" name = name.replaceAll("[^\\w\\\\]+", "_"); + // remove dollar sign + name = name.replaceAll("$", ""); + // model name cannot use reserved keyword if (reservedWords.contains(name)) { escapeReservedWord(name); // e.g. return => _return 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 6d9982cf78c..1759e515258 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 @@ -2,6 +2,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -27,7 +28,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig outputFolder = "generated-code" + File.separatorChar + "python"; modelTemplateFiles.put("model.mustache", ".py"); apiTemplateFiles.put("api.mustache", ".py"); - templateDir = "python"; + embeddedTemplateDir = templateDir = "python"; languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); @@ -62,30 +63,33 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig "return", "def", "for", "lambda", "try")); cliOptions.clear(); - cliOptions.add(new CliOption("packageName", "python package name (convention: snake_case), default: swagger_client")); - cliOptions.add(new CliOption("packageVersion", "python package version, default: 1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") + .defaultValue("swagger_client")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC)); } @Override public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("packageName")) { - setPackageName((String) additionalProperties.get("packageName")); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } else { setPackageName("swagger_client"); } - if (additionalProperties.containsKey("packageVersion")) { - setPackageVersion((String) additionalProperties.get("packageVersion")); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); } else { setPackageVersion("1.0.0"); } - additionalProperties.put("packageName", packageName); - additionalProperties.put("packageVersion", packageVersion); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); String swaggerFolder = packageName; @@ -171,6 +175,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig // sanitize name name = sanitizeName(name); + // remove dollar sign + name = name.replaceAll("$", ""); + // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { name = name.toLowerCase(); @@ -201,6 +208,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig public String toModelName(String name) { name = sanitizeName(name); + // remove dollar sign + name = name.replaceAll("$", ""); + // 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"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java index ff58dbd9440..2abff5515b0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -71,7 +71,7 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { * Template Location. This is the location which templates will be read from. The generator * will use the resource stream to attempt to read the templates. */ - templateDir = "qt5cpp"; + embeddedTemplateDir = templateDir = "qt5cpp"; /** * Reserved words. Override this with reserved words specific to your language @@ -97,7 +97,9 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { Arrays.asList( "bool", "qint32", - "qint64") + "qint64", + "float", + "double") ); supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); @@ -321,4 +323,4 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { public String toApiName(String type) { return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api"; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index 4aac683b6ef..f30b2ef8b85 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -2,6 +2,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -12,10 +13,14 @@ import io.swagger.models.properties.Property; import java.io.File; import java.util.Arrays; import java.util.HashSet; +import java.util.Iterator; import org.apache.commons.lang.StringUtils; public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String GEM_NAME = "gemName"; + public static final String MODULE_NAME = "moduleName"; + public static final String GEM_VERSION = "gemVersion"; protected String gemName = null; protected String moduleName = null; protected String gemVersion = "1.0.0"; @@ -28,7 +33,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { outputFolder = "generated-code" + File.separator + "ruby"; modelTemplateFiles.put("model.mustache", ".rb"); apiTemplateFiles.put("api.mustache", ".rb"); - templateDir = "ruby"; + embeddedTemplateDir = templateDir = "ruby"; typeMapping.clear(); languageSpecificPrimitives.clear(); @@ -67,21 +72,30 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("file", "File"); // remove modelPackage and apiPackage added by default - cliOptions.clear(); - cliOptions.add(new CliOption("gemName", "gem name (convention: underscore_case), default: swagger_client")); - cliOptions.add(new CliOption("moduleName", "top module name (convention: CamelCase, usually corresponding to gem name), default: SwaggerClient")); - cliOptions.add(new CliOption("gemVersion", "gem version, default: 1.0.0")); + Iterator itr = cliOptions.iterator(); + while (itr.hasNext()) { + CliOption opt = itr.next(); + if (CodegenConstants.MODEL_PACKAGE.equals(opt.getOpt()) || + CodegenConstants.API_PACKAGE.equals(opt.getOpt())) { + itr.remove(); + } + } + cliOptions.add(new CliOption(GEM_NAME, "gem name (convention: underscore_case)."). + defaultValue("swagger_client")); + cliOptions.add(new CliOption(MODULE_NAME, "top module name (convention: CamelCase, usually corresponding" + + " to gem name).").defaultValue("SwaggerClient")); + cliOptions.add(new CliOption(GEM_VERSION, "gem version.").defaultValue("1.0.0")); } @Override public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("gemName")) { - setGemName((String) additionalProperties.get("gemName")); + if (additionalProperties.containsKey(GEM_NAME)) { + setGemName((String) additionalProperties.get(GEM_NAME)); } - if (additionalProperties.containsKey("moduleName")) { - setModuleName((String) additionalProperties.get("moduleName")); + if (additionalProperties.containsKey(MODULE_NAME)) { + setModuleName((String) additionalProperties.get(MODULE_NAME)); } if (gemName == null && moduleName == null) { @@ -93,14 +107,14 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { setModuleName(generateModuleName(gemName)); } - additionalProperties.put("gemName", gemName); - additionalProperties.put("moduleName", moduleName); + additionalProperties.put(GEM_NAME, gemName); + additionalProperties.put(MODULE_NAME, moduleName); - if (additionalProperties.containsKey("gemVersion")) { - setGemVersion((String) additionalProperties.get("gemVersion")); + if (additionalProperties.containsKey(GEM_VERSION)) { + setGemVersion((String) additionalProperties.get(GEM_VERSION)); } else { // not set, pass the default value to template - additionalProperties.put("gemVersion", gemVersion); + additionalProperties.put(GEM_VERSION, gemVersion); } // use constant model/api package (folder path) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index 003be5ab950..b2f5b9571dd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -1,5 +1,6 @@ package io.swagger.codegen.languages; +import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; @@ -42,7 +43,7 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig outputFolder = "generated-code/scala"; modelTemplateFiles.put("model.mustache", ".scala"); apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "scala"; + embeddedTemplateDir = templateDir = "scala"; apiPackage = "io.swagger.client.api"; modelPackage = "io.swagger.client.model"; @@ -106,6 +107,9 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig ); instantiationTypes.put("array", "ListBuffer"); instantiationTypes.put("map", "HashMap"); + + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); } public CodegenType getTag() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java index 9bab6a6cad0..d50fa867887 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -1,5 +1,6 @@ package io.swagger.codegen.languages; +import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenOperation; @@ -29,7 +30,7 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf outputFolder = "generated-code/scalatra"; modelTemplateFiles.put("model.mustache", ".scala"); apiTemplateFiles.put("api.mustache", ".scala"); - templateDir = "scalatra"; + embeddedTemplateDir = templateDir = "scalatra"; apiPackage = "com.wordnik.client.api"; modelPackage = "com.wordnik.client.model"; @@ -117,6 +118,9 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf importMapping.put("LocalDateTime", "org.joda.time.LocalDateTime"); importMapping.put("LocalDate", "org.joda.time.LocalDate"); importMapping.put("LocalTime", "org.joda.time.LocalTime"); + + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); } public CodegenType getTag() { 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 e25aae15976..2e35f412bbf 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 @@ -35,7 +35,7 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig modelTemplateFiles.clear(); apiTemplateFiles.clear(); - templateDir = "silex"; + embeddedTemplateDir = templateDir = "silex"; reservedWords = new HashSet( Arrays.asList( diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java index c9d8e550b5d..9bcece87429 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java @@ -29,7 +29,7 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi // no model modelTemplateFiles.clear(); apiTemplateFiles.put("api.mustache", ".rb"); - templateDir = "sinatra"; + embeddedTemplateDir = templateDir = "sinatra"; typeMapping.clear(); languageSpecificPrimitives.clear(); 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 30d10073268..446185bcd47 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 @@ -15,6 +15,7 @@ import java.util.Map; import java.util.Iterator; public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig { + public static final String CONFIG_PACKAGE = "configPackage"; protected String title = "Petstore Server"; protected String configPackage = ""; @@ -23,7 +24,7 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen outputFolder = "generated-code/javaSpringMVC"; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "JavaSpringMVC"; + embeddedTemplateDir = templateDir = "JavaSpringMVC"; apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; configPackage = "io.swagger.configuration"; @@ -36,7 +37,7 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); additionalProperties.put("title", title); additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); - additionalProperties.put("configPackage", configPackage); + additionalProperties.put(CONFIG_PACKAGE, configPackage); languageSpecificPrimitives = new HashSet( Arrays.asList( @@ -49,8 +50,7 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen "Float") ); - cliOptions.add(new CliOption("configPackage", "configuration package for generated code")); - + cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); } public CodegenType getTag() { @@ -69,8 +69,8 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("configPackage")) { - this.setConfigPackage((String) additionalProperties.get("configPackage")); + if (additionalProperties.containsKey(CONFIG_PACKAGE)) { + this.setConfigPackage((String) additionalProperties.get(CONFIG_PACKAGE)); } supportingFiles.clear(); @@ -193,6 +193,17 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen String _import = iterator.next().get("import"); if (_import.endsWith(".Object")) iterator.remove(); } + List models = (List) objs.get("models"); + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + for (CodegenProperty var : cm.vars) { + // handle default value for enum, e.g. available => StatusEnum.available + if (var.isEnum && var.defaultValue != null && !"null".equals(var.defaultValue)) { + var.defaultValue = var.datatypeWithEnum + "." + var.defaultValue; + } + } + } return objs; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java index c0ccf2a0a6f..b27ba23a4cd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java @@ -20,7 +20,7 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { outputFolder = "docs"; modelTemplateFiles.put("model.mustache", ".html"); apiTemplateFiles.put("operation.mustache", ".html"); - templateDir = "swagger-static"; + embeddedTemplateDir = templateDir = "swagger-static"; additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java index 29cb5d55eaa..a86c2244995 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java @@ -28,7 +28,7 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig public StaticHtmlGenerator() { super(); outputFolder = "docs"; - templateDir = "htmlDocs"; + embeddedTemplateDir = templateDir = "htmlDocs"; defaultIncludes = new HashSet(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java index 94f6279f46f..3241dde7b92 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java @@ -13,7 +13,7 @@ import java.io.File; public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig { public SwaggerGenerator() { super(); - templateDir = "swagger"; + embeddedTemplateDir = templateDir = "swagger"; outputFolder = "generated-code/swagger"; supportingFiles.add(new SupportingFile("README.md", "", "README.md")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java index 35874390e0f..8ee1440b17e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java @@ -13,7 +13,7 @@ import java.io.File; public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfig { public SwaggerYamlGenerator() { super(); - templateDir = "swagger"; + embeddedTemplateDir = templateDir = "swagger"; outputFolder = "generated-code/swagger"; supportingFiles.add(new SupportingFile("README.md", "", "README.md")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index db0b0fc24eb..fffd3aa2aae 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -24,13 +24,26 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { - private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); + public static final String PROJECT_NAME = "projectName"; + public static final String RESPONSE_AS = "responseAs"; + public static final String UNWRAP_REQUIRED = "unwrapRequired"; + public static final String POD_SOURCE = "podSource"; + public static final String POD_AUTHORS = "podAuthors"; + public static final String POD_SOCIAL_MEDIA_URL = "podSocialMediaURL"; + public static final String POD_DOCSET_URL = "podDocsetURL"; + public static final String POD_LICENSE = "podLicense"; + public static final String POD_HOMEPAGE = "podHomepage"; + public static final String POD_SUMMARY = "podSummary"; + public static final String POD_DESCRIPTION = "podDescription"; + public static final String POD_SCREENSHOTS = "podScreenshots"; + public static final String POD_DOCUMENTATION_URL = "podDocumentationURL"; protected static final String LIBRARY_PROMISE_KIT = "PromiseKit"; protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT }; protected String projectName = "SwaggerClient"; protected boolean unwrapRequired = false; protected String[] responseAs = new String[0]; protected String sourceFolder = "Classes" + File.separator + "Swaggers"; + private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); public CodegenType getTag() { return CodegenType.CLIENT; @@ -49,7 +62,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { outputFolder = "generated-code" + File.separator + "swift"; modelTemplateFiles.put("model.mustache", ".swift"); apiTemplateFiles.put("api.mustache", ".swift"); - templateDir = "swift"; + embeddedTemplateDir = templateDir = "swift"; apiPackage = File.separator + "APIs"; modelPackage = File.separator + "Models"; @@ -107,22 +120,22 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { importMapping = new HashMap(); - cliOptions.add(new CliOption("projectName", "Project name in Xcode")); - cliOptions.add(new CliOption("responseAs", "Optionally use libraries to manage response. Currently " + + cliOptions.add(new CliOption(PROJECT_NAME, "Project name in Xcode")); + cliOptions.add(new CliOption(RESPONSE_AS, "Optionally use libraries to manage response. Currently " + StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available.")); - cliOptions.add(new CliOption("unwrapRequired", "Treat 'required' properties in response as non-optional " + + cliOptions.add(new CliOption(UNWRAP_REQUIRED, "Treat 'required' properties in response as non-optional " + "(which would crash the app if api returns null as opposed to required option specified in json schema")); - cliOptions.add(new CliOption("podSource", "Source information used for Podspec")); - cliOptions.add(new CliOption("podVersion", "Version used for Podspec")); - cliOptions.add(new CliOption("podAuthors", "Authors used for Podspec")); - cliOptions.add(new CliOption("podSocialMediaURL", "Social Media URL used for Podspec")); - cliOptions.add(new CliOption("podDocsetURL", "Docset URL used for Podspec")); - cliOptions.add(new CliOption("podLicense", "License used for Podspec")); - cliOptions.add(new CliOption("podHomepage", "Homepage used for Podspec")); - cliOptions.add(new CliOption("podSummary", "Summary used for Podspec")); - cliOptions.add(new CliOption("podDescription", "Description used for Podspec")); - cliOptions.add(new CliOption("podScreenshots", "Screenshots used for Podspec")); - cliOptions.add(new CliOption("podDocumentationURL", "Documentation URL used for Podspec")); + cliOptions.add(new CliOption(POD_SOURCE, "Source information used for Podspec")); + cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "Version used for Podspec")); + cliOptions.add(new CliOption(POD_AUTHORS, "Authors used for Podspec")); + cliOptions.add(new CliOption(POD_SOCIAL_MEDIA_URL, "Social Media URL used for Podspec")); + cliOptions.add(new CliOption(POD_DOCSET_URL, "Docset URL used for Podspec")); + cliOptions.add(new CliOption(POD_LICENSE, "License used for Podspec")); + cliOptions.add(new CliOption(POD_HOMEPAGE, "Homepage used for Podspec")); + cliOptions.add(new CliOption(POD_SUMMARY, "Summary used for Podspec")); + cliOptions.add(new CliOption(POD_DESCRIPTION, "Description used for Podspec")); + cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec")); + cliOptions.add(new CliOption(POD_DOCUMENTATION_URL, "Documentation URL used for Podspec")); } @Override @@ -130,29 +143,29 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { super.processOpts(); // Setup project name - if (additionalProperties.containsKey("projectName")) { - projectName = (String) additionalProperties.get("projectName"); + if (additionalProperties.containsKey(PROJECT_NAME)) { + setProjectName((String) additionalProperties.get(PROJECT_NAME)); } else { - additionalProperties.put("projectName", projectName); + additionalProperties.put(PROJECT_NAME, projectName); } sourceFolder = projectName + File.separator + sourceFolder; // Setup unwrapRequired option, which makes all the properties with "required" non-optional - if (additionalProperties.containsKey("unwrapRequired")) { - unwrapRequired = Boolean.parseBoolean(String.valueOf(additionalProperties.get("unwrapRequired"))); + if (additionalProperties.containsKey(UNWRAP_REQUIRED)) { + setUnwrapRequired(Boolean.parseBoolean(String.valueOf(additionalProperties.get(UNWRAP_REQUIRED)))); } - additionalProperties.put("unwrapRequired", unwrapRequired); + additionalProperties.put(UNWRAP_REQUIRED, unwrapRequired); // Setup unwrapRequired option, which makes all the properties with "required" non-optional - if (additionalProperties.containsKey("responseAs")) { - Object responseAsObject = additionalProperties.get("responseAs"); + if (additionalProperties.containsKey(RESPONSE_AS)) { + Object responseAsObject = additionalProperties.get(RESPONSE_AS); if (responseAsObject instanceof String) { - responseAs = ((String)responseAsObject).split(","); + setResponseAs(((String)responseAsObject).split(",")); } else { - responseAs = (String[]) responseAsObject; + setResponseAs((String[]) responseAsObject); } } - additionalProperties.put("responseAs", responseAs); + additionalProperties.put(RESPONSE_AS, responseAs); if (ArrayUtils.contains(responseAs, LIBRARY_PROMISE_KIT)) { additionalProperties.put("usePromiseKit", true); } @@ -308,4 +321,16 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { return builder.toString(); } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public void setUnwrapRequired(boolean unwrapRequired) { + this.unwrapRequired = unwrapRequired; + } + + public void setResponseAs(String[] responseAs) { + this.responseAs = responseAs; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java index 7dc0b8ec3bd..8efb5276cff 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java @@ -40,7 +40,7 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig modelTemplateFiles.put("model-body.mustache", ".cpp"); apiTemplateFiles.put("api-header.mustache", ".h"); apiTemplateFiles.put("api-body.mustache", ".cpp"); - templateDir = "tizen"; + embeddedTemplateDir = templateDir = "tizen"; modelPackage = ""; defaultIncludes = new HashSet( diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index d145760d2cc..6c9b615476d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -4,7 +4,7 @@ import io.swagger.codegen.SupportingFile; import java.io.File; public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen { - + @Override public String getName() { return "typescript-angular"; @@ -19,7 +19,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode outputFolder = "generated-code/typescript-angular"; modelTemplateFiles.put("model.mustache", ".ts"); apiTemplateFiles.put("api.mustache", ".ts"); - templateDir = "TypeScript-Angular"; + embeddedTemplateDir = templateDir = "TypeScript-Angular"; apiPackage = "API.Client"; modelPackage = "API.Client"; supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index b92598b1fb6..b4de0f7ed0c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -17,7 +17,7 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen public TypeScriptNodeClientCodegen() { super(); outputFolder = "generated-code/typescript-node"; - templateDir = "TypeScript-node"; + embeddedTemplateDir = templateDir = "TypeScript-node"; supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); } diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 18d27ede7c3..91d1eb93daf 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -55,13 +55,15 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { - // Use ISO 8601 format for date and datetime. - // See https://en.wikipedia.org/wiki/ISO_8601 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + this.json.setDateFormat((DateFormat) dateFormat.clone()); + // Set default User-Agent. setUserAgent("Java-Swagger"); @@ -74,6 +76,13 @@ public class ApiClient { authentications = Collections.unmodifiableMap(authentications); } + /** + * Gets the JSON instance to do JSON serialization and deserialization. + */ + public JSON getJSON() { + return json; + } + public String getBasePath() { return basePath; } @@ -166,6 +175,19 @@ public class ApiClient { throw new RuntimeException("No API key authentication configured!"); } + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + /** * Set the User-Agent header's value (by adding to the default header map). */ @@ -214,6 +236,8 @@ public class ApiClient { */ public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; + // also set the date format for model (de)serialization with Date properties + this.json.setDateFormat((DateFormat) dateFormat.clone()); return this; } diff --git a/modules/swagger-codegen/src/main/resources/Java/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/JSON.mustache index 43b38f6e21d..54faed8dcb3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/JSON.mustache @@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.datatype.joda.*; +import java.text.DateFormat; + import java.io.IOException; {{>generatedAnnotation}} @@ -20,6 +22,13 @@ public class JSON { mapper.registerModule(new JodaModule()); } + /** + * Set the date format for JSON (de)serialization with Date properties. + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } + /** * Serialize the given Java object into JSON string. */ diff --git a/modules/swagger-codegen/src/main/resources/Java/README.mustache b/modules/swagger-codegen/src/main/resources/Java/README.mustache new file mode 100644 index 00000000000..7ce9bac3ca0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/README.mustache @@ -0,0 +1,43 @@ +# {{artifactId}} + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation & Usage + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: + +```xml + + {{groupId}} + {{artifactId}} + {{artifactVersion}} + compile + + +``` + +## 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}} +{{/hasMore}}{{/apis}}{{/apiInfo}} + diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 08d28ebd51b..3ac280b2d70 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -64,7 +64,7 @@ public class {{classname}} { {{/queryParams}} {{#headerParams}}if ({{paramName}} != null) - {{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}})); + {{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}})); {{/headerParams}} {{#formParams}}if ({{paramName}} != null) 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 a1f1b6a827c..902f54a2e3a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache @@ -7,8 +7,20 @@ import java.util.List; {{>generatedAnnotation}} public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + @Override public void applyToParams(List queryParams, Map headerParams) { - // TODO: support oauth + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } } } diff --git a/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache index 971dcd816a4..2725cbe1f86 100644 --- a/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache @@ -18,72 +18,76 @@ repositories { if(hasProperty('target') && target == 'android') { - apply plugin: 'com.android.library' - apply plugin: 'com.github.dcendents.android-maven' - - android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' - defaultConfig { - minSdkVersion 14 - targetSdkVersion 22 - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - } - - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.each { output -> - def outputFile = output.outputFile - if (outputFile != null && outputFile.name.endsWith('.aar')) { - def fileName = "${project.name}-${variant.baseName}-${version}.aar" - output.outputFile = new File(outputFile.parent, fileName) - } - } - } - } - - afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDir - task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } - } - - task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' - } - - artifacts { - archives sourcesJar - } + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } } else { - apply plugin: 'java' - apply plugin: 'maven' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - - install { - repositories.mavenInstaller { - pom.artifactId = '{{artifactId}}' - } - } - - task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath - } + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } } ext { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index fffd5fc824f..bd64a6fe659 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -45,6 +45,7 @@ import {{invokerPackage}}.auth.OAuth; {{>generatedAnnotation}} public class ApiClient { + private Client client; private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); private boolean debugging = false; @@ -59,16 +60,20 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { - // Use ISO 8601 format for date and datetime. - // See https://en.wikipedia.org/wiki/ISO_8601 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + this.json.setDateFormat((DateFormat) dateFormat.clone()); + // Set default User-Agent. setUserAgent("Java-Swagger"); + buildClient(); + // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap();{{#authMethods}}{{#isBasic}} authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} @@ -78,6 +83,13 @@ public class ApiClient { authentications = Collections.unmodifiableMap(authentications); } + /** + * Gets the JSON instance to do JSON serialization and deserialization. + */ + public JSON getJSON() { + return json; + } + public String getBasePath() { return basePath; } @@ -170,6 +182,19 @@ public class ApiClient { throw new RuntimeException("No API key authentication configured!"); } + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + /** * Set the User-Agent header's value (by adding to the default header map). */ @@ -203,6 +228,7 @@ public class ApiClient { */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; + buildClient(); return this; } @@ -218,6 +244,8 @@ public class ApiClient { */ public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; + // also set the date format for model (de)serialization with Date properties + this.json.setDateFormat((DateFormat) dateFormat.clone()); return this; } @@ -419,13 +447,6 @@ public class ApiClient { public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); - final ClientConfig clientConfig = new ClientConfig(); - clientConfig.register(MultiPartFeature.class); - if (debugging) { - clientConfig.register(LoggingFilter.class); - } - Client client = ClientBuilder.newClient(clientConfig); - WebTarget target = client.target(this.basePath).path(path); if (queryParams != null) { @@ -537,6 +558,15 @@ public class ApiClient { } } + private void buildClient() { + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + if (debugging) { + clientConfig.register(LoggingFilter.class); + } + this.client = ClientBuilder.newClient(clientConfig); + } + private Map> buildResponseHeaders(Response response) { Map> responseHeaders = new HashMap>(); for (Entry> entry: response.getHeaders().entrySet()) { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache index 548c1854e5e..09262af0d63 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache @@ -18,72 +18,76 @@ repositories { if(hasProperty('target') && target == 'android') { - apply plugin: 'com.android.library' - apply plugin: 'com.github.dcendents.android-maven' - - android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' - defaultConfig { - minSdkVersion 14 - targetSdkVersion 22 - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - } - - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.each { output -> - def outputFile = output.outputFile - if (outputFile != null && outputFile.name.endsWith('.aar')) { - def fileName = "${project.name}-${variant.baseName}-${version}.aar" - output.outputFile = new File(outputFile.parent, fileName) - } - } - } - } - - afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDir - task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } - } - - task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' - } - - artifacts { - archives sourcesJar - } + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } } else { - apply plugin: 'java' - apply plugin: 'maven' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - - install { - repositories.mavenInstaller { - pom.artifactId = '{{artifactId}}' - } - } - - task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath - } + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } } ext { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache index e2d0f73d408..c8d2145bc6e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache @@ -162,7 +162,7 @@ 1.5.0 - 2.6 + 2.12 2.4.2 2.3 1.0.0 diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index df36a8b5483..f238c37fb47 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -75,13 +75,11 @@ public class ApiClient { private int statusCode; private Map> responseHeaders; - private String dateFormat; - private DateFormat dateFormatter; + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; private int dateLength; - private String datetimeFormat; - private DateFormat datetimeFormatter; - private InputStream sslCaCert; private boolean verifyingSsl; @@ -95,10 +93,19 @@ public class ApiClient { json = new JSON(this); - // Use ISO 8601 format for date and datetime. - // See https://en.wikipedia.org/wiki/ISO_8601 - setDateFormat("yyyy-MM-dd"); - setDatetimeFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + // Use the system's default time zone when dealing with datetime (mainly formatting). + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; // Set default User-Agent. setUserAgent("Java-Swagger"); @@ -186,32 +193,35 @@ public class ApiClient { return this; } - public String getDateFormat() { + public DateFormat getDateFormat() { return dateFormat; } - public ApiClient setDateFormat(String dateFormat) { + public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; - - this.dateFormatter = new SimpleDateFormat(dateFormat); - // Use UTC as the default time zone. - this.dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - - this.dateLength = this.dateFormatter.format(new Date()).length(); - + this.dateLength = this.dateFormat.format(new Date()).length(); return this; } - public String getDatetimeFormat() { + public DateFormat getDatetimeFormat() { return datetimeFormat; } - public ApiClient setDatetimeFormat(String datetimeFormat) { + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { this.datetimeFormat = datetimeFormat; + return this; + } - this.datetimeFormatter = new SimpleDateFormat(datetimeFormat); - // Note: The datetime formatter uses the system's default time zone. + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; return this; } @@ -225,15 +235,15 @@ public class ApiClient { if (str == null) return null; try { - return dateFormatter.parse(str); + return dateFormat.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } } /** - * Parse the given date-time string into Date object. - * The default datetimeFormat supports these ISO 8601 datetime formats: + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: * 2015-08-16T08:20:05Z * 2015-8-16T8:20:05Z * 2015-08-16T08:20:05+00:00 @@ -253,25 +263,25 @@ public class ApiClient { if (str == null) return null; - if ("yyyy-MM-dd'T'HH:mm:ss.SSSZ".equals(datetimeFormat)) { + if (lenientDatetimeFormat) { /* - * When the default datetime format is used, process the given string + * When lenientDatetimeFormat is enabled, process the given string * to support various formats defined by ISO 8601. */ // normalize time zone - // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 - str = str.replaceAll("[zZ]\\z", "+0000"); - // remove colon: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); - // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+00:00 + str = str.replaceAll("[zZ]\\z", "+00:00"); + // add colon: 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05+00:00 + str = str.replaceAll("([+-]\\d{2})(\\d{2})\\z", "$1:$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+00:00 + str = str.replaceAll("([+-]\\d{2})\\z", "$1:00"); // add milliseconds when missing - // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 - str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + // 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05.000+00:00 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{2}:\\d{2})\\z", "$1.000$2"); } try { - return datetimeFormatter.parse(str); + return datetimeFormat.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } @@ -290,14 +300,14 @@ public class ApiClient { * Format the given Date object into string. */ public String formatDate(Date date) { - return dateFormatter.format(date); + return dateFormat.format(date); } /** * Format the given Date object into string. */ public String formatDatetime(Date date) { - return datetimeFormatter.format(date); + return datetimeFormat.format(date); } /** @@ -369,6 +379,19 @@ public class ApiClient { throw new RuntimeException("No API key authentication configured!"); } + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + /** * Set the User-Agent header's value (by adding to the default header map). */ diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache index 289f9a6df72..9741cb13d10 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache @@ -18,72 +18,76 @@ repositories { if(hasProperty('target') && target == 'android') { - apply plugin: 'com.android.library' - apply plugin: 'com.github.dcendents.android-maven' - - android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' - defaultConfig { - minSdkVersion 14 - targetSdkVersion 22 - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - } - - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.each { output -> - def outputFile = output.outputFile - if (outputFile != null && outputFile.name.endsWith('.aar')) { - def fileName = "${project.name}-${variant.baseName}-${version}.aar" - output.outputFile = new File(outputFile.parent, fileName) - } - } - } - } - - afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDir - task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } - } - - task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' - } - - artifacts { - archives sourcesJar - } + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } } else { - apply plugin: 'java' - apply plugin: 'maven' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - - install { - repositories.mavenInstaller { - pom.artifactId = '{{artifactId}}' - } - } - - task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath - } + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } } dependencies { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache index eaca662c583..183fb5f27ce 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache @@ -28,6 +28,7 @@ import com.squareup.okhttp.OkHttpClient; import {{invokerPackage}}.auth.HttpBasicAuth; import {{invokerPackage}}.auth.ApiKeyAuth; import {{invokerPackage}}.auth.OAuth; +import {{invokerPackage}}.auth.OAuth.AccessTokenListener; import {{invokerPackage}}.auth.OAuthFlow; @@ -44,12 +45,7 @@ public class ApiClient { public ApiClient(String[] authNames) { this(); - okClient = new OkHttpClient(); - adapterBuilder.setClient(new OkClient(okClient)); - for(String authName : authNames) { - if (apiAuthorizations.containsKey(authName)) { - throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); - }{{#hasAuthMethods}} + for(String authName : authNames) { {{#hasAuthMethods}} Interceptor auth; {{#authMethods}}if (authName == "{{name}}") { {{#isBasic}} auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} @@ -58,10 +54,9 @@ public class ApiClient { } else {{/authMethods}}{ throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } - apiAuthorizations.put(authName, auth);{{/hasAuthMethods}}{{^hasAuthMethods}} + addAuthorization(authName, auth);{{/hasAuthMethods}}{{^hasAuthMethods}} throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");{{/hasAuthMethods}} } - addAuthsToOkClient(okClient); } /** @@ -115,9 +110,12 @@ public class ApiClient { .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .create(); + okClient = new OkHttpClient(); + adapterBuilder = new RestAdapter .Builder() .setEndpoint("{{basePath}}") + .setClient(new OkClient(okClient)) .setConverter(new GsonConverterWrapper(gson)); } @@ -224,6 +222,33 @@ public class ApiClient { } } + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener + */ + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; + } + } + } + + /** + * Adds an authorization to be used by the client + * @param authName + * @param authorization + */ + public void addAuthorization(String authName, Interceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + apiAuthorizations.put(authName, authorization); + okClient.interceptors().add(authorization); + } + public Map getApiAuthorizations() { return apiAuthorizations; } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache index e6179d6c690..647ff141329 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache @@ -1,6 +1,7 @@ package {{invokerPackage}}.auth; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; +import static java.net.HttpURLConnection.HTTP_FORBIDDEN; import java.io.IOException; import java.util.Map; @@ -14,6 +15,7 @@ import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import org.apache.oltu.oauth2.common.message.types.GrantType; +import org.apache.oltu.oauth2.common.token.BasicOAuthToken; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; @@ -23,12 +25,18 @@ import com.squareup.okhttp.Response; public class OAuth implements Interceptor { + public interface AccessTokenListener { + public void notify(BasicOAuthToken token); + } + private volatile String accessToken; private OAuthClient oauthClient; private TokenRequestBuilder tokenRequestBuilder; private AuthenticationRequestBuilder authenticationRequestBuilder; + private AccessTokenListener accessTokenListener; + public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) { this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client)); this.tokenRequestBuilder = requestBuilder; @@ -78,47 +86,67 @@ public class OAuth implements Interceptor { updateAccessToken(null); } - // Build the request - Builder rb = request.newBuilder(); - - String requestAccessToken = new String(getAccessToken()); - try { - oAuthRequest = new OAuthBearerClientRequest(request.urlString()) - .setAccessToken(requestAccessToken) - .buildHeaderMessage(); - } catch (OAuthSystemException e) { - throw new IOException(e); + if (getAccessToken() != null) { + // Build the request + Builder rb = request.newBuilder(); + + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.urlString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response != null && (response.code() == HTTP_UNAUTHORIZED | response.code() == HTTP_FORBIDDEN) ) { + if (updateAccessToken(requestAccessToken)) { + return intercept( chain ); + } + } + return response; + } else { + return chain.proceed(chain.request()); } - - for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { - rb.addHeader(header.getKey(), header.getValue()); - } - rb.url( oAuthRequest.getLocationUri()); - - //Execute the request - Response response = chain.proceed(rb.build()); - - // 401 most likely indicates that access token has expired. - // Time to refresh and resend the request - if ( response.code() == HTTP_UNAUTHORIZED ) { - updateAccessToken(requestAccessToken); - return intercept( chain ); - } - return response; } - public synchronized void updateAccessToken(String requestAccessToken) throws IOException { + /* + * Returns true if the access token has been updated + */ + public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { try { - OAuthJSONAccessTokenResponse accessTokenResponse; - accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); - setAccessToken(accessTokenResponse.getAccessToken()); + OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + return getAccessToken().equals(requestAccessToken); + } else { + return false; + } } catch (OAuthSystemException e) { throw new IOException(e); } catch (OAuthProblemException e) { throw new IOException(e); } } + return true; + } + + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; } public synchronized String getAccessToken() { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache index a285745505a..7072c8752f5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache @@ -18,72 +18,76 @@ repositories { if(hasProperty('target') && target == 'android') { - apply plugin: 'com.android.library' - apply plugin: 'com.github.dcendents.android-maven' - - android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' - defaultConfig { - minSdkVersion 14 - targetSdkVersion 22 - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - } - - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.each { output -> - def outputFile = output.outputFile - if (outputFile != null && outputFile.name.endsWith('.aar')) { - def fileName = "${project.name}-${variant.baseName}-${version}.aar" - output.outputFile = new File(outputFile.parent, fileName) - } - } - } - } - - afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDir - task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } - } - - task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' - } - - artifacts { - archives sourcesJar - } + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } } else { - apply plugin: 'java' - apply plugin: 'maven' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - - install { - repositories.mavenInstaller { - pom.artifactId = '{{artifactId}}' - } - } - - task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath - } + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } } ext { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache new file mode 100644 index 00000000000..56e83f7d915 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache @@ -0,0 +1,343 @@ +package {{invokerPackage}}; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; + +import retrofit.Converter; +import retrofit.Retrofit; +import retrofit.GsonConverterFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.ResponseBody; + +import {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.auth.OAuth; +import {{invokerPackage}}.auth.OAuth.AccessTokenListener; +import {{invokerPackage}}.auth.OAuthFlow; + + +public class ApiClient { + + private Map apiAuthorizations; + private OkHttpClient okClient; + private Retrofit.Builder adapterBuilder; + + public ApiClient() { + apiAuthorizations = new LinkedHashMap(); + createDefaultAdapter(); + } + + public ApiClient(String[] authNames) { + this(); + for(String authName : authNames) { {{#hasAuthMethods}} + Interceptor auth; + {{#authMethods}}if (authName == "{{name}}") { {{#isBasic}} + auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} + auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} + auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}} + } else {{/authMethods}}{ + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + addAuthorization(authName, auth);{{/hasAuthMethods}}{{^hasAuthMethods}} + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");{{/hasAuthMethods}} + } + } + + /** + * Basic constructor for single auth name + * @param authName + */ + public ApiClient(String authName) { + this(new String[]{authName}); + } + + /** + * Helper constructor for single api key + * @param authName + * @param apiKey + */ + public ApiClient(String authName, String apiKey) { + this(authName); + this.setApiKey(apiKey); + } + + /** + * Helper constructor for single basic auth or password oauth2 + * @param authName + * @param username + * @param password + */ + public ApiClient(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); + } + + /** + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password + */ + public ApiClient(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); + } + + public void createDefaultAdapter() { + Gson gson = new GsonBuilder() + .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .create(); + + okClient = new OkHttpClient(); + + String baseUrl = "{{basePath}}"; + if(!baseUrl.endsWith("/")) + baseUrl = baseUrl + "/"; + + adapterBuilder = new Retrofit + .Builder() + .baseUrl(baseUrl) + .client(okClient) + .addConverterFactory(GsonCustomConverterFactory.create(gson)); + } + + public S createService(Class serviceClass) { + return adapterBuilder.build().create(serviceClass); + + } + + /** + * Helper method to configure the first api key found + * @param apiKey + */ + private void setApiKey(String apiKey) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; + keyAuth.setApiKey(apiKey); + return; + } + } + } + + /** + * Helper method to configure the username/password for basic auth or password oauth + * @param username + * @param password + */ + private void setCredentials(String username, String password) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + return; + } + } + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public TokenRequestBuilder getTokenEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public AuthenticationRequestBuilder getAuthorizationEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getAuthenticationRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken + */ + public void setAccessToken(String accessToken) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.setAccessToken(accessToken); + return; + } + } + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId + * @param clientSecret + * @param redirectURI + */ + public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; + } + } + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener + */ + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; + } + } + } + + /** + * Adds an authorization to be used by the client + * @param authName + * @param authorization + */ + public void addAuthorization(String authName, Interceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + apiAuthorizations.put(authName, authorization); + okClient.interceptors().add(authorization); + } + + public Map getApiAuthorizations() { + return apiAuthorizations; + } + + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; + } + + public Retrofit.Builder getAdapterBuilder() { + return adapterBuilder; + } + + public void setAdapterBuilder(Retrofit.Builder adapterBuilder) { + this.adapterBuilder = adapterBuilder; + } + + public OkHttpClient getOkClient() { + return okClient; + } + + public void addAuthsToOkClient(OkHttpClient okClient) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + okClient.interceptors().add(apiAuthorization); + } + } + + /** + * Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the Retrofit + * @param okClient + */ + public void configureFromOkclient(OkHttpClient okClient) { + OkHttpClient clone = okClient.clone(); + addAuthsToOkClient(clone); + adapterBuilder.client(clone); + } +} + +/** + * 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 GsonResponseBodyConverterToString implements Converter { + private final Gson gson; + private final Type type; + + GsonResponseBodyConverterToString(Gson gson, Type type) { + this.gson = gson; + this.type = type; + } + + @Override public T convert(ResponseBody value) throws IOException { + String returned = value.string(); + try { + return gson.fromJson(returned, type); + } + catch (JsonParseException e) { + return (T) returned; + } + } +} + +class GsonCustomConverterFactory extends Converter.Factory +{ + public static GsonCustomConverterFactory create(Gson gson) { + return new GsonCustomConverterFactory(gson); + } + + private final Gson gson; + private final GsonConverterFactory gsonConverterFactory; + + private GsonCustomConverterFactory(Gson gson) { + if (gson == null) throw new NullPointerException("gson == null"); + this.gson = gson; + this.gsonConverterFactory = GsonConverterFactory.create(gson); + } + + @Override + public Converter fromResponseBody(Type type, Annotation[] annotations) { + if(type.equals(String.class)) + return new GsonResponseBodyConverterToString(gson, type); + else + return gsonConverterFactory.fromResponseBody(type, annotations); + } + + @Override + public Converter toRequestBody(Type type, Annotation[] annotations) { + return gsonConverterFactory.toRequestBody(type, annotations); + } +} + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/CollectionFormats.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/CollectionFormats.mustache new file mode 100644 index 00000000000..a549ea59d1c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/CollectionFormats.mustache @@ -0,0 +1,95 @@ +package {{invokerPackage}}; + +import java.util.Arrays; +import java.util.List; + +public class CollectionFormats { + + public static class CSVParams { + + protected List params; + + public CSVParams() { + } + + public CSVParams(List params) { + this.params = params; + } + + public CSVParams(String... params) { + this.params = Arrays.asList(params); + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), ","); + } + + } + + public static class SSVParams extends CSVParams { + + public SSVParams() { + } + + public SSVParams(List params) { + super(params); + } + + public SSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), " "); + } + } + + public static class TSVParams extends CSVParams { + + public TSVParams() { + } + + public TSVParams(List params) { + super(params); + } + + public TSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join( params.toArray(new String[0]), "\t"); + } + } + + public static class PIPESParams extends CSVParams { + + public PIPESParams() { + } + + public PIPESParams(List params) { + super(params); + } + + public PIPESParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), "|"); + } + } + +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache new file mode 100644 index 00000000000..d0205c3d0b1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -0,0 +1,34 @@ +package {{package}}; + +import {{invokerPackage}}.CollectionFormats.*; + +import retrofit.Call; +import retrofit.http.*; +import com.squareup.okhttp.RequestBody; + +{{#imports}}import {{import}}; +{{/imports}} + +{{^fullJavaUtil}} +import java.util.*; +{{/fullJavaUtil}} + +{{#operations}} +public interface {{classname}} { + {{#operation}} + /** + * {{summary}} + * {{notes}} +{{#allParams}} * @param {{paramName}} {{description}} +{{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> + */ + {{#formParams}}{{#-first}} + {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + @{{httpMethod}}("{{path}}") + Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{nickname}}({{^allParams}});{{/allParams}} + {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} + );{{/hasMore}}{{/allParams}} + + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache new file mode 100644 index 00000000000..fec45262e93 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/ApiKeyAuth.mustache @@ -0,0 +1,68 @@ +package {{invokerPackage}}.auth; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class ApiKeyAuth implements Interceptor { + private final String location; + private final String paramName; + + private String apiKey; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + @Override + public Response intercept(Chain chain) throws IOException { + String paramValue; + Request request = chain.request(); + + if (location == "query") { + String newQuery = request.uri().getQuery(); + paramValue = paramName + "=" + apiKey; + if (newQuery == null) { + newQuery = paramValue; + } else { + newQuery += "&" + paramValue; + } + + URI newUri; + try { + newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(), + request.uri().getPath(), newQuery, request.uri().getFragment()); + } catch (URISyntaxException e) { + throw new IOException(e); + } + + request = request.newBuilder().url(newUri.toURL()).build(); + } else if (location == "header") { + request = request.newBuilder() + .addHeader(paramName, apiKey) + .build(); + } + return chain.proceed(request); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/HttpBasicAuth.mustache new file mode 100644 index 00000000000..394592f64d9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/HttpBasicAuth.mustache @@ -0,0 +1,49 @@ +package {{invokerPackage}}.auth; + +import java.io.IOException; + +import com.squareup.okhttp.Credentials; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class HttpBasicAuth implements Interceptor { + + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setCredentials(String username, String password) { + this.username = username; + this.password = password; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") == null) { + String credentials = Credentials.basic(username, password); + request = request.newBuilder() + .addHeader("Authorization", credentials) + .build(); + } + return chain.proceed(request); + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache new file mode 100644 index 00000000000..68ee918601e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache @@ -0,0 +1,161 @@ +package {{invokerPackage}}.auth; + +import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; + +import java.io.IOException; +import java.util.Map; + +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; +import org.apache.oltu.oauth2.common.token.BasicOAuthToken; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Request.Builder; +import com.squareup.okhttp.Response; + +public class OAuth implements Interceptor { + + public interface AccessTokenListener { + public void notify(BasicOAuthToken token); + } + + private volatile String accessToken; + private OAuthClient oauthClient; + + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + + private AccessTokenListener accessTokenListener; + + public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) { + this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client)); + this.tokenRequestBuilder = requestBuilder; + } + + public OAuth(TokenRequestBuilder requestBuilder ) { + this(new OkHttpClient(), requestBuilder); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case accessCode: + case implicit: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) + throws IOException { + + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") != null) { + return chain.proceed(request); + } + + // If first time, get the token + OAuthClientRequest oAuthRequest; + if (getAccessToken() == null) { + updateAccessToken(null); + } + + // Build the request + Builder rb = request.newBuilder(); + + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.urlString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response.code() == HTTP_UNAUTHORIZED ) { + updateAccessToken(requestAccessToken); + return intercept( chain ); + } + return response; + } + + public synchronized void updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + try { + OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); + setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + } catch (OAuthSystemException e) { + throw new IOException(e); + } catch (OAuthProblemException e) { + throw new IOException(e); + } + } + } + + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { + return authenticationRequestBuilder; + } + + public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { + this.authenticationRequestBuilder = authenticationRequestBuilder; + } + +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuthOkHttpClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuthOkHttpClient.mustache new file mode 100644 index 00000000000..ea195f7df04 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuthOkHttpClient.mustache @@ -0,0 +1,69 @@ +package {{invokerPackage}}.auth; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; + + +public class OAuthOkHttpClient implements HttpClient { + + private OkHttpClient client; + + public OAuthOkHttpClient() { + this.client = new OkHttpClient(); + } + + public OAuthOkHttpClient(OkHttpClient client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + MediaType mediaType = MediaType.parse("application/json"); + Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); + + if(headers != null) { + for (Entry entry : headers.entrySet()) { + if (entry.getKey().equalsIgnoreCase("Content-Type")) { + mediaType = MediaType.parse(entry.getValue()); + } else { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; + requestBuilder.method(requestMethod, body); + + try { + Response response = client.newCall(requestBuilder.build()).execute(); + return OAuthClientResponseFactory.createCustomResponse( + response.body().string(), + response.body().contentType().toString(), + response.code(), + responseClass); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + } + + public void shutdown() { + // Nothing to do here + } + +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache new file mode 100644 index 00000000000..f8788583db5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}@Body {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache new file mode 100644 index 00000000000..b1efe3911a8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache @@ -0,0 +1,106 @@ +group = '{{groupId}}' +version = '{{artifactVersion}}' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + okhttp_version = "2.5.0" + oltu_version = "1.0.0" + retrofit_version = "2.0.0-beta2" + gson_version = "2.4" + swagger_annotations_version = "1.5.0" + junit_version = "4.12" +} + +dependencies { + compile "com.squareup.okhttp:okhttp:$okhttp_version" + compile "com.squareup.retrofit:retrofit:$retrofit_version" + compile 'com.google.code.gson:gson:$gson_version' + compile 'com.squareup.retrofit:converter-gson:$retrofit_version' + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + testCompile "junit:junit:$junit_version" +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache new file mode 100644 index 00000000000..8d9208978b5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}\"; filename=\"{{baseName}}\"") RequestBody {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache new file mode 100644 index 00000000000..29206e1546b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/model.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/model.mustache new file mode 100644 index 00000000000..0987aa68f34 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/model.mustache @@ -0,0 +1,58 @@ +package {{package}}; + +import {{invokerPackage}}.StringUtil; +{{#imports}}import {{import}}; +{{/imports}} + +import com.google.gson.annotations.SerializedName; + +{{#serializableModel}} +import java.io.Serializable;{{/serializableModel}} + +import io.swagger.annotations.*; + +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@ApiModel(description = "{{{description}}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { + {{#vars}}{{#isEnum}} + +{{>libraries/okhttp-gson/enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} + +{{>libraries/okhttp-gson/enumClass}}{{/items}}{{/items.isEnum}} + @SerializedName("{{baseName}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; + {{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache new file mode 100644 index 00000000000..8a8bdc74c88 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache new file mode 100644 index 00000000000..a155d04ef88 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -0,0 +1,158 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + com.squareup.retrofit + retrofit + ${retrofit-version} + + + com.squareup.retrofit + converter-gson + ${retrofit-version} + + + com.google.code.gson + gson + ${gson-version} + + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} + + + com.squareup.okhttp + okhttp + ${okhttp-version} + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.0.0-beta2 + 2.5.0 + 2.4 + 1.0.0 + 1.0.0 + 4.12 + + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache new file mode 100644 index 00000000000..3c5b1bb7e69 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/manifest.mustache b/modules/swagger-codegen/src/main/resources/Java/manifest.mustache new file mode 100644 index 00000000000..f44bd07d0a0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/manifest.mustache @@ -0,0 +1,3 @@ + + + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index e919fa7ce71..ea9f2518b01 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -22,14 +22,13 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.*; -@Path("{{basePathWithoutHost}}/{{baseName}}") +@Path("/{{baseName}}") {{#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") +@io.swagger.annotations.Api(description = "the {{baseName}} API") {{>generatedAnnotation}} {{#operations}} public class {{classname}} { - private final {{classname}}Service delegate = {{classname}}ServiceFactory.get{{classname}}(); {{#operation}} @@ -43,7 +42,7 @@ public class {{classname}} { {{/hasMore}}{{/scopes}} }{{/isOAuth}}){{#hasMore}}, {{/hasMore}}{{/authMethods}} - }{{/hasAuthMethods}}) + }{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) @io.swagger.annotations.ApiResponses(value = { {{#responses}} @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}}, {{/hasMore}}{{/responses}} }) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache index ae6f6d4d692..8cd666106f9 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache @@ -34,14 +34,14 @@ swagger.api.basepath - http://localhost:8080 + {{basePath}} 2 jersey - /* + {{contextPath}}/* ApiOriginFilter diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/bodyParams.mustache index 86546afb9ca..f1137ba7073 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/bodyParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestBody {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 4cf785abbd8..5c607488d9b 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 @@ -3,6 +3,7 @@ io.swagger.codegen.languages.AsyncScalaClientCodegen io.swagger.codegen.languages.CSharpClientCodegen io.swagger.codegen.languages.DartClientCodegen io.swagger.codegen.languages.FlashClientCodegen +io.swagger.codegen.languages.FlaskConnexionCodegen io.swagger.codegen.languages.JavaClientCodegen io.swagger.codegen.languages.JaxRSServerCodegen io.swagger.codegen.languages.JavaInflectorServerCodegen @@ -28,3 +29,4 @@ io.swagger.codegen.languages.TypeScriptAngularClientCodegen io.swagger.codegen.languages.TypeScriptNodeClientCodegen io.swagger.codegen.languages.AkkaScalaClientCodegen io.swagger.codegen.languages.CsharpDotNet2ClientCodegen +io.swagger.codegen.languages.ClojureClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index 9681634a765..9efea198f36 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -12,26 +12,38 @@ namespace {{package}} { */ {{/description}} export class {{classname}} { - private basePath = '{{basePath}}'; + protected basePath = '{{basePath}}'; + public defaultHeaders : any = {}; static $inject: string[] = ['$http', '$httpParamSerializer']; - constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (d: any) => any) { + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { if (basePath) { this.basePath = basePath; } } + + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + {{#operation}} - + /** + * {{summary}} + * {{notes}} + {{#allParams}}* @param {{paramName}} {{description}} + {{/allParams}}*/ public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { - let path = this.basePath + '{{path}}'; + const path = this.basePath + '{{path}}'{{#pathParams}} + .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; -{{#pathParams}} - path = path.replace('{' + '{{baseName}}' + '}', String({{paramName}})); - -{{/pathParams}} let queryParameters: any = {}; - let headerParams: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); {{#hasFormParams}} let formParams: any = {}; @@ -42,7 +54,6 @@ namespace {{package}} { if (!{{paramName}}) { throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); } - {{/required}} {{/allParams}} {{#queryParams}} @@ -61,7 +72,7 @@ namespace {{package}} { {{/hasFormParams}} {{#formParams}} formParams['{{baseName}}'] = {{paramName}}; - + {{/formParams}} let httpRequestParams: any = { method: '{{httpMethod}}', @@ -76,11 +87,7 @@ namespace {{package}} { }; if (extraHttpRequestParams) { - for (let k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache index 5b57ed4dc94..f4cfe923baa 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache @@ -18,7 +18,7 @@ namespace {{package}} { * {{{description}}} */ {{/description}} - {{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + {{name}}{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} } @@ -27,7 +27,7 @@ namespace {{package}} { {{#vars}} {{#isEnum}} - export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} + export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} {{.}} = '{{.}}',{{/values}}{{/allowableValues}} } {{/isEnum}} @@ -36,4 +36,4 @@ namespace {{package}} { {{/hasEnums}} {{/model}} {{/models}} -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index 4d03ae0f424..c1f311fec19 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -95,7 +95,11 @@ class VoidAuth implements Authentication { */ {{/description}} export class {{classname}} { - private basePath = '{{basePath}}'; + protected basePath = '{{basePath}}'; + protected defaultHeaders : any = {}; + + + public authentications = { 'default': new VoidAuth(), {{#authMethods}} @@ -154,17 +158,25 @@ export class {{classname}} { {{#isOAuth}} {{/isOAuth}} {{/authMethods}} + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } {{#operation}} - - public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { - let path = this.url + this.basePath + '{{path}}'; - -{{#pathParams}} - path = path.replace('{' + '{{baseName}}' + '}', String({{paramName}})); - -{{/pathParams}} + /** + * {{summary}} + * {{notes}} + {{#allParams}}* @param {{paramName}} {{description}} + {{/allParams}}*/ + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }> { + const path = this.url + this.basePath + '{{path}}'{{#pathParams}} + .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; let queryParameters: any = {}; - let headerParams: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); let formParams: any = {}; {{#allParams}}{{#required}} @@ -194,7 +206,7 @@ export class {{classname}} { {{/isFile}} {{/formParams}} - let deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); + let deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}}{{^returnType}}body?: any; {{/returnType}} }>(); let requestOptions: request.Options = { method: '{{httpMethod}}', diff --git a/modules/swagger-codegen/src/main/resources/clojure/api.mustache b/modules/swagger-codegen/src/main/resources/clojure/api.mustache new file mode 100644 index 00000000000..a4425280f1b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/clojure/api.mustache @@ -0,0 +1,19 @@ +{{=< >=}}(ns . + (:require [.core :refer [call-api check-required-params]]) + (:import (java.io File))) +<#operations><#operation> +(defn + "<&summary><#notes> + <¬es>"<#hasOptionalParams> + ([<#allParams><#required><#isFile>^File ] (<#allParams><#required> nil)) + <#hasOptionalParams>([<#allParams><#required><#isFile>^File <#hasOptionalParams>{:keys [<#allParams><^required><#isFile>^File ]}]<#hasRequiredParams> + <#hasOptionalParams> (check-required-params<#allParams><#required> ) + <#hasOptionalParams> (call-api "" : + <#hasOptionalParams> {:path-params {<#pathParams>"" } + <#hasOptionalParams> :header-params {<#headerParams>"" } + <#hasOptionalParams> :query-params {<#queryParams>"" } + <#hasOptionalParams> :form-params {<#formParams>"" }<#bodyParam> + <#hasOptionalParams> :body-param + <#hasOptionalParams> :content-types [<#consumes>""<#hasMore> ] + <#hasOptionalParams> :accepts [<#produces>""<#hasMore> ]}))<#hasOptionalParams>) + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/clojure/core.mustache b/modules/swagger-codegen/src/main/resources/clojure/core.mustache new file mode 100644 index 00000000000..32aa8a6bc0d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/clojure/core.mustache @@ -0,0 +1,178 @@ +(ns {{{baseNamespace}}}.core + (:require [cheshire.core :refer [generate-string parse-string]] + [clojure.string :as str] + [clj-http.client :as client]) + (:import (com.fasterxml.jackson.core JsonParseException) + (java.io File) + (java.util Date TimeZone) + (java.text SimpleDateFormat))) + +(def default-api-context + "Default API context." + {:base-url "http://petstore.swagger.io/v2" + :date-format "yyyy-MM-dd" + :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" + :debug false}) + +(def ^:dynamic *api-context* + "Dynamic API context to be applied in API calls." + default-api-context) + +(defmacro with-api-context + "A helper macro to wrap *api-context* with default values." + [context & body] + `(binding [*api-context* (merge *api-context* ~context)] + ~@body)) + +(defmacro check-required-params + "Throw exception if the given parameter value is nil." + [& params] + (->> params + (map (fn [p] + `(if (nil? ~p) + (throw (IllegalArgumentException. ~(str "The parameter \"" p "\" is required")))))) + (list* 'do))) + +(defn- make-date-format + ([format-str] (make-date-format format-str nil)) + ([format-str time-zone] + (let [date-format (SimpleDateFormat. format-str)] + (when time-zone + (.setTimeZone date-format (TimeZone/getTimeZone time-zone))) + date-format))) + +(defn format-date + "Format the given Date object with the :date-format defined in *api-options*. + NOTE: The UTC time zone is used." + [^Date date] + (let [{:keys [date-format]} *api-context*] + (-> (make-date-format date-format "UTC") + (.format date)))) + +(defn parse-date + "Parse the given string to a Date object with the :date-format defined in *api-options*. + NOTE: The UTC time zone is used." + [^String s] + (let [{:keys [date-format]} *api-context*] + (-> (make-date-format date-format "UTC") + (.parse s)))) + +(defn format-datetime + "Format the given Date object with the :datetime-format defined in *api-options*. + NOTE: The system's default time zone is used when not provided." + ([^Date date] (format-datetime date nil)) + ([^Date date ^String time-zone] + (let [{:keys [datetime-format]} *api-context*] + (-> (make-date-format datetime-format time-zone) + (.format date))))) + +(defn parse-datetime + "Parse the given string to a Date object with the :datetime-format defined in *api-options*. + NOTE: The system's default time zone is used when not provided." + ([^String s] (parse-datetime s nil)) + ([^String s ^String time-zone] + (let [{:keys [datetime-format]} *api-context*] + (-> (make-date-format datetime-format time-zone) + (.parse s))))) + +(defn param-to-str [param] + "Format the given parameter value to string." + (cond + (instance? Date param) (format-datetime param) + (sequential? param) (str/join "," param) + :else (str param))) + +(defn make-url + "Make full URL by adding base URL and filling path parameters." + [path path-params] + (let [path (reduce (fn [p [k v]] + (str/replace p (re-pattern (str "\\{" k "\\}")) (param-to-str v))) + path + path-params)] + (str (:base-url *api-context*) path))) + +(defn normalize-param + "Normalize parameter value, handling three cases: + for sequential value, normalize each elements of it; + for File value, do nothing with it; + otherwise, call `param-to-string`." + [param] + (cond + (sequential? param) (map normalize-param param) + (instance? File param) param + :else (param-to-str param))) + +(defn normalize-params + "Normalize parameters values: remove nils, format to string with `param-to-str`." + [params] + (->> params + (remove (comp nil? second)) + (map (fn [[k v]] [k (normalize-param v)])) + (into {}))) + +(defn json-mime? [mime] + "Check if the given MIME is a standard JSON MIME or :json." + (if mime + (or (= :json mime) + (re-matches #"application/json(;.*)?" (name mime))))) + +(defn json-preferred-mime [mimes] + "Choose a MIME from the given MIMEs with JSON preferred, + i.e. return JSON if included, otherwise return the first one." + (-> (filter json-mime? mimes) + first + (or (first mimes)))) + +(defn serialize + "Serialize the given data according to content-type. + Only JSON is supported for now." + [data content-type] + (if (json-mime? content-type) + (generate-string data {:date-format (:datetime-format *api-context*)}) + (throw (IllegalArgumentException. (str "Content type \"" content-type "\" is not support for serialization"))))) + +(defn deserialize + "Deserialize the given HTTP response according to the Content-Type header." + [{:keys [body] {:keys [content-type]} :headers}] + (cond + (json-mime? content-type) + (try + (parse-string body true) + (catch JsonParseException e + ;; return the body string directly on JSON parsing error + body)) + ;; for non-JSON response, return the body string directly + :else body)) + +(defn form-params-to-multipart + "Convert the given form parameters map into a vector as clj-http's :multipart option." + [form-params] + (->> form-params + (map (fn [[k v]] (array-map :name k :content v))) + vec)) + +(defn call-api + "Call an API by making HTTP request and return its response." + [path method {:keys [path-params query-params header-params form-params body-param content-types accepts]}] + (let [{:keys [debug]} *api-context* + url (make-url path path-params) + content-type (or (json-preferred-mime content-types) + (and body-param :json)) + accept (or (json-preferred-mime accepts) :json) + multipart? (= "multipart/form-data" content-type) + opts (cond-> {:url url :method method} + accept (assoc :accept accept) + (seq query-params) (assoc :query-params (normalize-params query-params)) + (seq header-params) (assoc :header-params (normalize-params header-params)) + (and content-type (not multipart?)) (assoc :content-type content-type) + multipart? (assoc :multipart (-> form-params + normalize-params + form-params-to-multipart)) + (and (not multipart?) (seq form-params)) (assoc :form-params (normalize-params form-params)) + body-param (assoc :body (serialize body-param content-type)) + debug (assoc :debug true :debug-body true)) + resp (client/request opts)] + (when debug + (println "Response:") + (println resp)) + (deserialize resp))) diff --git a/modules/swagger-codegen/src/main/resources/clojure/project.mustache b/modules/swagger-codegen/src/main/resources/clojure/project.mustache new file mode 100644 index 00000000000..c403c9c43c6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/clojure/project.mustache @@ -0,0 +1,8 @@ +{{=< >=}}(defproject <&projectName> "<&projectVersion>" + :description "<&projectDescription>"<#projectUrl> + :url "<&projectUrl>"<#licenseName> + :license {:name "<&licenseName>"<#licenseUrl> + :url "<&licenseUrl>"} + :dependencies [[org.clojure/clojure "1.7.0"] + [clj-http "2.0.0"] + [cheshire "5.5.0"]]) diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index f6dd2933331..87d55ab3f6e 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -10,7 +10,6 @@ using System.Net; using System.Text; using Newtonsoft.Json; using RestSharp; -using RestSharp.Extensions; namespace {{packageName}}.Client { @@ -171,7 +170,7 @@ namespace {{packageName}}.Client /// Escaped string. public string EscapeString(string str) { - return RestSharp.Extensions.StringExtensions.UrlEncode(str); + return UrlEncode(str); } /// @@ -183,9 +182,9 @@ namespace {{packageName}}.Client public FileParameter ParameterToFile(string name, Stream stream) { if (stream is FileStream) - return FileParameter.Create(name, stream.ReadAsBytes(), Path.GetFileName(((FileStream)stream).Name)); + return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name)); else - return FileParameter.Create(name, stream.ReadAsBytes(), "no_file_name_provided"); + return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided"); } /// @@ -319,8 +318,7 @@ namespace {{packageName}}.Client { {{#authMethods}} case "{{name}}": - {{#isApiKey}}{{#isKeyInHeader}}headerParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}queryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}headerParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password);{{/isBasic}} - {{#isOAuth}}//TODO support oauth{{/isOAuth}} + {{#isApiKey}}{{#isKeyInHeader}}headerParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}queryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}headerParams["Authorization"] = "Basic " + Base64Encode(Configuration.Username + ":" + Configuration.Password);{{/isBasic}}{{#isOAuth}}headerParams["Authorization"] = "Bearer " + Configuration.AccessToken;{{/isOAuth}} break; {{/authMethods}} default: @@ -366,6 +364,62 @@ namespace {{packageName}}.Client public static dynamic ConvertType(dynamic source, Type dest) { return Convert.ChangeType(source, dest); } + + /// + /// Convert stream to byte array + /// Credit/Ref: http://stackoverflow.com/a/221941/677735 + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream input) + { + byte[] buffer = new byte[16*1024]; + using (MemoryStream ms = new MemoryStream()) + { + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) > 0) + { + ms.Write(buffer, 0, read); + } + return ms.ToArray(); + } + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// String to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + } } diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 67b07069e2f..79b20c6062c 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -37,6 +37,12 @@ namespace {{packageName}}.Client /// The password. public static String Password { get; set; } + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// The access token. + public static String AccessToken { get; set; } + /// /// Gets or sets the API key based on the authentication name. /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 89594091dfb..6708fa1e16d 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -102,7 +102,7 @@ namespace {{packageName}}.Api if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); {{/required}}{{/allParams}} - var path = "{{path}}"; + var path_ = "{{path}}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -137,7 +137,7 @@ namespace {{packageName}}.Api String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); @@ -158,7 +158,7 @@ namespace {{packageName}}.Api if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); {{/required}}{{/allParams}} - var path = "{{path}}"; + var path_ = "{{path}}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -193,7 +193,7 @@ namespace {{packageName}}.Api String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index 99da4f8302a..d40ece4cc02 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache new file mode 100644 index 00000000000..ed64b667558 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache @@ -0,0 +1,27 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled flask server. + +This example uses the [connexion](https://github.com/zalando/connexion) library on top of Flask. + +To run the server, please execute the following: + +``` +python3 app.py +``` + +and open your browser to here: + +``` +http://localhost:{{serverPort}}/ui +``` + +Your swagger definition lives here: + +``` +http://localhost:{{serverPort}}{{basePathWithoutHost}}/swagger.json +``` + diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache new file mode 100644 index 00000000000..14af64be6f9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 + +import connexion + +if __name__ == '__main__': + app = connexion.App(__name__, {{serverPort}}, + specification_dir='./swagger/') + app.add_api('swagger.yaml', arguments={'title': '{{appDescription}}'}) + app.run() diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache new file mode 100644 index 00000000000..cb8544aa1b4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache @@ -0,0 +1,11 @@ +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + +def {{vendorExtensions.x-operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> str: + return 'do some magic!' +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/swagger.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/swagger.mustache new file mode 100644 index 00000000000..51560926bba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/swagger.mustache @@ -0,0 +1 @@ +{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index 9473309ff83..83cd24e72d0 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -94,17 +94,15 @@ {{/hasFormParams}} - + {{#hasExamples}} {{#examples}} diff --git a/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache b/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache index 85d1f3211a1..0f0c35bc0ee 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache @@ -9,17 +9,7 @@ var {{classname}} = require('./{{classname}}Service'); {{#operation}} module.exports.{{nickname}} = function {{nickname}} (req, res, next) { - {{#allParams}}var {{paramName}} = req.swagger.params['{{baseName}}'].value; - {{/allParams}} - - var result = {{classname}}.{{nickname}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + {{classname}}.{{nickname}}(req.swagger.params, res, next); }; {{/operation}} {{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/nodejs/index.mustache b/modules/swagger-codegen/src/main/resources/nodejs/index.mustache index 419b3fb5e63..397661d4d52 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/index.mustache @@ -3,7 +3,8 @@ var app = require('connect')(); var http = require('http'); var swaggerTools = require('swagger-tools'); - +var jsyaml = require('js-yaml'); +var fs = require('fs'); var serverPort = {{serverPort}}; // swaggerRouter configuration @@ -14,7 +15,8 @@ var options = { }; // The Swagger document (require it, build it programmatically, fetch it from a URL, ...) -var swaggerDoc = require('./api/swagger.json'); +var spec = fs.readFileSync('./api/swagger.yaml', 'utf8'); +var swaggerDoc = jsyaml.safeLoad(spec); // Initialize the Swagger middleware swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) { diff --git a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache index 89db4c0b91e..86aa21af635 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache @@ -10,6 +10,7 @@ "private": true, "dependencies": { "connect": "^3.2.0", - "swagger-tools": "0.8.*" + "js-yaml": "^3.3.0", + "swagger-tools": "0.9.*" } } diff --git a/modules/swagger-codegen/src/main/resources/nodejs/service.mustache b/modules/swagger-codegen/src/main/resources/nodejs/service.mustache index d7c2ade5079..5073d249275 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/service.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/service.mustache @@ -2,17 +2,27 @@ {{#operations}} {{#operation}} -exports.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { +exports.{{nickname}} = function(args, res, next) { + /** + * parameters expected in the args: + {{#allParams}}* {{paramName}} ({{dataType}}) + {{/allParams}}**/ - var examples = {}; +var examples = {}; {{#examples}} examples['{{contentType}}'] = {{{example}}}; {{/examples}} {{#returnType}} - if(Object.keys(examples).length > 0) - return examples[Object.keys(examples)[0]]; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } {{/returnType}} + {{^returnType}}res.end();{{/returnType}} } {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache index 1d0f7d78162..51560926bba 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache @@ -1,43 +1 @@ -{ - "swagger": "2.0", - "info": { - "title": "{{appName}}", - "description": "{{{appDescription}}}", - "version": "{{apiVersion}}" - }, -{{#apiInfo}} - "produces": ["application/json"], - "host": "localhost:{{serverPort}}", - "basePath": "{{contextPath}}", - "paths": { -{{#apis}} -{{#operations}} - {{#operationsByPath}} - "{{{path}}}": { - {{#operation}} - "{{httpMethod}}": { - "summary": "{{summary}}", - "description":"{{notes}}", - "x-swagger-router-controller": "{{classname}}", - "tags": ["{{baseName}}"], - "operationId": "{{operationId}}",{{#hasParams}} - "parameters": [ - {{#allParams}}{{{jsonSchema}}}{{#hasMore}},{{/hasMore}} - {{/allParams}} - ],{{/hasParams}} - "responses": { - {{#responses}}"{{code}}": {{{jsonSchema}}} - {{#hasMore}},{{/hasMore}} - {{/responses}} - } - } {{#hasMore}},{{/hasMore}} - {{/operation}} - } {{#hasMore}},{{/hasMore}} - {{/operationsByPath}} -{{/operations}} -{{/apis}} -{{/apiInfo}} - }, "definitions": { - {{#models}}{{#model}}"{{classVarName}}": {{{modelJson}}}{{#hasMoreModels}},{{/hasMoreModels}}{{/model}}{{/models}} - } -} +{{{swagger-yaml}}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache index fa88dbd0333..bf1220912d2 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache @@ -20,7 +20,9 @@ use Module::Runtime qw(use_module); use WWW::{{moduleName}}::Configuration; -sub new +use base 'Class::Singleton'; + +sub _new_instance { my $class = shift; my (%args) = ( @@ -32,6 +34,8 @@ sub new return bless \%args, $class; } +sub _cfg {'WWW::{{moduleName}}::Configuration'} + # Set the user agent of the API client # # @param string $user_agent The user agent of the API client @@ -118,10 +122,12 @@ sub call_api { $self->{ua}->timeout($self->{http_timeout} || $WWW::{{moduleName}}::Configuration::http_timeout); $self->{ua}->agent($self->{http_user_agent} || $WWW::{{moduleName}}::Configuration::http_user_agent); + $log->debugf("REQUEST: %s", $_request->as_string); my $_response = $self->{ua}->request($_request); + $log->debugf("RESPONSE: %s", $_response->as_string); unless ($_response->is_success) { - croak("API Exception(".$_response->code."): ".$_response->message); + croak(sprintf "API Exception(%s): %s\n%s", $_response->code, $_response->message, $_response->content); } return $_response->content; @@ -146,8 +152,8 @@ sub to_path_value { # @return string the serialized object sub to_query_value { my ($self, $object) = @_; - if (is_array($object)) { - return implode(',', $object); + if (ref($object) eq 'ARRAY') { + return join(',', @$object); } else { return $self->to_string($object); } @@ -286,23 +292,26 @@ sub select_header_content_type # @return string API key with the prefix sub get_api_key_with_prefix { - my ($self, $api_key) = @_; - if ($WWW::{{moduleName}}::Configuration::api_key_prefix->{$api_key}) { - return $WWW::{{moduleName}}::Configuration::api_key_prefix->{$api_key}." ".$WWW::{{moduleName}}::Configuration::api_key->{$api_key}; - } else { - return $WWW::{{moduleName}}::Configuration::api_key->{$api_key}; - } -} + my ($self, $key_name) = @_; -# update hearder and query param based on authentication setting + my $api_key = $WWW::{{moduleName}}::Configuration::api_key->{$key_name}; + + return unless $api_key; + + my $prefix = $WWW::{{moduleName}}::Configuration::api_key_prefix->{$key_name}; + return $prefix ? "$prefix $api_key" : $api_key; +} + +# update header and query param based on authentication setting # # @param array $headerParams header parameters (by ref) # @param array $queryParams query parameters (by ref) # @param array $authSettings array of authentication scheme (e.g ['api_key']) sub update_params_for_auth { my ($self, $header_params, $query_params, $auth_settings) = @_; - - return if (!defined($auth_settings) || scalar(@$auth_settings) == 0); + + return $self->_global_auth_setup($header_params, $query_params) + unless $auth_settings && @$auth_settings; # one endpoint can have more than 1 auth settings foreach my $auth (@$auth_settings) { @@ -311,14 +320,51 @@ sub update_params_for_auth { } {{#authMethods}}elsif ($auth eq '{{name}}') { {{#isApiKey}}{{#isKeyInHeader}}$header_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$query_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$header_params->{'Authorization'} = 'Basic '.encode_base64($WWW::{{moduleName}}::Configuration::username.":".$WWW::{{moduleName}}::Configuration::password);{{/isBasic}} - {{#isOAuth}}# TODO support oauth{{/isOAuth}} + {{#isOAuth}}$header_params->{'Authorization'} = 'Bearer ' . $WWW::{{moduleName}}::Configuration::access_token;{{/isOAuth}} } {{/authMethods}} else { - # TODO show warning about security definition not found + # TODO show warning about security definition not found } } } +# The endpoint API class has not found any settings for auth. This may be deliberate, +# in which case update_params_for_auth() will be a no-op. But it may also be that the +# swagger spec does not describe the intended authorization. So we check in the config for any +# auth tokens and if we find any, we use them for all endpoints; +sub _global_auth_setup { + my ($self, $header_params, $query_params) = @_; + + my $tokens = $self->_cfg->get_tokens; + return unless keys %$tokens; + + # basic + if (my $uname = delete $tokens->{username}) { + my $pword = delete $tokens->{password}; + $header_params->{'Authorization'} = 'Basic '.encode_base64($uname.":".$pword); + } + + # oauth + if (my $access_token = delete $tokens->{access_token}) { + $header_params->{'Authorization'} = 'Bearer ' . $access_token; + } + + # other keys + foreach my $token_name (keys %$tokens) { + my $in = $tokens->{$token_name}->{in}; + my $token = $self->get_api_key_with_prefix($token_name); + if ($in eq 'head') { + $header_params->{$token_name} = $token; + } + elsif ($in eq 'query') { + $query_params->{$token_name} = $token; + } + else { + die "Don't know where to put token '$token_name' ('$in' is not 'head' or 'query')"; + } + } +} + 1; diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache new file mode 100644 index 00000000000..fc119f7a902 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache @@ -0,0 +1,100 @@ +package WWW::{{moduleName}}::ApiFactory; + +use strict; +use warnings; +use utf8; + +use Carp; +use Module::Find; + +usesub WWW::{{moduleName}}::Object; + +use WWW::{{moduleName}}::ApiClient; + +=head1 Name + + WWW::{{moduleName}}::ApiFactory - constructs APIs to retrieve {{moduleName}} objects + +=head1 Synopsis + + package My::Petstore::App; + + use WWW::{{moduleName}}::ApiFactory; + + my $api_factory = WWW::{{moduleName}}::ApiFactory->new( ... ); # any args for ApiClient constructor + + # later... + my $pet_api = $api_factory->get_api('Pet'); + + # $pet_api isa WWW::{{moduleName}}::PetApi + + my $pet = $pet_api->get_pet_by_id(pet_id => $pet_id); + + # object attributes have proper accessors: + printf "Pet's name is %s", $pet->name; + + # change the value stored on the object: + $pet->name('Dave'); + +=cut + +# Load all the API classes and construct a lookup table at startup time +my %_apis = map { $_ =~ /^WWW::{{moduleName}}::(.*)$/; $1 => $_ } + grep {$_ =~ /Api$/} + usesub 'WWW::{{moduleName}}'; + +=head1 new() + + Any parameters are optional, and are passed to and stored on the api_client object. + + base_url: (optional) + supply this to change the default base URL taken from the Swagger definition. + +=cut + +sub new { + my ($class, %p) = (shift, @_); + $p{api_client} = WWW::{{moduleName}}::ApiClient->instance(%p); + return bless \%p, $class; +} + +=head1 get_api($which) + + Returns an API object of the requested type. + + $which is a nickname for the class: + + WWW::FooBarClient::BazApi has nickname 'Baz' + +=cut + +sub get_api { + my ($self, $which) = @_; + croak "API not specified" unless $which; + my $api_class = $_apis{"${which}Api"} || croak "No known API for '$which'"; + return $api_class->new(api_client => $self->api_client); +} + +=head1 api_client() + + Returns the api_client object, should you ever need it. + +=cut + +sub api_client { $_[0]->{api_client} } + +=head1 apis_available() +=cut + +sub apis_available { return map { $_ =~ s/Api$//; $_ } sort keys %_apis } + +=head1 classname_for() +=cut + +sub classname_for { + my ($self, $api_name) = @_; + return $_apis{"${api_name}Api"}; +} + + +1; diff --git a/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache b/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache new file mode 100644 index 00000000000..76da048b069 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache @@ -0,0 +1,427 @@ +package WWW::{{moduleName}}::Role::AutoDoc; +use List::MoreUtils qw(uniq); + +use Moose::Role; + +sub autodoc { + my ($self, $how) = @_; + + die "Unknown format '$how'" unless $how =~ /^(pod|wide|narrow)$/; + + $self->_printisa($how); + $self->_printmethods($how); + $self->_printattrs($how); + print "\n"; +} + +sub _printisa { + my ($self, $how) = @_; + my $meta = $self->meta; + + my $myclass = ref $self; + + my $super = join ', ', $meta->superclasses; + my @roles = $meta->calculate_all_roles; + #shift(@roles) if @roles > 1; # if > 1, the first is a composite, the rest are the roles + + my $isa = join ', ', grep {$_ ne $myclass} $meta->linearized_isa; + my $sub = join ', ', $meta->subclasses; + my $dsub = join ', ', $meta->direct_subclasses; + + my $app_name = $self->version_info->{app_name}; + my $app_version = $self->version_info->{app_version}; + my $generated_date = $self->version_info->{generated_date}; + my $generator_class = $self->version_info->{generator_class}; + + $~ = $how eq 'pod' ? 'INHERIT_POD' : 'INHERIT'; + write; + + my ($rolepkg, $role_reqs); + + foreach my $role (@roles) { + $rolepkg = $role->{package} || next; # some are anonymous, or something + next if $rolepkg eq 'WWW::{{moduleName}}::Role::AutoDoc'; + $role_reqs = join ', ', keys %{$role->{required_methods}}; + $role_reqs ||= ''; + $~ = $how eq 'pod' ? 'ROLES_POD' : 'ROLES'; + write; + } + + if ($how eq 'pod') { + $~ = 'ROLES_POD_CLOSE'; + write; + } + +# ----- format specs ----- + format INHERIT = + +@* - +$myclass + ISA: @* + $isa + Direct subclasses: @* + $dsub + All subclasses: @* + $sub + + Target API: @* @* + $app_name, $app_version + Generated on: @* + $generated_date + Generator class: @* + $generator_class + +. + format ROLES = + Composes: ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ + $rolepkg + requires: ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ + $role_reqs + ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~ + $role_reqs +. + + format INHERIT_POD = +=head1 NAME + +@* +$myclass + +=head1 VERSION + +=head2 @* version: @* + $app_name, $app_version + +Automatically generated by the Perl Swagger Codegen project: + +=over 4 + +=item Build date: @* + $generated_date + +=item Build package: @* + $generator_class + +=item Codegen version: + + +=back + +=head1 INHERITANCE + +=head2 Base class(es) + +@* +$isa + +=head2 Direct subclasses + +@* +$dsub + +=head2 All subclasses + +@* +$sub + + +=head1 COMPOSITION + +@* composes the following roles: +$myclass + + +. + format ROLES_POD = +=head2 C<@*> + $rolepkg + +Requires: + +@* +$role_reqs + +. + format ROLES_POD_CLOSE = + + +. +# ----- / format specs ----- +} + +sub _printmethods { + my ($self, $how) = @_; + + if ($how eq 'narrow') { + print <_printmethod($_, $how) for uniq sort $self->meta->get_all_method_names; #$self->meta->get_method_list, + + if ($how eq 'pod') { + $~ = 'METHOD_POD_CLOSE'; + write; + } + + +} + +sub _printmethod { + my ($self, $methodname, $how) = @_; + return if $methodname =~ /^_/; + return if $self->meta->has_attribute($methodname); + my %internal = map {$_ => 1} qw(BUILD BUILDARGS meta can new DEMOLISHALL DESTROY + DOES isa BUILDALL does VERSION dump + ); + return if $internal{$methodname}; + my $method = $self->meta->get_method($methodname) or return; # symbols imported into namespaces i.e. not known by Moose + + return if $method->original_package_name eq __PACKAGE__; + + my $delegate_to = ''; + my $via = ''; + my $on = ''; + my $doc = ''; + my $original_pkg = $method->original_package_name; + if ($method->can('associated_attribute')) { + $delegate_to = $method->delegate_to_method; + my $aa = $method->associated_attribute; + $on = $aa->{isa}; + $via = $aa->{name}; + $original_pkg = $on; + $doc = $original_pkg->method_documentation->{$delegate_to}->{summary}; + } + else { + $doc = $method->documentation; + } + + if ($how eq 'narrow') { + $~ = 'METHOD_NARROW'; + write; + } + elsif ($how eq 'pod' and $delegate_to) { + $~ = 'METHOD_POD_DELEGATED'; + write; + } + elsif ($how eq 'pod') { + $~ = 'METHOD_POD'; + write; + } + else { + $~ = 'METHOD'; + write; + } + +# ----- format specs ----- + format METHODHEAD = + +METHODS +------- +Name delegates to on via +=========================================================================================================================================================================== +. + format METHOD = +@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<... @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<... @<<<<<<<<<<<<<<<<... +$methodname, $delegate_to, $on, $via +. + + format METHOD_NARROW = +@* +$methodname + original pkg: @* + $original_pkg + delegates to: @* + $delegate_to + on: @* + $on + via: @* + $via + +. + + format METHODHEAD_POD = + +=head1 METHODS + +. + + format METHOD_POD = + +=head2 C<@*()> + $methodname + + Defined in: @* + $original_pkg + + +. + format METHOD_POD_DELEGATED = + +=head2 C<@*()> + $methodname + + Defined in: @* + $original_pkg + Delegates to: @*() + $delegate_to + On: @* + $on + Via: @*() + $via + Doc: @* + $doc + Same as: $self->@*->@*() + $via, $delegate_to + +. + format METHOD_POD_CLOSE = + +. +# ----- / format specs ----- +} + +sub _printattrs { + my ($self, $how) = @_; + + if ($how eq 'narrow') { + print <_printattr($_, $how) for sort $self->meta->get_attribute_list; + + if ($how eq 'pod') { + $~ = 'ATTR_POD_CLOSE'; + write; + } +} + +sub _printattr { + my ($self, $attrname, $how) = @_; + return if $attrname =~ /^_/; + my $attr = $self->meta->get_attribute($attrname) or die "No attr for $attrname"; + + my $is; + $is = 'rw' if $attr->get_read_method && $attr->get_write_method; + $is = 'ro' if $attr->get_read_method && ! $attr->get_write_method; + $is = 'wo' if $attr->get_write_method && ! $attr->get_read_method; + $is = '--' if ! $attr->get_write_method && ! $attr->get_read_method; + $is or die "No \$is for $attrname"; + + my $tc = $attr->type_constraint || ''; + my $from = $attr->associated_class->name || ''; + my $reqd = $attr->is_required ? 'yes' : 'no'; + my $lazy = $attr->is_lazy ? 'yes' : 'no'; + my $has_doc = $attr->has_documentation ? 'yes' : 'no'; # *_api attributes will never have doc, but other attributes might have + my $doc = $attr->documentation || ''; + my $handles = join ', ', sort @{$attr->handles || []}; + $handles ||= ''; + + if ($how eq 'narrow') { + $~ = 'ATTR_NARROW'; + } + elsif ($how eq 'pod') { + $~ = 'ATTR_POD'; + } + else { + $~ = 'ATTR'; + } + + write; + +# ----- format specs ----- + format ATTRHEAD = + +ATTRIBUTES +---------- +Name is isa reqd lazy doc handles +============================================================================================================== +. + format ATTR = +@<<<<<<<<<<<<<<<<< @< @<<<<<<<<<<<<<<<<<<<<<<<< @<<< @<<< @<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< +$attrname, $is, $tc, $reqd, $lazy, $has_doc, $handles + ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~ + $handles +. + + format ATTR_NARROW = +@* +$attrname + is: @* + $is + isa: @* + $tc + reqd: @* + $reqd + lazy: @* + $lazy + doc: @* + $doc + handles: ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< + $handles + ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~ + $handles + +. + format ATTRHEAD_POD = +=head1 ATTRIBUTES + +. + format ATTR_POD = + +=head2 C<@*> + $attrname + + is: @* + $is + isa: @* + $tc + reqd: @* + $reqd + lazy: @* + $lazy + doc: @* + $doc + handles: ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< + $handles + ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~ + $handles + +. + format ATTR_POD_CLOSE = + + +. +# ----- / format specs ----- +} + + + +1; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index e740ea593ab..a41931940ba 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -11,6 +11,8 @@ use Log::Any qw($log); use Date::Parse; use DateTime; +use base ("Class::Accessor", "Class::Data::Inheritable"); + # # @@ -18,8 +20,26 @@ use DateTime; #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); -# return json string +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash sub to_hash { return decode_json(JSON->new->convert_blessed->encode( shift )); } @@ -28,36 +48,38 @@ sub to_hash { sub TO_JSON { my $self = shift; my $_data = {}; - foreach my $_key (keys %{$self->get_attribute_map}) { + foreach my $_key (keys %{$self->attribute_map}) { if (defined $self->{$_key}) { - $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; } } return $_data; } -# from json string +# from Perl hashref sub from_hash { my ($self, $hash) = @_; + # loop through attributes and use swagger_types to deserialize the data - while ( my ($_key, $_type) = each %{$self->get_swagger_types} ) { + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; if ($_type =~ /^array\[/i) { # array my $_subclass = substr($_type, 6, -1); my @_array = (); - foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { + foreach my $_element (@{$hash->{$_json_attribute}}) { push @_array, $self->_deserialize($_subclass, $_element); } $self->{$_key} = \@_array; - } elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime - $self->{$_key} = $self->_deserialize($_type, $hash->{$_key}); + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); } else { - $log->debugf("warning: %s not defined\n", $_key); + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); } } return $self; } - + # deserialize non-array data sub _deserialize { my ($self, $type, $data) = @_; diff --git a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache index 0a097dda7bd..75a1ba7f61a 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache @@ -10,15 +10,71 @@ use Carp; use constant VERSION => '{{moduleVersion}}'; # class/static variables -our $api_client; our $http_timeout = 180; our $http_user_agent = 'Perl-Swagger'; # authenticaiton setting our $api_key = {}; our $api_key_prefix = {}; -our $username; -our $password; +our $api_key_in = {}; +# username and password for HTTP basic authentication +our $username = ''; +our $password = ''; + +# access token for OAuth +our $access_token = ''; + +sub get_tokens { + my $class = shift; + + my $tokens = {}; + $tokens->{username} = $username if $username; + $tokens->{password} = $password if $password; + $tokens->{access_token} = $access_token if $access_token; + + foreach my $token_name (keys %{ $api_key }) { + $tokens->{$token_name}->{token} = $api_key->{$token_name}; + $tokens->{$token_name}->{prefix} = $api_key_prefix->{$token_name}; + $tokens->{$token_name}->{in} = $api_key_in->{$token_name}; + } + + return $tokens; +} + +sub clear_tokens { + my $class = shift; + my %tokens = %{$class->get_tokens}; # copy + + $username = undef; + $password = undef; + $access_token = undef; + + $api_key = {}; + $api_key_prefix = {}; + $api_key_in = {}; + + return \%tokens; +} + +sub accept_tokens { + my ($class, $tokens) = @_; + + foreach my $known_name (qw(username password access_token)) { + next unless $tokens->{$known_name}; + eval "\$$known_name = delete \$tokens->{\$known_name}"; + die $@ if $@; + } + + foreach my $token_name (keys %$tokens) { + $api_key->{$token_name} = $tokens->{$token_name}->{token}; + if ($tokens->{$token_name}->{prefix}) { + $api_key_prefix->{$token_name} = $tokens->{$token_name}->{prefix}; + } + my $in = $tokens->{$token_name}->{in} || 'head'; + croak "Tokens can only go in 'head' or 'query' (not in '$in')" unless $in =~ /^(?:head|query)$/; + $api_key_in->{$token_name} = $in; + } +} 1; diff --git a/modules/swagger-codegen/src/main/resources/perl/README.md b/modules/swagger-codegen/src/main/resources/perl/README.md new file mode 100644 index 00000000000..8d0b7695c15 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/README.md @@ -0,0 +1,219 @@ +# NAME + +WWW::{{moduleName}}::Role - a Moose role for the {{appName}} + +## {{appName}} version: {{appVersion}} + +# VERSION + +Automatically generated by the Perl Swagger Codegen project: + +- Build date: {{generatedDate}} +- Build package: {{generatorClass}} +- Codegen version: + +## A note on Moose + +This role is the only component of the library that uses Moose. See +WWW::{{moduleName}}::ApiFactory for non-Moosey usage. + +# SYNOPSIS + +The Perl Swagger Codegen project builds a library of Perl modules to interact with +a web service defined by a Swagger specification. See below for how to build the +library. + +This module provides an interface to the generated library. All the classes, +objects, and methods (well, not quite \*all\*, see below) are flattened into this +role. + + package MyApp; + use Moose; + with 'WWW::{{moduleName}}::Role'; + + package main; + + my $api = MyApp->new({ tokens => $tokens }); + + my $pet = $api->get_pet_by_id(pet_id => $pet_id); + + +## Structure of the library + +The library consists of a set of API classes, one for each endpoint. These APIs +implement the method calls available on each endpoint. + +Additionally, there is a set of "object" classes, which represent the objects +returned by and sent to the methods on the endpoints. + +An API factory class is provided, which builds instances of each endpoint API. + +This Moose role flattens all the methods from the endpoint APIs onto the consuming +class. It also provides methods to retrieve the endpoint API objects, and the API +factory object, should you need it. + +For documentation of all these methods, see AUTOMATIC DOCUMENTATION below. + +## Configuring authentication + +In the normal case, the Swagger spec will describe what parameters are +required and where to put them. You just need to supply the tokens. + + my $tokens = { + # basic + username => $username, + password => $password, + + # oauth + access_token => $oauth_token, + + # keys + $some_key => { token => $token, + prefix => $prefix, + in => $in, # 'head||query', + }, + + $another => { token => $token, + prefix => $prefix, + in => $in, # 'head||query', + }, + ..., + + }; + + my $api = MyApp->new({ tokens => $tokens }); + +Note these are all optional, as are `prefix` and `in`, and depend on the API +you are accessing. Usually `prefix` and `in` will be determined by the code generator from +the spec and you will not need to set them at run time. If not, `in` will +default to 'head' and `prefix` to the empty string. + +The tokens will be placed in the `WWW::{{moduleName}}::Configuration` namespace +as follows, but you don't need to know about this. + +- `$WWW::{{moduleName}}::Configuration::username` + + String. The username for basic auth. + +- `$WWW::{{moduleName}}::Configuration::password` + + String. The password for basic auth. + +- `$WWW::{{moduleName}}::Configuration::api_key` + + Hashref. Keyed on the name of each key (there can be multiple tokens). + + $WWW::{{moduleName}}::Configuration::api_key = { + secretKey => 'aaaabbbbccccdddd', + anotherKey => '1111222233334444', + }; + +- `$WWW::{{moduleName}}::Configuration::api_key_prefix` + + Hashref. Keyed on the name of each key (there can be multiple tokens). Note not + all api keys require a prefix. + + $WWW::{{moduleName}}::Configuration::api_key_prefix = { + secretKey => 'string', + anotherKey => 'same or some other string', + }; + +- `$WWW::{{moduleName}}::Configuration::access_token` + + String. The OAuth access token. + +# METHODS + +## `base_url` + +The generated code has the `base_url` already set as a default value. This method +returns (and optionally sets, but only if the API client has not been +created yet) the current value of `base_url`. + +## `api_factory` + +Returns an API factory object. You probably won't need to call this directly. + + $self->api_factory('Pet'); # returns a WWW::{{moduleName}}::PetApi instance + + $self->pet_api; # the same + +# MISSING METHODS + +Most of the methods on the API are delegated to individual endpoint API objects +(e.g. Pet API, Store API, User API etc). Where different endpoint APIs use the +same method name (e.g. `new()`), these methods can't be delegated. So you need +to call `$api->pet_api->new()`. + +In principle, every API is susceptible to the presence of a few, random, undelegatable +method names. In practice, because of the way method names are constructed, it's +unlikely in general that any methods will be undelegatable, except for: + + new() + class_documentation() + method_documentation() + +To call these methods, you need to get a handle on the relevant object, either +by calling `$api->foo_api` or by retrieving an object, e.g. +`$api->get_pet_by_id(pet_id => $pet_id)`. They are class methods, so +you could also call them on class names. + +# BUILDING YOUR LIBRARY + +See the homepage `https://github.com/swagger-api/swagger-codegen` for full details. +But briefly, clone the git repository, build the codegen codebase, set up your build +config file, then run the API build script. You will need git, Java 7 and Apache +maven 3.0.3 or better already installed. + +The config file should specify the project name for the generated library: + + {"moduleName":"MyProjectName"} + +Your library files will be built under `WWW::MyProjectName`. + + $ git clone https://github.com/swagger-api/swagger-codegen.git + $ cd swagger-codegen + $ mvn package + $ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ + -i [URL or file path to JSON swagger API spec] \ + -l perl \ + -c /path/to/config/file.json \ + -o /path/to/output/folder + +Bang, all done. Run the `autodoc` script in the `bin` directory to see the API +you just built. + +# AUTOMATIC DOCUMENTATION + +You can print out a summary of the generated API by running the included +`autodoc` script in the `bin` directory of your generated library. A few +output formats are supported: + + Usage: autodoc [OPTION] + + -w wide format (default) + -n narrow format + -p POD format + -H HTML format + -m Markdown format + -h print this help message + -c your application class + + +The `-c` option allows you to load and inspect your own application. A dummy +namespace is used if you don't supply your own class. + +# DOCUMENTATION FROM THE SWAGGER SPEC + +Additional documentation for each class and method may be provided by the Swagger +spec. If so, this is available via the `class_documentation()` and +`method_documentation()` methods on each generated object class, and the +`method_documentation()` method on the endpoint API classes: + + my $cmdoc = $api->pet_api->method_documentation->{$method_name}; + + my $odoc = $api->get_pet_by_id->(pet_id => $pet_id)->class_documentation; + my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; + + +Each of these calls returns a hashref with various useful pieces of information. diff --git a/modules/swagger-codegen/src/main/resources/perl/Role.mustache b/modules/swagger-codegen/src/main/resources/perl/Role.mustache new file mode 100644 index 00000000000..7bca8cca78d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/Role.mustache @@ -0,0 +1,323 @@ +package WWW::{{moduleName}}::Role; +use utf8; + +use Moose::Role; +use namespace::autoclean; +use Class::Inspector; +use Log::Any qw($log); +use WWW::{{moduleName}}::ApiFactory; + +has base_url => ( is => 'ro', + required => 0, + isa => 'Str', + documentation => 'Root of the server that requests are sent to', + ); + +has api_factory => ( is => 'ro', + isa => 'WWW::{{moduleName}}::ApiFactory', + builder => '_build_af', + lazy => 1, + documentation => 'Builds an instance of the endpoint API class', + ); + +has tokens => ( is => 'ro', + isa => 'HashRef', + required => 0, + default => sub { {} }, + documentation => 'The auth tokens required by the application - basic, OAuth and/or API key(s)', + ); + +has _cfg => ( is => 'ro', + isa => 'Str', + default => 'WWW::{{moduleName}}::Configuration', + ); + +has version_info => ( is => 'ro', + isa => 'HashRef', + default => sub { { + app_name => '{{appName}}', + app_version => '{{appVersion}}', + generated_date => '{{generatedDate}}', + generator_class => '{{generatorClass}}', + } }, + documentation => 'Information about the application version and the codegen codebase version' + ); + +sub BUILD { + my $self = shift; + + $self->_cfg->accept_tokens( $self->tokens ) if keys %{$self->tokens}; + + # ignore these symbols imported into API namespaces + my %outsiders = map {$_ => 1} qw( croak ); + + my %delegates; + + # collect the methods callable on each API + foreach my $api_name ($self->api_factory->apis_available) { + my $api_class = $self->api_factory->classname_for($api_name); + my $methods = Class::Inspector->methods($api_class, 'expanded'); # not Moose, so use CI instead + my @local_methods = grep {! /^_/} grep {! $outsiders{$_}} map {$_->[2]} grep {$_->[1] eq $api_class} @$methods; + push( @{$delegates{$_}}, {api_name => $api_name, api_class => $api_class} ) for @local_methods; + } + + # remove clashes + foreach my $method (keys %delegates) { + if ( @{$delegates{$method}} > 1 ) { + my ($apis) = delete $delegates{$method}; + } + } + + # build the flattened API + foreach my $api_name ($self->api_factory->apis_available) { + my $att_name = sprintf "%s_api", lc($api_name); + my $api_class = $self->api_factory->classname_for($api_name); + my @delegated = grep { $delegates{$_}->[0]->{api_name} eq $api_name } keys %delegates; + $log->debugf("Adding API: '%s' handles %s", $att_name, join ', ', @delegated); + $self->meta->add_attribute( $att_name => ( + is => 'ro', + isa => $api_class, + default => sub {$self->api_factory->get_api($api_name)}, + lazy => 1, + handles => \@delegated, + ) ); + } +} + +sub _build_af { + my $self = shift; + my %args; + $args{base_url} = $self->base_url if $self->base_url; + return WWW::{{moduleName}}::ApiFactory->new(%args); +} + +=head1 NAME + +WWW::{{moduleName}}::Role - a Moose role for the {{appName}} + +=head2 {{appName}} version: {{appVersion}} + +=head1 VERSION + +Automatically generated by the Perl Swagger Codegen project: + +=over 4 + +=item Build date: {{generatedDate}} + +=item Build package: {{generatorClass}} + +=item Codegen version: + +=back + +=head2 A note on Moose + +This role is the only component of the library that uses Moose. See +WWW::{{moduleName}}::ApiFactory for non-Moosey usage. + +=head1 SYNOPSIS + +The Perl Swagger Codegen project builds a library of Perl modules to interact with +a web service defined by a Swagger specification. See below for how to build the +library. + +This module provides an interface to the generated library. All the classes, +objects, and methods (well, not quite *all*, see below) are flattened into this +role. + + package MyApp; + use Moose; + with 'WWW::{{moduleName}}::Role'; + + package main; + + my $api = MyApp->new({ tokens => $tokens }); + + my $pet = $api->get_pet_by_id(pet_id => $pet_id); + +=head2 Structure of the library + +The library consists of a set of API classes, one for each endpoint. These APIs +implement the method calls available on each endpoint. + +Additionally, there is a set of "object" classes, which represent the objects +returned by and sent to the methods on the endpoints. + +An API factory class is provided, which builds instances of each endpoint API. + +This Moose role flattens all the methods from the endpoint APIs onto the consuming +class. It also provides methods to retrieve the endpoint API objects, and the API +factory object, should you need it. + +For documentation of all these methods, see AUTOMATIC DOCUMENTATION below. + +=head2 Configuring authentication + +In the normal case, the Swagger spec will describe what parameters are +required and where to put them. You just need to supply the tokens. + + my $tokens = { + # basic + username => $username, + password => $password, + + # oauth + access_token => $oauth_token, + + # keys + $some_key => { token => $token, + prefix => $prefix, + in => $in, # 'head||query', + }, + + $another => { token => $token, + prefix => $prefix, + in => $in, # 'head||query', + }, + ..., + + }; + + my $api = MyApp->new({ tokens => $tokens }); + +Note these are all optional, as are C and C, and depend on the API +you are accessing. Usually C and C will be determined by the code generator from +the spec and you will not need to set them at run time. If not, C will +default to 'head' and C to the empty string. + +The tokens will be placed in the C namespace +as follows, but you don't need to know about this. + +=over 4 + +=item C<$WWW::{{moduleName}}::Configuration::username> + +String. The username for basic auth. + +=item C<$WWW::{{moduleName}}::Configuration::password> + +String. The password for basic auth. + +=item C<$WWW::{{moduleName}}::Configuration::api_key> + +Hashref. Keyed on the name of each key (there can be multiple tokens). + + $WWW::{{moduleName}}::Configuration::api_key = { + secretKey => 'aaaabbbbccccdddd', + anotherKey => '1111222233334444', + }; + +=item C<$WWW::{{moduleName}}::Configuration::api_key_prefix> + +Hashref. Keyed on the name of each key (there can be multiple tokens). Note not +all api keys require a prefix. + + $WWW::{{moduleName}}::Configuration::api_key_prefix = { + secretKey => 'string', + anotherKey => 'same or some other string', + }; + +=item C<$WWW::{{moduleName}}::Configuration::access_token> + +String. The OAuth access token. + +=back + +=head1 METHODS + +=head2 C + +The generated code has the C already set as a default value. This method +returns (and optionally sets, but only if the API client has not been +created yet) the current value of C. + +=head2 C + +Returns an API factory object. You probably won't need to call this directly. + + $self->api_factory('Pet'); # returns a WWW::{{moduleName}}::PetApi instance + + $self->pet_api; # the same + +=head1 MISSING METHODS + +Most of the methods on the API are delegated to individual endpoint API objects +(e.g. Pet API, Store API, User API etc). Where different endpoint APIs use the +same method name (e.g. C), these methods can't be delegated. So you need +to call C<$api-Epet_api-Enew()>. + +In principle, every API is susceptible to the presence of a few, random, undelegatable +method names. In practice, because of the way method names are constructed, it's +unlikely in general that any methods will be undelegatable, except for: + + new() + class_documentation() + method_documentation() + +To call these methods, you need to get a handle on the relevant object, either +by calling C<$api-Efoo_api> or by retrieving an object, e.g. +C<$api-Eget_pet_by_id(pet_id =E $pet_id)>. They are class methods, so +you could also call them on class names. + +=head1 BUILDING YOUR LIBRARY + +See the homepage C for full details. +But briefly, clone the git repository, build the codegen codebase, set up your build +config file, then run the API build script. You will need git, Java 7 and Apache +maven 3.0.3 or better already installed. + +The config file should specify the project name for the generated library: + + {"moduleName":"MyProjectName"} + +Your library files will be built under C. + + $ git clone https://github.com/swagger-api/swagger-codegen.git + $ cd swagger-codegen + $ mvn package + $ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ + -i [URL or file path to JSON swagger API spec] \ + -l perl \ + -c /path/to/config/file.json \ + -o /path/to/output/folder + +Bang, all done. Run the C script in the C directory to see the API +you just built. + +=head1 AUTOMATIC DOCUMENTATION + +You can print out a summary of the generated API by running the included +C script in the C directory of your generated library. A few +output formats are supported: + + Usage: autodoc [OPTION] + + -w wide format (default) + -n narrow format + -p POD format + -H HTML format + -m Markdown format + -h print this help message + -c your application class + +The C<-c> option allows you to load and inspect your own application. A dummy +namespace is used if you don't supply your own class. + +=head1 DOCUMENTATION FROM THE SWAGGER SPEC + +Additional documentation for each class and method may be provided by the Swagger +spec. If so, this is available via the C and +C methods on each generated object class, and the +C method on the endpoint API classes: + + my $cmdoc = $api->pet_api->method_documentation->{$method_name}; + + my $odoc = $api->get_pet_by_id->(pet_id => $pet_id)->class_documentation; + my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; + +Each of these calls returns a hashref with various useful pieces of information. + +=cut + +1; diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index e69e4e3066f..f25c63a528c 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -30,11 +30,14 @@ use Log::Any qw($log); use WWW::{{moduleName}}::ApiClient; use WWW::{{moduleName}}::Configuration; +use base "Class::Data::Inheritable"; + +__PACKAGE__->mk_classdata('method_documentation' => {}); + sub new { my $class = shift; - my $default_api_client = $WWW::{{moduleName}}::Configuration::api_client ? $WWW::{{moduleName}}::Configuration::api_client : WWW::{{moduleName}}::ApiClient->new; my (%self) = ( - 'api_client' => $default_api_client, + 'api_client' => WWW::{{moduleName}}::ApiClient->instance, @_ ); @@ -49,13 +52,31 @@ sub new { {{#operations}} {{#operation}} + # # {{{nickname}}} # # {{{summary}}} # {{#allParams}}# @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} -{{/allParams}}# @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +{{/allParams}} +{ + my $params = { +{{#allParams}} + '{{paramName}}' => { + data_type => '{{dataType}}', + description => '{{description}}', + required => {{#required}}'1'{{/required}}{{^required}}'0'{{/required}}, + }, +{{/allParams}} + }; + __PACKAGE__->method_documentation->{ {{nickname}} } = { + summary => '{{summary}}', + params => $params, + returns => {{#returnType}}'{{{returnType}}}'{{/returnType}}{{^returnType}}undef{{/returnType}}, + }; +} +# @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} # sub {{nickname}} { my ($self, %args) = @_; @@ -100,7 +121,7 @@ sub {{nickname}} { {{#formParams}}# form params if ( exists $args{'{{paramName}}'} ) { {{#isFile}}$form_params->{'{{baseName}}'} = [] unless defined $form_params->{'{{baseName}}'}; - push $form_params->{'{{baseName}}'}, $args{'{{paramName}}'}; + push @{$form_params->{'{{baseName}}'}}, $args{'{{paramName}}'}; {{/isFile}} {{^isFile}}$form_params->{'{{baseName}}'} = $self->{api_client}->to_form_value($args{'{{paramName}}'}); {{/isFile}} @@ -112,7 +133,7 @@ sub {{nickname}} { }{{/bodyParams}} # authentication setting, if any - my $auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; + my $auth_settings = [qw({{#authMethods}}{{name}} {{/authMethods}})]; # make the API Call {{#returnType}}my $response = $self->{api_client}->call_api($_resource_path, $_method, diff --git a/modules/swagger-codegen/src/main/resources/perl/autodoc.script.mustache b/modules/swagger-codegen/src/main/resources/perl/autodoc.script.mustache new file mode 100644 index 00000000000..240936d9b51 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/perl/autodoc.script.mustache @@ -0,0 +1,77 @@ +#!/usr/bin/perl +use FindBin; +use File::Spec; +use lib File::Spec->catdir($FindBin::Bin, '..', 'lib'); + +use Moose::Util qw(apply_all_roles); +use Getopt::Std; + +my %options=(); +getopts("wnphmHc:", \%options); +help if $options{h}; + +my $my_app = $options{c} || 'My::App'; + +if ($options{c}) { + eval <new; + +if ($options{H}) { + my $pod2html = "pod2html --backlink --css http://st.pimg.net/tucs/style.css?3"; + open STDOUT, "| $pod2html" or die "Can't fork: $!"; + $api->autodoc($opt); + close STDOUT or die "Can't close: $!"; +} +elsif ($options{m}) { + my $pod2markdown = "pod2markdown --html-encode-chars 1"; + open STDOUT, "| $pod2markdown" or die "Can't fork: $!"; + $api->autodoc($opt); + close STDOUT or die "Can't close: $!"; +} +else { + $api->autodoc($opt); +} + +exit(0); + +# -------------------- +sub help { + print <class_documentation({description => '{{description}}', + class => '{{classname}}', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + {{#vars}}'{{name}}' => { + datatype => '{{datatype}}', + base_name => '{{baseName}}', + description => '{{description}}', + format => '{{format}}', + read_only => '{{readOnly}}', + }, + {{/vars}} +}); + +__PACKAGE__->swagger_types( { {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} -}; +} ); -my $attribute_map = { +__PACKAGE__->attribute_map( { {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} -}; +} ); -# new object -sub new { - my ($class, %args) = @_; - my $self = { - {{#vars}}#{{#description}}{{{description}}}{{/description}} - '{{name}}' => $args{'{{baseName}}'}{{#hasMore}}, - {{/hasMore}}{{/vars}} - }; - - return bless $self, $class; -} - -# get swagger type of the attribute -sub get_swagger_types { - return $swagger_types; -} - -# get attribute mappping -sub get_attribute_map { - return $attribute_map; -} +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); 1; {{/model}} diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index e2193b1d754..11fe3827d48 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -69,7 +69,7 @@ class ApiClient * Constructor of the class * @param Configuration $config config for this ApiClient */ - function __construct(Configuration $config = null) + public function __construct(Configuration $config = null) { if ($config == null) { $config = Configuration::getDefaultConfiguration(); diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index db1d4c8cb4f..e3a9749c423 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -140,7 +140,18 @@ use \{{invokerPackage}}\ObjectSerializer; }{{/pathParams}} {{#formParams}}// form params if (${{paramName}} !== null) { - $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->getSerializer()->toFormValue(${{paramName}}); + {{#isFile}} + // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax + // See: https://wiki.php.net/rfc/curl-file-upload + if (function_exists('curl_file_create')) { + $formParams['{{baseName}}'] = curl_file_create($this->apiClient->getSerializer()->toFormValue(${{paramName}})); + } else { + $formParams['{{baseName}}'] = '@' . $this->apiClient->getSerializer()->toFormValue(${{paramName}}); + } + {{/isFile}} + {{^isFile}} + $formParams['{{baseName}}'] = $this->apiClient->getSerializer()->toFormValue(${{paramName}}); + {{/isFile}} }{{/formParams}} {{#bodyParams}}// body params $_tempBody = null; @@ -159,8 +170,8 @@ use \{{invokerPackage}}\ObjectSerializer; if (isset($apiKey)) { {{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} }{{/isApiKey}} - {{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode($this->apiClient->getConfig()->getUsername().":".$this->apiClient->getConfig()->getPassword());{{/isBasic}} - {{#isOAuth}}//TODO support oauth{{/isOAuth}} + {{#isBasic}}$headerParams['Authorization'] = 'Basic ' . base64_encode($this->apiClient->getConfig()->getUsername() . ":" . $this->apiClient->getConfig()->getPassword());{{/isBasic}} + {{#isOAuth}}$headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken();{{/isOAuth}} {{/authMethods}} // make the API Call try diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 96bc8a1b660..14d7957fe54 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -63,6 +63,13 @@ class Configuration */ protected $apiKeyPrefixes = array(); + /** + * Access token for OAuth + * + * @var string + */ + protected $accessToken = ''; + /** * Username for HTTP basic authentication * @@ -195,6 +202,29 @@ class Configuration return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; } + /** + * Sets the access token for OAuth + * + * @param string $accessToken Token for OAuth + * + * @return Configuration + */ + public function setAccessToken($accessToken) + { + $this->$accessToken = $accessToken; + return $this; + } + + /** + * Gets the access token for OAuth + * + * @return string Access token for OAuth + */ + public function getAccessToken() + { + return $this->accessToken; + } + /** * Sets the username for HTTP basic authentication * diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index b076fa5d3ea..474cf84f356 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -47,7 +47,7 @@ class {{classname}}(object): self.api_client = config.api_client {{#operation}} - def {{nickname}}(self, {{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}**kwargs): + def {{nickname}}(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): """ {{{summary}}} {{{notes}}} @@ -58,7 +58,12 @@ class {{classname}}(object): >>> def callback_function(response): >>> pprint(response) >>> +{{#sortParamsByRequiredFlag}} >>> thread = api.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}callback=callback_function) +{{/sortParamsByRequiredFlag}} +{{^sortParamsByRequiredFlag}} + >>> thread = api.{{nickname}}({{#allParams}}{{#required}}{{paramName}}={{paramName}}_value, {{/required}}{{/allParams}}callback=callback_function) +{{/sortParamsByRequiredFlag}} :param callback function: The callback function for asynchronous request. (optional) @@ -69,13 +74,6 @@ class {{classname}}(object): If the method is called asynchronously, returns the request thread. """ -{{#allParams}} -{{#required}} - # verify the required parameter '{{paramName}}' is set - if {{paramName}} is None: - raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{nickname}}`") -{{/required}} -{{/allParams}} all_params = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] all_params.append('callback') @@ -90,6 +88,14 @@ class {{classname}}(object): params[key] = val del params['kwargs'] +{{#allParams}} +{{#required}} + # verify the required parameter '{{paramName}}' is set + if ('{{paramName}}' not in params) or (params['{{paramName}}'] is None): + raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{nickname}}`") +{{/required}} +{{/allParams}} + resource_path = '{{path}}'.replace('{format}', 'json') method = '{{httpMethod}}' diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 78fa8fb6d3c..bab1d09d761 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -71,6 +71,10 @@ class Configuration(object): self.username = "" # Password for HTTP basic authentication self.password = "" +{{#authMethods}}{{#isOAuth}} + # access token for OAuth + self.access_token = "" +{{/isOAuth}}{{/authMethods}} # Logging Settings self.logger = {} @@ -231,8 +235,15 @@ class Configuration(object): 'key': 'Authorization', 'value': self.get_basic_auth_token() }, -{{/isBasic}} -{{/authMethods}} +{{/isBasic}}{{#isOauth}} + '{{name}}': + { + 'type': 'oauth2', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + }, +{{/isOauth}}{{/authMethods}} } def to_debug_report(self): diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache index 7f4d748c2dc..7bd9b3f46cc 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/helpers-body.mustache @@ -25,6 +25,14 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) { qint64 *val = static_cast(value); *val = obj.toVariant().toLongLong(); } + else if(QStringLiteral("float").compare(type) == 0) { + float *val = static_cast(value); + *val = obj.toDouble(); + } + else if(QStringLiteral("double").compare(type) == 0) { + double *val = static_cast(value); + *val = obj.toDouble(); + } else if (QStringLiteral("QString").compare(type) == 0) { QString **val = static_cast(value); @@ -86,6 +94,16 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) { setValue(&val, jval, QStringLiteral("bool"), QStringLiteral("")); output->append((void*)&val); } + else if(QStringLiteral("float").compare(complexType) == 0) { + float val; + setValue(&val, jval, QStringLiteral("float"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("double").compare(complexType) == 0) { + double val; + setValue(&val, jval, QStringLiteral("double"), QStringLiteral("")); + output->append((void*)&val); + } } } QList **val = static_cast**>(value); @@ -131,6 +149,14 @@ toJsonValue(QString name, void* value, QJsonObject* output, QString type) { bool* str = static_cast(value); output->insert(name, QJsonValue(*str)); } + else if(QStringLiteral("float").compare(type) == 0) { + float* str = static_cast(value); + output->insert(name, QJsonValue((double)*str)); + } + else if(QStringLiteral("double").compare(type) == 0) { + double* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } } void diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index ad885dac94e..a43260c0607 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -36,8 +36,8 @@ module {{moduleName}} # query parameters query_params = {}{{#queryParams}}{{#required}} - query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} - query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} + query_params[:'{{{baseName}}}'] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} + query_params[:'{{{baseName}}}'] = {{#collectionFormat}}@api_client.build_collection_param(opts[:'{{{paramName}}}'], :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}opts[:'{{{paramName}}}']{{/collectionFormat}} if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} # header parameters header_params = {} @@ -49,13 +49,13 @@ module {{moduleName}} # HTTP header 'Content-Type' _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} - header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} - header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} + header_params[:'{{{baseName}}}'] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} + header_params[:'{{{baseName}}}'] = {{#collectionFormat}}@api_client.build_collection_param(opts[:'{{{paramName}}}'], :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}opts[:'{{{paramName}}}']{{/collectionFormat}} if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} # form parameters form_params = {}{{#formParams}}{{#required}} - form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} - form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}} + form_params["{{baseName}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} + form_params["{{baseName}}"] = {{#collectionFormat}}@api_client.build_collection_param(opts[:'{{{paramName}}}'], :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}opts[:'{{{paramName}}}']{{/collectionFormat}} if opts[:'{{paramName}}']{{/required}}{{/formParams}} # http body (model) {{^bodyParam}}post_body = nil diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 2bdcf6dc7be..4ef665bddf2 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -189,9 +189,15 @@ module {{moduleName}} # http form if header_params['Content-Type'] == 'application/x-www-form-urlencoded' || header_params['Content-Type'] == 'multipart/form-data' - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) + data = {} + form_params.each do |key, value| + case value + when File, Array, nil + # let typhoeus handle File, Array and nil parameters + data[key] = value + else + data[key] = value.to_s + end end elsif body data = body.is_a?(String) ? body : body.to_json @@ -269,5 +275,25 @@ module {{moduleName}} obj end end + + # Build parameter value according to the given collection format. + # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi + def build_collection_param(param, collection_format) + case collection_format + when :csv + param.join(',') + when :ssv + param.join(' ') + when :tsv + param.join("\t") + when :pipes + param.join('|') + when :multi + # return the array directly as typhoeus will handle it as expected + param + else + fail "unknown collection format: #{collection_format.inspect}" + end + end end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index ccf6db4a4fd..ddb68998e9e 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -42,6 +42,17 @@ module {{moduleName}} else false end + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end else # model _model = {{moduleName}}.const_get(type).new _model.build_from_hash(value) @@ -63,11 +74,7 @@ module {{moduleName}} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? - if value.is_a?(Array) - hash[param] = value.compact.map{ |v| _to_hash(v) } - else - hash[param] = _to_hash(value) - end + hash[param] = _to_hash(value) end hash end @@ -75,7 +82,13 @@ module {{moduleName}} # Method to output non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value def _to_hash(value) - if value.respond_to? :to_hash + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash value.to_hash else value diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache index 0385aaffd83..89bf133b22c 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache @@ -44,6 +44,9 @@ module {{moduleName}} # @return [String] attr_accessor :password + # Defines the access token (Bearer) used with OAuth2. + attr_accessor :access_token + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response # details will be logged with `logger.debug` (see the `logger` attribute). # Default to false. @@ -179,6 +182,15 @@ module {{moduleName}} value: basic_auth_token }, {{/isBasic}} +{{#isOAuth}} + '{{name}}' => + { + type: 'oauth2', + in: 'header', + key: 'Authorization', + value: "Bearer #{access_token}" + }, +{{/isOAuth}} {{/authMethods}} } end diff --git a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache index 495752f624d..5a9f1f7a278 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache @@ -7,8 +7,9 @@ import Foundation public class {{projectName}}API { - static let basePath = "{{basePath}}" - static var credential: NSURLCredential? + public static var basePath = "{{basePath}}" + public static var credential: NSURLCredential? + public static var customHeaders: [String:String] = [:] static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() } @@ -41,9 +42,17 @@ public class RequestBuilder { self.URLString = URLString self.parameters = parameters self.isBody = isBody + + addHeaders({{projectName}}API.customHeaders) } - public func execute(completion: (response: Response?, erorr: ErrorType?) -> Void) { } + public func addHeaders(aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + public func execute(completion: (response: Response?, error: ErrorType?) -> Void) { } public func addHeader(name name: String, value: String) -> Self { if !value.isEmpty { diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index dbc25584886..6b4d36f9410 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -20,7 +20,7 @@ class AlamofireRequestBuilder: RequestBuilder { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) } - override func execute(completion: (response: Response?, erorr: ErrorType?) -> Void) { + override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { let managerId = NSUUID().UUIDString // Create a new manager for each request to customize its request header let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() @@ -60,7 +60,7 @@ class AlamofireRequestBuilder: RequestBuilder { case .Success(let upload, _, _): self.processRequest(upload, managerId, completion) case .Failure(let encodingError): - completion(response: nil, erorr: encodingError) + completion(response: nil, error: encodingError) } } ) @@ -70,7 +70,7 @@ class AlamofireRequestBuilder: RequestBuilder { } - private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, erorr: ErrorType?) -> Void) { + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, error: ErrorType?) -> Void) { if let credential = self.credential { request.authenticate(usingCredential: credential) } @@ -79,26 +79,26 @@ class AlamofireRequestBuilder: RequestBuilder { managerStore.removeValueForKey(managerId) if response.result.isFailure { - completion(response: nil, erorr: response.result.error) + completion(response: nil, error: response.result.error) return } if () is T { - completion(response: Response(response: response.response!, body: () as! T), erorr: nil) + completion(response: Response(response: response.response!, body: () as! T), error: nil) return } if let json: AnyObject = response.result.value { let body = Decoders.decode(clazz: T.self, source: json) - completion(response: Response(response: response.response!, body: body), erorr: nil) + completion(response: Response(response: response.response!, body: body), error: nil) return } else if "" is T { // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release // https://github.com/swagger-api/swagger-parser/pull/34 - completion(response: Response(response: response.response!, body: "" as! T), erorr: nil) + completion(response: Response(response: response.response!, body: "" as! T), error: nil) return } - completion(response: nil, erorr: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) } } diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index f6df790ea94..af8f5c875a7 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -118,6 +118,10 @@ class Decoders { fatalError("formatter failed to parse \(sourceString)") } {{#models}}{{#model}} + // Decoder for [{{{classname}}}] + Decoders.addDecoder(clazz: [{{{classname}}}].self) { (source: AnyObject) -> [{{{classname}}}] in + return Decoders.decode(clazz: [{{{classname}}}].self, source: source) + } // Decoder for {{{classname}}} Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in let sourceDictionary = source as! [NSObject:AnyObject] diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java new file mode 100644 index 00000000000..7bc2a86bc6b --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/AbstractOptionsTest.java @@ -0,0 +1,63 @@ +package io.swagger.codegen; + +import io.swagger.codegen.options.OptionsProvider; + +import com.google.common.base.Function; +import com.google.common.collect.Lists; + +import mockit.FullVerifications; + +import org.apache.commons.lang3.StringUtils; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public abstract class AbstractOptionsTest { + private final OptionsProvider optionsProvider; + + protected AbstractOptionsTest(OptionsProvider optionsProvider) { + this.optionsProvider = optionsProvider; + } + + @Test + public void checkOptionsProcessing() { + getCodegenConfig().additionalProperties().putAll(optionsProvider.createOptions()); + setExpectations(); + + getCodegenConfig().processOpts(); + + new FullVerifications() {{ + }}; + } + + @Test(description = "check if all options described in documentation are presented in test case") + public void checkOptionsHelp() { + final List cliOptions = Lists.transform(getCodegenConfig().cliOptions(), getCliOptionTransformer()); + final Set testOptions = optionsProvider.createOptions().keySet(); + final Set skipped = new HashSet(cliOptions); + skipped.removeAll(testOptions); + if (!skipped.isEmpty()) { + Assert.fail(String.format("These options weren't checked: %s.", StringUtils.join(skipped, ", "))); + } + final Set undocumented = new HashSet(testOptions); + undocumented.removeAll(cliOptions); + if (!undocumented.isEmpty()) { + Assert.fail(String.format("These options weren't documented: %s.", StringUtils.join(undocumented, ", "))); + } + } + + private Function getCliOptionTransformer() { + return new Function() { + public String apply(CliOption option) { + return option.getOpt(); + } + }; + } + + protected abstract CodegenConfig getCodegenConfig(); + + protected abstract void setExpectations(); +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java new file mode 100644 index 00000000000..1b6f878b512 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/akkascala/AkkaScalaClientOptionsTest.java @@ -0,0 +1,36 @@ +package io.swagger.codegen.akkascala; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.AkkaScalaClientCodegen; +import io.swagger.codegen.options.AkkaScalaClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class AkkaScalaClientOptionsTest extends AbstractOptionsTest { + + @Tested + private AkkaScalaClientCodegen clientCodegen; + + public AkkaScalaClientOptionsTest() { + super(new AkkaScalaClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(AkkaScalaClientOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(AkkaScalaClientOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AkkaScalaClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java new file mode 100644 index 00000000000..c36c5453d98 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java @@ -0,0 +1,48 @@ +package io.swagger.codegen.android; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.AndroidClientCodegen; +import io.swagger.codegen.options.AndroidClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class AndroidClientOptionsTest extends AbstractOptionsTest { + + @Tested + private AndroidClientCodegen clientCodegen; + + public AndroidClientOptionsTest() { + super(new AndroidClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(AndroidClientOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(AndroidClientOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AndroidClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(AndroidClientOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(AndroidClientOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(AndroidClientOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(AndroidClientOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(AndroidClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setUseAndroidMavenGradlePlugin(Boolean.valueOf(AndroidClientOptionsProvider.ANDROID_MAVEN_GRADLE_PLUGIN_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java new file mode 100644 index 00000000000..b6b90ae7a7c --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/asyncscala/AsyncScalaClientOptionsTest.java @@ -0,0 +1,36 @@ +package io.swagger.codegen.asyncscala; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.AsyncScalaClientCodegen; +import io.swagger.codegen.options.AsyncScalaClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class AsyncScalaClientOptionsTest extends AbstractOptionsTest { + + @Tested + private AsyncScalaClientCodegen clientCodegen; + + public AsyncScalaClientOptionsTest() { + super(new AsyncScalaClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(AsyncScalaClientOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(AsyncScalaClientOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AsyncScalaClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java new file mode 100644 index 00000000000..4c0d5f366a1 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -0,0 +1,34 @@ +package io.swagger.codegen.csharp; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.CSharpClientCodegen; +import io.swagger.codegen.options.CSharpClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class CSharpClientOptionsTest extends AbstractOptionsTest { + + @Tested + private CSharpClientCodegen clientCodegen; + + public CSharpClientOptionsTest() { + super(new CSharpClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setPackageName(CSharpClientOptionsProvider.PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setPackageVersion(CSharpClientOptionsProvider.PACKAGE_VERSION_VALUE); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java new file mode 100644 index 00000000000..7e30e2b1cd0 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharpdotnettwo/CsharpDotNet2ClientOptionsTest.java @@ -0,0 +1,36 @@ +package io.swagger.codegen.csharpdotnettwo; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.CsharpDotNet2ClientCodegen; +import io.swagger.codegen.options.CsharpDotNet2ClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class CsharpDotNet2ClientOptionsTest extends AbstractOptionsTest { + + @Tested + private CsharpDotNet2ClientCodegen clientCodegen; + + public CsharpDotNet2ClientOptionsTest() { + super(new CsharpDotNet2ClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setPackageName(CsharpDotNet2ClientOptionsProvider.PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setPackageVersion(CsharpDotNet2ClientOptionsProvider.PACKAGE_VERSION_VALUE); + times = 1; + clientCodegen.setClientPackage(CsharpDotNet2ClientOptionsProvider.CLIENT_PACKAGE_VALUE); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java new file mode 100644 index 00000000000..b002fd99978 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java @@ -0,0 +1,43 @@ +package io.swagger.codegen.dart; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.DartClientCodegen; +import io.swagger.codegen.options.DartClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class DartClientOptionsTest extends AbstractOptionsTest { + + @Tested + private DartClientCodegen clientCodegen; + + public DartClientOptionsTest() { + super(new DartClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(DartClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setBrowserClient(Boolean.valueOf(DartClientOptionsProvider.BROWSER_CLIENT_VALUE)); + times = 1; + clientCodegen.setPubName(DartClientOptionsProvider.PUB_NAME_VALUE); + times = 1; + clientCodegen.setPubVersion(DartClientOptionsProvider.PUB_VERSION_VALUE); + times = 1; + clientCodegen.setPubDescription(DartClientOptionsProvider.PUB_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setSourceFolder(DartClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + }}; + } +} + diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java new file mode 100644 index 00000000000..21a9cb5e03b --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/flash/FlashClienOptionsTest.java @@ -0,0 +1,40 @@ +package io.swagger.codegen.flash; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.FlashClientCodegen; +import io.swagger.codegen.options.FlashClienOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +import java.util.Map; + +public class FlashClienOptionsTest extends AbstractOptionsTest { + + @Tested + private FlashClientCodegen clientCodegen; + + public FlashClienOptionsTest() { + super(new FlashClienOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setPackageName(FlashClienOptionsProvider.PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setPackageVersion(FlashClienOptionsProvider.PACKAGE_VERSION_VALUE); + times = 1; + clientCodegen.setInvokerPackage(FlashClienOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setSourceFolder(FlashClienOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java new file mode 100644 index 00000000000..d7046dda9b2 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/inflector/JavaInflectorServerOptionsTest.java @@ -0,0 +1,55 @@ +package io.swagger.codegen.inflector; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.java.JavaClientOptionsTest; +import io.swagger.codegen.languages.JavaInflectorServerCodegen; +import io.swagger.codegen.options.JavaInflectorServerOptionsProvider; +import io.swagger.codegen.options.JavaOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class JavaInflectorServerOptionsTest extends JavaClientOptionsTest { + + @Tested + private JavaInflectorServerCodegen clientCodegen; + + public JavaInflectorServerOptionsTest() { + super(new JavaInflectorServerOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(JavaInflectorServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(JavaInflectorServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaInflectorServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(JavaInflectorServerOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(JavaInflectorServerOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(JavaInflectorServerOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(JavaInflectorServerOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(JavaInflectorServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(JavaInflectorServerOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(JavaInflectorServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setLibrary(JavaInflectorServerOptionsProvider.LIBRARY_VALUE); + times = 1; + clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaInflectorServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java new file mode 100644 index 00000000000..29166bc8750 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java @@ -0,0 +1,59 @@ +package io.swagger.codegen.java; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.options.JavaOptionsProvider; +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.codegen.options.OptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class JavaClientOptionsTest extends AbstractOptionsTest { + + @Tested + private JavaClientCodegen clientCodegen; + + public JavaClientOptionsTest() { + super(new JavaOptionsProvider()); + } + + protected JavaClientOptionsTest(OptionsProvider optionsProvider) { + super(optionsProvider); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(JavaOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(JavaOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(JavaOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(JavaOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(JavaOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(JavaOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(JavaOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(JavaOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(JavaOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setLibrary(JavaOptionsProvider.LIBRARY_VALUE); + times = 1; + clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java new file mode 100644 index 00000000000..ac6288b7f1e --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java @@ -0,0 +1,54 @@ +package io.swagger.codegen.jaxrs; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.java.JavaClientOptionsTest; +import io.swagger.codegen.languages.JaxRSServerCodegen; +import io.swagger.codegen.options.JaxRSServerOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class JaxRSServerOptionsTest extends JavaClientOptionsTest { + + @Tested + private JaxRSServerCodegen clientCodegen; + + public JaxRSServerOptionsTest() { + super(new JaxRSServerOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(JaxRSServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(JaxRSServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JaxRSServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(JaxRSServerOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(JaxRSServerOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(JaxRSServerOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(JaxRSServerOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(JaxRSServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(JaxRSServerOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(JaxRSServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setLibrary(JaxRSServerOptionsProvider.LIBRARY_VALUE); + times = 1; + clientCodegen.setFullJavaUtil(Boolean.valueOf(JaxRSServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java new file mode 100644 index 00000000000..ce905315ae3 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.nodejs; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.NodeJSServerCodegen; +import io.swagger.codegen.options.NodeJSServerOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class NodeJSServerOptionsTest extends AbstractOptionsTest { + + @Tested + private NodeJSServerCodegen clientCodegen; + + public NodeJSServerOptionsTest() { + super(new NodeJSServerOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(NodeJSServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java new file mode 100644 index 00000000000..33f20625e16 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcClientOptionsTest.java @@ -0,0 +1,44 @@ +package io.swagger.codegen.objc; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.ObjcClientCodegen; +import io.swagger.codegen.options.ObjcClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class ObjcClientOptionsTest extends AbstractOptionsTest { + + @Tested + private ObjcClientCodegen clientCodegen; + + public ObjcClientOptionsTest() { + super(new ObjcClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setClassPrefix(ObjcClientOptionsProvider.CLASS_PREFIX_VALUE); + times = 1; + clientCodegen.setPodName(ObjcClientOptionsProvider.POD_NAME_VALUE); + times = 1; + clientCodegen.setPodVersion(ObjcClientOptionsProvider.POD_VERSION_VALUE); + times = 1; + clientCodegen.setAuthorName(ObjcClientOptionsProvider.AUTHOR_NAME_VALUE); + times = 1; + clientCodegen.setAuthorEmail(ObjcClientOptionsProvider.AUTHOR_EMAIL_VALUE); + times = 1; + clientCodegen.setGitRepoURL(ObjcClientOptionsProvider.GIT_REPO_URL_VALUE); + times = 1; + clientCodegen.setLicense(ObjcClientOptionsProvider.LICENSE_VALUE); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java new file mode 100644 index 00000000000..e26968500d7 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java @@ -0,0 +1,34 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class AkkaScalaClientOptionsProvider implements OptionsProvider { + public static final String MODEL_PACKAGE_VALUE = "package"; + public static final String API_PACKAGE_VALUE = "apiPackage"; + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "akka-scala"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java new file mode 100644 index 00000000000..c677e5caa7b --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java @@ -0,0 +1,47 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.AndroidClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class AndroidClientOptionsProvider implements OptionsProvider { + public static final String ARTIFACT_ID_VALUE = "swagger-java-client-test"; + public static final String MODEL_PACKAGE_VALUE = "package"; + public static final String API_PACKAGE_VALUE = "apiPackage"; + public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String GROUP_ID_VALUE = "io.swagger.test"; + public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; + public static final String ANDROID_MAVEN_GRADLE_PLUGIN_VALUE = "true"; + + @Override + public String getLanguage() { + return "android"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) + .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) + .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(AndroidClientCodegen.USE_ANDROID_MAVEN_GRADLE_PLUGIN, ANDROID_MAVEN_GRADLE_PLUGIN_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java new file mode 100644 index 00000000000..be21a20efe4 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java @@ -0,0 +1,34 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class AsyncScalaClientOptionsProvider implements OptionsProvider { + public static final String MODEL_PACKAGE_VALUE = "package"; + public static final String API_PACKAGE_VALUE = "apiPackage"; + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "async-scala"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java new file mode 100644 index 00000000000..442465dfcf9 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -0,0 +1,31 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class CSharpClientOptionsProvider implements OptionsProvider { + public static final String PACKAGE_NAME_VALUE = "swagger_client_csharp"; + public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; + + @Override + public String getLanguage() { + return "csharp"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CsharpDotNet2ClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CsharpDotNet2ClientOptionsProvider.java new file mode 100644 index 00000000000..cbbd7b2f093 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CsharpDotNet2ClientOptionsProvider.java @@ -0,0 +1,33 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.CsharpDotNet2ClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class CsharpDotNet2ClientOptionsProvider implements OptionsProvider { + public static final String PACKAGE_NAME_VALUE = "swagger_client_csharp_dotnet"; + public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String CLIENT_PACKAGE_VALUE = "IO.Swagger.Client.Test"; + + @Override + public String getLanguage() { + return "CsharpDotNet2"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) + .put(CsharpDotNet2ClientCodegen.CLIENT_PACKAGE, CLIENT_PACKAGE_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java new file mode 100644 index 00000000000..72066f54053 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java @@ -0,0 +1,41 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.DartClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class DartClientOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String BROWSER_CLIENT_VALUE = "true"; + public static final String PUB_NAME_VALUE = "swagger"; + public static final String PUB_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String PUB_DESCRIPTION_VALUE = "Swagger API client dart"; + public static final String SOURCE_FOLDER_VALUE = "src"; + + @Override + public String getLanguage() { + return "dart"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(DartClientCodegen.BROWSER_CLIENT, BROWSER_CLIENT_VALUE) + .put(DartClientCodegen.PUB_NAME, PUB_NAME_VALUE) + .put(DartClientCodegen.PUB_VERSION, PUB_VERSION_VALUE) + .put(DartClientCodegen.PUB_DESCRIPTION, PUB_DESCRIPTION_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/FlashClienOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/FlashClienOptionsProvider.java new file mode 100644 index 00000000000..1fcdc86271b --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/FlashClienOptionsProvider.java @@ -0,0 +1,34 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class FlashClienOptionsProvider implements OptionsProvider { + public static final String PACKAGE_NAME_VALUE = "io.swagger.flash"; + public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String INVOKER_PACKAGE_VALUE = "io.swagger.flash"; + public static final String SOURCE_FOLDER_VALUE = "src/main/flex/test"; + + @Override + public String getLanguage() { + return "flash"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaInflectorServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaInflectorServerOptionsProvider.java new file mode 100644 index 00000000000..25842a6fd7e --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaInflectorServerOptionsProvider.java @@ -0,0 +1,13 @@ +package io.swagger.codegen.options; + +public class JavaInflectorServerOptionsProvider extends JavaOptionsProvider { + @Override + public String getLanguage() { + return "inflector"; + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java new file mode 100644 index 00000000000..8ea7ee31452 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java @@ -0,0 +1,53 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.JavaClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class JavaOptionsProvider implements OptionsProvider { + public static final String ARTIFACT_ID_VALUE = "swagger-java-client-test"; + public static final String MODEL_PACKAGE_VALUE = "package"; + public static final String API_PACKAGE_VALUE = "apiPackage"; + public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; + public static final String SORT_PARAMS_VALUE = "false"; + public static final String GROUP_ID_VALUE = "io.swagger.test"; + public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; + public static final String LOCAL_PREFIX_VALUE = "tst"; + public static final String LIBRARY_VALUE = "jersey2"; + public static final String SERIALIZABLE_MODEL_VALUE = "false"; + public static final String FULL_JAVA_UTIL_VALUE = "true"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) + .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) + .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) + .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) + .put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE) + .put(CodegenConstants.LIBRARY, LIBRARY_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } + + @Override + public String getLanguage() { + return "java"; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java new file mode 100644 index 00000000000..0b735363b77 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java @@ -0,0 +1,13 @@ +package io.swagger.codegen.options; + +public class JaxRSServerOptionsProvider extends JavaOptionsProvider { + @Override + public boolean isServer() { + return true; + } + + @Override + public String getLanguage() { + return "jaxrs"; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java new file mode 100644 index 00000000000..3d49fcb8d01 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class NodeJSServerOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "nodejs"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java new file mode 100644 index 00000000000..2f76199e4f3 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ObjcClientOptionsProvider.java @@ -0,0 +1,41 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.ObjcClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class ObjcClientOptionsProvider implements OptionsProvider { + public static final String CLASS_PREFIX_VALUE = "SWGObjc"; + public static final String POD_NAME_VALUE = "SwaggerClientObjc"; + public static final String POD_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String AUTHOR_NAME_VALUE = "SwaggerObjc"; + public static final String AUTHOR_EMAIL_VALUE = "objc@swagger.io"; + public static final String GIT_REPO_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; + public static final String LICENSE_VALUE = "MIT"; + + @Override + public String getLanguage() { + return "objc"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(ObjcClientCodegen.CLASS_PREFIX, CLASS_PREFIX_VALUE) + .put(ObjcClientCodegen.POD_NAME, POD_NAME_VALUE) + .put(CodegenConstants.POD_VERSION, POD_VERSION_VALUE) + .put(ObjcClientCodegen.AUTHOR_NAME, AUTHOR_NAME_VALUE) + .put(ObjcClientCodegen.AUTHOR_EMAIL, AUTHOR_EMAIL_VALUE) + .put(ObjcClientCodegen.GIT_REPO_URL, GIT_REPO_URL_VALUE) + .put(ObjcClientCodegen.LICENSE, LICENSE_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/OptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/OptionsProvider.java new file mode 100644 index 00000000000..5521a78432b --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/OptionsProvider.java @@ -0,0 +1,9 @@ +package io.swagger.codegen.options; + +import java.util.Map; + +public interface OptionsProvider { + String getLanguage(); + Map createOptions(); + boolean isServer(); +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java new file mode 100644 index 00000000000..5ffe04bff2b --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java @@ -0,0 +1,34 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import io.swagger.codegen.languages.PerlClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class PerlClientOptionsProvider implements OptionsProvider { + public static final String MODULE_NAME_VALUE = ""; + public static final String MODULE_VERSION_VALUE = ""; + + @Override + public String getLanguage() { + return "perl"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(PerlClientCodegen.MODULE_NAME, MODULE_NAME_VALUE) + .put(PerlClientCodegen.MODULE_VERSION, MODULE_VERSION_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "true") + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java new file mode 100644 index 00000000000..dcd7a06438f --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java @@ -0,0 +1,49 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.PhpClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class PhpClientOptionsProvider implements OptionsProvider { + public static final String MODEL_PACKAGE_VALUE = "package"; + public static final String API_PACKAGE_VALUE = "apiPackage"; + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String VARIABLE_NAMING_CONVENTION_VALUE = "snake_case"; + public static final String INVOKER_PACKAGE_VALUE = "Swagger\\Client\\Php"; + public static final String PACKAGE_PATH_VALUE = "SwaggerClient-php"; + public static final String SRC_BASE_PATH_VALUE = "libPhp"; + public static final String COMPOSER_VENDOR_NAME_VALUE = "swaggerPhp"; + public static final String COMPOSER_PROJECT_NAME_VALUE = "swagger-client-php"; + public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + + @Override + public String getLanguage() { + return "php"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(PhpClientCodegen.VARIABLE_NAMING_CONVENTION, VARIABLE_NAMING_CONVENTION_VALUE) + .put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE) + .put(PhpClientCodegen.PACKAGE_PATH, PACKAGE_PATH_VALUE) + .put(PhpClientCodegen.SRC_BASE_PATH, SRC_BASE_PATH_VALUE) + .put(PhpClientCodegen.COMPOSER_VENDOR_NAME, COMPOSER_VENDOR_NAME_VALUE) + .put(PhpClientCodegen.COMPOSER_PROJECT_NAME, COMPOSER_PROJECT_NAME_VALUE) + .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java new file mode 100644 index 00000000000..ec62e3f2b7c --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java @@ -0,0 +1,31 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class PythonClientOptionsProvider implements OptionsProvider { + public static final String PACKAGE_NAME_VALUE = "swagger_client_python"; + public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; + + @Override + public String getLanguage() { + return "python"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Qt5CPPOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Qt5CPPOptionsProvider.java new file mode 100644 index 00000000000..05f9f1f068c --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Qt5CPPOptionsProvider.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class Qt5CPPOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "qt5cpp"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java new file mode 100644 index 00000000000..d80341f0200 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java @@ -0,0 +1,37 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.RubyClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class RubyClientOptionsProvider implements OptionsProvider { + public static final String GEM_NAME_VALUE = "swagger_client_ruby"; + public static final String MODULE_NAME_VALUE = "SwaggerClientRuby"; + public static final String GEM_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "ruby"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(RubyClientCodegen.GEM_NAME, GEM_NAME_VALUE) + .put(RubyClientCodegen.MODULE_NAME, MODULE_NAME_VALUE) + .put(RubyClientCodegen.GEM_VERSION, GEM_VERSION_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java new file mode 100644 index 00000000000..867482f145b --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java @@ -0,0 +1,34 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class ScalaClientOptionsProvider implements OptionsProvider { + public static final String MODEL_PACKAGE_VALUE = "package"; + public static final String API_PACKAGE_VALUE = "apiPackage"; + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "scala"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java new file mode 100644 index 00000000000..a0fef2f4858 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java @@ -0,0 +1,34 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class ScalatraServerOptionsProvider implements OptionsProvider { + public static final String MODEL_PACKAGE_VALUE = "package"; + public static final String API_PACKAGE_VALUE = "apiPackage"; + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "scalatra"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SilexServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SilexServerOptionsProvider.java new file mode 100644 index 00000000000..ae6596923d2 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SilexServerOptionsProvider.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class SilexServerOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "silex-PHP"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SinatraServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SinatraServerOptionsProvider.java new file mode 100644 index 00000000000..d4a830dc203 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SinatraServerOptionsProvider.java @@ -0,0 +1,23 @@ +package io.swagger.codegen.options; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class SinatraServerOptionsProvider implements OptionsProvider { + @Override + public String getLanguage() { + return "sinatra"; + } + + @Override + public Map createOptions() { + //SinatraServerCodegen doesn't have its own options and base options are cleared + return ImmutableMap.of(); + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringMVCServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringMVCServerOptionsProvider.java new file mode 100644 index 00000000000..13a3600918d --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringMVCServerOptionsProvider.java @@ -0,0 +1,27 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.languages.SpringMVCServerCodegen; + +import java.util.HashMap; +import java.util.Map; + +public class SpringMVCServerOptionsProvider extends JavaOptionsProvider { + public static final String CONFIG_PACKAGE_VALUE = "configPackage"; + + @Override + public String getLanguage() { + return "spring-mvc"; + } + + @Override + public Map createOptions() { + Map options = new HashMap(super.createOptions()); + options.put(SpringMVCServerCodegen.CONFIG_PACKAGE, CONFIG_PACKAGE_VALUE); + return options; + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticDocOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticDocOptionsProvider.java new file mode 100644 index 00000000000..5e198a0e91a --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticDocOptionsProvider.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class StaticDocOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "dynamic-html"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java new file mode 100644 index 00000000000..f236ff40dc0 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class StaticHtmlOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "html"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerOptionsProvider.java new file mode 100644 index 00000000000..e97860e83ab --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerOptionsProvider.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class SwaggerOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "swagger"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java new file mode 100644 index 00000000000..ff5daa86797 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class SwaggerYamlOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "swagger-yaml"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java new file mode 100644 index 00000000000..507d3b62829 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java @@ -0,0 +1,60 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.SwiftCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class SwiftOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String PROJECT_NAME_VALUE = "Swagger"; + public static final String RESPONSE_AS_VALUE = "test"; + public static final String UNWRAP_REQUIRED_VALUE = "true"; + public static final String POD_SOURCE_VALUE = "{ :git => 'git@github.com:swagger-api/swagger-mustache.git'," + + " :tag => 'v1.0.0-SNAPSHOT' }"; + public static final String POD_VERSION_VALUE = "v1.0.0-SNAPSHOT"; + public static final String POD_AUTHORS_VALUE = "podAuthors"; + public static final String POD_SOCIAL_MEDIA_URL_VALUE = "podSocialMediaURL"; + public static final String POD_DOCSET_URL_VALUE = "podDocsetURL"; + public static final String POD_LICENSE_VALUE = "'Apache License, Version 2.0'"; + public static final String POD_HOMEPAGE_VALUE = "podHomepage"; + public static final String POD_SUMMARY_VALUE = "podSummary"; + public static final String POD_DESCRIPTION_VALUE = "podDescription"; + public static final String POD_SCREENSHOTS_VALUE = "podScreenshots"; + public static final String POD_DOCUMENTATION_URL_VALUE = "podDocumentationURL"; + + @Override + public String getLanguage() { + return "swift"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(SwiftCodegen.PROJECT_NAME, PROJECT_NAME_VALUE) + .put(SwiftCodegen.RESPONSE_AS, RESPONSE_AS_VALUE) + .put(SwiftCodegen.UNWRAP_REQUIRED, UNWRAP_REQUIRED_VALUE) + .put(SwiftCodegen.POD_SOURCE, POD_SOURCE_VALUE) + .put(CodegenConstants.POD_VERSION, POD_VERSION_VALUE) + .put(SwiftCodegen.POD_AUTHORS, POD_AUTHORS_VALUE) + .put(SwiftCodegen.POD_SOCIAL_MEDIA_URL, POD_SOCIAL_MEDIA_URL_VALUE) + .put(SwiftCodegen.POD_DOCSET_URL, POD_DOCSET_URL_VALUE) + .put(SwiftCodegen.POD_LICENSE, POD_LICENSE_VALUE) + .put(SwiftCodegen.POD_HOMEPAGE, POD_HOMEPAGE_VALUE) + .put(SwiftCodegen.POD_SUMMARY, POD_SUMMARY_VALUE) + .put(SwiftCodegen.POD_DESCRIPTION, POD_DESCRIPTION_VALUE) + .put(SwiftCodegen.POD_SCREENSHOTS, POD_SCREENSHOTS_VALUE) + .put(SwiftCodegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TizenClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TizenClientOptionsProvider.java new file mode 100644 index 00000000000..ff8659627f4 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TizenClientOptionsProvider.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class TizenClientOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "tizen"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java new file mode 100644 index 00000000000..d7d4e5392fc --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "typescript-angular"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java new file mode 100644 index 00000000000..e1c0259222e --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { + public static final String SORT_PARAMS_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + + @Override + public String getLanguage() { + return "typescript-node"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java new file mode 100644 index 00000000000..d85b0c9dbc1 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/perl/PerlClientOptionsTest.java @@ -0,0 +1,34 @@ +package io.swagger.codegen.perl; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.PerlClientCodegen; +import io.swagger.codegen.options.PerlClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class PerlClientOptionsTest extends AbstractOptionsTest { + + @Tested + private PerlClientCodegen clientCodegen; + + public PerlClientOptionsTest() { + super(new PerlClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModuleName(PerlClientOptionsProvider.MODULE_NAME_VALUE); + times = 1; + clientCodegen.setModuleVersion(PerlClientOptionsProvider.MODULE_VERSION_VALUE); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java new file mode 100644 index 00000000000..e50185a3e8d --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpClientOptionsTest.java @@ -0,0 +1,50 @@ +package io.swagger.codegen.php; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.PhpClientCodegen; +import io.swagger.codegen.options.PhpClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class PhpClientOptionsTest extends AbstractOptionsTest { + + @Tested + private PhpClientCodegen clientCodegen; + + public PhpClientOptionsTest() { + super(new PhpClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(PhpClientOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(PhpClientOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(PhpClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setParameterNamingConvention(PhpClientOptionsProvider.VARIABLE_NAMING_CONVENTION_VALUE); + times = 1; + clientCodegen.setInvokerPackage(PhpClientOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setPackagePath(PhpClientOptionsProvider.PACKAGE_PATH_VALUE); + times = 1; + clientCodegen.setSrcBasePath(PhpClientOptionsProvider.SRC_BASE_PATH_VALUE); + times = 1; + clientCodegen.setComposerVendorName(PhpClientOptionsProvider.COMPOSER_VENDOR_NAME_VALUE); + times = 1; + clientCodegen.setComposerProjectName(PhpClientOptionsProvider.COMPOSER_PROJECT_NAME_VALUE); + times = 1; + clientCodegen.setArtifactVersion(PhpClientOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java new file mode 100644 index 00000000000..fc68a9e92e1 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java @@ -0,0 +1,34 @@ +package io.swagger.codegen.python; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.PythonClientCodegen; +import io.swagger.codegen.options.PythonClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class PythonClientOptionsTest extends AbstractOptionsTest { + + @Tested + private PythonClientCodegen clientCodegen; + + public PythonClientOptionsTest() { + super(new PythonClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setPackageName(PythonClientOptionsProvider.PACKAGE_NAME_VALUE); + times = 1; + clientCodegen.setPackageVersion(PythonClientOptionsProvider.PACKAGE_VERSION_VALUE); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java new file mode 100644 index 00000000000..389721d3841 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/qtfivecpp/Qt5CPPOptionsTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.qtfivecpp; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.Qt5CPPGenerator; +import io.swagger.codegen.options.Qt5CPPOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class Qt5CPPOptionsTest extends AbstractOptionsTest { + + @Tested + private Qt5CPPGenerator clientCodegen; + + public Qt5CPPOptionsTest() { + super(new Qt5CPPOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(Qt5CPPOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java new file mode 100644 index 00000000000..b679de923c8 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java @@ -0,0 +1,36 @@ +package io.swagger.codegen.ruby; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.RubyClientCodegen; +import io.swagger.codegen.options.RubyClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class RubyClientOptionsTest extends AbstractOptionsTest { + + @Tested + private RubyClientCodegen clientCodegen; + + public RubyClientOptionsTest() { + super(new RubyClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setGemName(RubyClientOptionsProvider.GEM_NAME_VALUE); + times = 1; + clientCodegen.setModuleName(RubyClientOptionsProvider.MODULE_NAME_VALUE); + times = 1; + clientCodegen.setGemVersion(RubyClientOptionsProvider.GEM_VERSION_VALUE); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java new file mode 100644 index 00000000000..0e916aebd76 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaClientOptionsTest.java @@ -0,0 +1,36 @@ +package io.swagger.codegen.scala; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.ScalaClientCodegen; +import io.swagger.codegen.options.ScalaClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class ScalaClientOptionsTest extends AbstractOptionsTest { + + @Tested + private ScalaClientCodegen clientCodegen; + + public ScalaClientOptionsTest() { + super(new ScalaClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(ScalaClientOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(ScalaClientOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(ScalaClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java new file mode 100644 index 00000000000..49bbe4373b6 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scalatra/ScalatraServerOptionsTest.java @@ -0,0 +1,36 @@ +package io.swagger.codegen.scalatra; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.ScalatraServerCodegen; +import io.swagger.codegen.options.ScalatraServerOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class ScalatraServerOptionsTest extends AbstractOptionsTest { + + @Tested + private ScalatraServerCodegen clientCodegen; + + public ScalatraServerOptionsTest() { + super(new ScalatraServerOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(ScalatraServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(ScalatraServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(ScalatraServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java new file mode 100644 index 00000000000..11681230289 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/silex/SilexServerOptionsTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.silex; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.SilexServerCodegen; +import io.swagger.codegen.options.SilexServerOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class SilexServerOptionsTest extends AbstractOptionsTest { + + @Tested + private SilexServerCodegen clientCodegen; + + public SilexServerOptionsTest() { + super(new SilexServerOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SilexServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java new file mode 100644 index 00000000000..6691cf27f86 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/sinatra/SinatraServerOptionsTest.java @@ -0,0 +1,30 @@ +package io.swagger.codegen.sinatra; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.SinatraServerCodegen; +import io.swagger.codegen.options.SinatraServerOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class SinatraServerOptionsTest extends AbstractOptionsTest { + + @Tested + private SinatraServerCodegen clientCodegen; + + public SinatraServerOptionsTest() { + super(new SinatraServerOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/springmvc/SpringMVCServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/springmvc/SpringMVCServerOptionsTest.java new file mode 100644 index 00000000000..d4b984ffcd2 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/springmvc/SpringMVCServerOptionsTest.java @@ -0,0 +1,56 @@ +package io.swagger.codegen.springmvc; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.java.JavaClientOptionsTest; +import io.swagger.codegen.languages.SpringMVCServerCodegen; +import io.swagger.codegen.options.SpringMVCServerOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class SpringMVCServerOptionsTest extends JavaClientOptionsTest { + + @Tested + private SpringMVCServerCodegen clientCodegen; + + public SpringMVCServerOptionsTest() { + super(new SpringMVCServerOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(SpringMVCServerOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(SpringMVCServerOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SpringMVCServerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(SpringMVCServerOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(SpringMVCServerOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(SpringMVCServerOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(SpringMVCServerOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(SpringMVCServerOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(SpringMVCServerOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(SpringMVCServerOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setLibrary(SpringMVCServerOptionsProvider.LIBRARY_VALUE); + times = 1; + clientCodegen.setFullJavaUtil(Boolean.valueOf(SpringMVCServerOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + clientCodegen.setConfigPackage(SpringMVCServerOptionsProvider.CONFIG_PACKAGE_VALUE); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java new file mode 100644 index 00000000000..bc2da143efb --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticDocOptionsTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.staticDocs; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.StaticDocCodegen; +import io.swagger.codegen.options.StaticDocOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class StaticDocOptionsTest extends AbstractOptionsTest { + + @Tested + private StaticDocCodegen clientCodegen; + + public StaticDocOptionsTest() { + super(new StaticDocOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(StaticDocOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java new file mode 100644 index 00000000000..befe62e32c4 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlOptionsTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.statichtml; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.StaticHtmlGenerator; +import io.swagger.codegen.options.StaticHtmlOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class StaticHtmlOptionsTest extends AbstractOptionsTest { + + @Tested + private StaticHtmlGenerator clientCodegen; + + public StaticHtmlOptionsTest() { + super(new StaticHtmlOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(StaticHtmlOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java new file mode 100644 index 00000000000..f2f461f2b70 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swagger/SwaggerOptionsTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.swagger; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.SwaggerGenerator; +import io.swagger.codegen.options.SwaggerOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class SwaggerOptionsTest extends AbstractOptionsTest { + + @Tested + private SwaggerGenerator clientCodegen; + + public SwaggerOptionsTest() { + super(new SwaggerOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SwaggerOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java new file mode 100644 index 00000000000..a1478a8ba05 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swaggeryaml/SwaggerYamlOptionsTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.swaggeryaml; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.SwaggerYamlGenerator; +import io.swagger.codegen.options.SwaggerYamlOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class SwaggerYamlOptionsTest extends AbstractOptionsTest { + + @Tested + private SwaggerYamlGenerator clientCodegen; + + public SwaggerYamlOptionsTest() { + super(new SwaggerYamlOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SwaggerYamlOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java new file mode 100644 index 00000000000..7d3504f67de --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftOptionsTest.java @@ -0,0 +1,38 @@ +package io.swagger.codegen.swift; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.SwiftCodegen; +import io.swagger.codegen.options.SwiftOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class SwiftOptionsTest extends AbstractOptionsTest { + + @Tested + private SwiftCodegen clientCodegen; + + public SwiftOptionsTest() { + super(new SwiftOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SwiftOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setProjectName(SwiftOptionsProvider.PROJECT_NAME_VALUE); + times = 1; + clientCodegen.setResponseAs(SwiftOptionsProvider.RESPONSE_AS_VALUE.split(",")); + times = 1; + clientCodegen.setUnwrapRequired(Boolean.valueOf(SwiftOptionsProvider.UNWRAP_REQUIRED_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java new file mode 100644 index 00000000000..83ebb8be15e --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/tizen/TizenClientOptionsTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.tizen; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.TizenClientCodegen; +import io.swagger.codegen.options.TizenClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class TizenClientOptionsTest extends AbstractOptionsTest { + + @Tested + private TizenClientCodegen clientCodegen; + + public TizenClientOptionsTest() { + super(new TizenClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TizenClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java new file mode 100644 index 00000000000..3fdf817dc58 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularClientOptionsTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.typescriptangular; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.TypeScriptAngularClientCodegen; +import io.swagger.codegen.options.TypeScriptAngularClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class TypeScriptAngularClientOptionsTest extends AbstractOptionsTest { + + @Tested + private TypeScriptAngularClientCodegen clientCodegen; + + public TypeScriptAngularClientOptionsTest() { + super(new TypeScriptAngularClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptAngularClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java new file mode 100644 index 00000000000..2374011b1b9 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeClientOptionsTest.java @@ -0,0 +1,32 @@ +package io.swagger.codegen.typescriptnode; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.TypeScriptNodeClientCodegen; +import io.swagger.codegen.options.TypeScriptNodeClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class TypeScriptNodeClientOptionsTest extends AbstractOptionsTest { + + @Tested + private TypeScriptNodeClientCodegen clientCodegen; + + public TypeScriptNodeClientOptionsTest() { + super(new TypeScriptNodeClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + }}; + } +} diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index 4f8794c331b..bfdb17e9f0e 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -149,6 +149,13 @@ swagger-codegen ${project.parent.version} + + io.swagger + swagger-codegen + ${project.parent.version} + test-jar + test + ch.qos.logback logback-classic diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java index a13995505c7..018d3416149 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java @@ -16,15 +16,14 @@ package io.swagger.generator; -import java.io.IOException; -import java.io.InputStream; +import org.apache.commons.io.IOUtils; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; - -import org.apache.commons.io.IOUtils; +import java.io.IOException; +import java.io.InputStream; public class Bootstrap extends HttpServlet { public void init(ServletConfig config) throws ServletException { @@ -50,8 +49,17 @@ public class Bootstrap extends HttpServlet { } } - bc.setSchemes(new String[]{"https"}); - bc.setHost("generator.swagger.io"); + String host = config.getInitParameter("generator.host"); + if(host == null) { + host = "generator.swagger.io"; + } + bc.setHost(host); + + String scheme = config.getInitParameter("generator.protocol"); + if(host == null) { + scheme = "https"; + } + bc.setSchemes(new String[]{scheme}); bc.setLicenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html"); bc.setResourcePackage("io.swagger.generator.resource"); bc.setScan(true); diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java b/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java index ee5792850c5..974b938a1aa 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java @@ -26,35 +26,36 @@ public class DynamicSwaggerConfig extends BeanConfig { Parameter framework = post.getParameters().get(0); if (framework instanceof PathParameter) { PathParameter param = (PathParameter) framework; - StringBuilder b = new StringBuilder(); - for (String client : clients) { - if (b.toString().length() > 0) { - b.append(", "); - } - b.append(client); - } - param.setDescription("available clients: " + b.toString()); param.setEnum(clients); } + + Operation get = clientPath.getGet(); + if(get != null) { + framework = get.getParameters().get(0); + if (framework instanceof PathParameter) { + PathParameter param = (PathParameter) framework; + param.setEnum(clients); + } + } } Path serverPath = swagger.getPaths().get("/gen/servers/{framework}"); - // update the path description based on what servers are available via SPI if (serverPath != null) { Operation post = serverPath.getPost(); Parameter framework = post.getParameters().get(0); if (framework instanceof PathParameter) { PathParameter param = (PathParameter) framework; - StringBuilder b = new StringBuilder(); - for (String server : servers) { - if (b.toString().length() > 0) { - b.append(", "); - } - b.append(server); - } - param.setDescription("available servers: " + b.toString()); param.setEnum(servers); } + + Operation get = serverPath.getGet(); + if(get != null) { + framework = get.getParameters().get(0); + if (framework instanceof PathParameter) { + PathParameter param = (PathParameter) framework; + param.setEnum(servers); + } + } } return swagger.info(getInfo()) diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java index 2a653888625..5175ac3b60a 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/GeneratorInput.java @@ -29,6 +29,7 @@ public class GeneratorInput { this.options = options; } + @ApiModelProperty(example = "http://petstore.swagger.io/v2/swagger.json") public String getSwaggerUrl() { return swaggerUrl; } diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java index ad5b9cdec8f..0fcc5312dac 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ResponseCode.java @@ -1,5 +1,7 @@ package io.swagger.generator.model; +import io.swagger.annotations.ApiModelProperty; + public class ResponseCode { private String code; private String link; @@ -12,6 +14,7 @@ public class ResponseCode { setLink(link); } + @ApiModelProperty(value = "File download code", example = "d40029be-eda6-4d62-b1ef-d05e2e91a72a") public String getCode() { return code; } @@ -20,6 +23,7 @@ public class ResponseCode { this.code = code; } + @ApiModelProperty(value = "URL for fetching the generated client", example = "http://generator.swagger.io:80/api/gen/download/d40029be-eda6-4d62-b1ef-d05e2e91a72a") public String getLink() { return link; } diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java index 6e17c38218e..9946831640d 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java @@ -1,6 +1,8 @@ package io.swagger.generator.online; import com.fasterxml.jackson.databind.JsonNode; + +import io.swagger.codegen.CliOption; import io.swagger.codegen.ClientOptInput; import io.swagger.codegen.ClientOpts; import io.swagger.codegen.Codegen; @@ -14,17 +16,33 @@ import io.swagger.generator.util.ZipUtil; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; import io.swagger.util.Json; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class Generator { static Logger LOGGER = LoggerFactory.getLogger(Generator.class); + public static Map getOptions(String language) throws ApiException { + CodegenConfig config = null; + try { + config = CodegenConfigLoader.forName(language); + } catch (Exception e) { + throw new BadRequestException(400, String.format("Unsupported target %s supplied. %s", language, e)); + } + Map map = new LinkedHashMap(); + for (CliOption option : config.cliOptions()) { + map.put(option.getOpt(), option); + } + return map; + } + public enum Type { CLIENT("client"), SERVER("server"); @@ -54,6 +72,10 @@ public class Generator { throw new BadRequestException(400, "No options were supplied"); } JsonNode node = opts.getSpec(); + if(node != null && "{}".equals(node.toString())) { + LOGGER.debug("ignoring empty spec"); + node = null; + } Swagger swagger; if (node == null) { if (opts.getSwaggerUrl() != null) { @@ -86,14 +108,13 @@ public class Generator { } if (opts.getOptions() != null) { - for (Map.Entry entry : opts.getOptions().entrySet()) { - codegenConfig.additionalProperties().put(entry.getKey(), entry.getValue()); - } + codegenConfig.additionalProperties().putAll(opts.getOptions()); + codegenConfig.additionalProperties().put("swagger", swagger); } codegenConfig.setOutputDir(outputFolder); - Json.prettyPrint(clientOpts); + LOGGER.debug(Json.pretty(clientOpts)); clientOptInput.setConfig(codegenConfig); @@ -108,6 +129,20 @@ public class Generator { } else { throw new BadRequestException(400, "A target generation was attempted, but no files were created!"); } + for(File file: files) { + try { + file.delete(); + } + catch(Exception e) { + LOGGER.error("unable to delete file " + file.getAbsolutePath()); + } + } + try { + new File(outputFolder).delete(); + } + catch (Exception e) { + LOGGER.error("unable to delete output folder " + outputFolder); + } } catch (Exception e) { throw new BadRequestException(500, "Unable to build target: " + e.getMessage()); } diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java index fa6a4785c5b..343692f8385 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java @@ -3,6 +3,7 @@ package io.swagger.generator.resource; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; +import io.swagger.codegen.CliOption; import io.swagger.codegen.Codegen; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenType; @@ -11,16 +12,14 @@ import io.swagger.generator.model.Generated; import io.swagger.generator.model.GeneratorInput; import io.swagger.generator.model.ResponseCode; import io.swagger.generator.online.Generator; +import org.apache.commons.io.FileUtils; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; import javax.ws.rs.core.Context; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.servlet.http.HttpServletRequest; +import java.io.File; import java.util.*; @Path("/gen") @@ -34,6 +33,9 @@ public class SwaggerResource { @Path("/download/{fileId}") @Produces({MediaType.APPLICATION_OCTET_STREAM}) @ApiOperation(value = "Downloads a pre-generated file", + notes = "A valid `fileId` is generated by the `/clients/{language}` or `/servers/{language}` POST " + + "operations. The fileId code can be used just once, after which a new `fileId` will need to " + + "be requested.", response = String.class, tags = {"clients", "servers"}) public Response downloadFile(@PathParam("fileId") String fileId) throws Exception { @@ -41,7 +43,15 @@ public class SwaggerResource { System.out.println("looking for fileId " + fileId); System.out.println("got filename " + g.getFilename()); if (g.getFilename() != null) { - byte[] bytes = org.apache.commons.io.FileUtils.readFileToByteArray(new java.io.File(g.getFilename())); + File file = new java.io.File(g.getFilename()); + byte[] bytes = org.apache.commons.io.FileUtils.readFileToByteArray(file); + + try { + FileUtils.deleteDirectory(file.getParentFile()); + } + catch (Exception e) { + System.out.println("failed to delete file " + file.getAbsolutePath()); + } return Response.ok(bytes, "application/zip") .header("Content-Disposition", "attachment; filename=\"" + g.getFriendlyName() + "-generated.zip\"") @@ -56,7 +66,8 @@ public class SwaggerResource { @POST @Path("/clients/{language}") @ApiOperation( - value = "Generates a client library based on the config", + value = "Generates a client library", + notes = "Accepts a `GeneratorInput` options map for spec location and generation options", response = ResponseCode.class, tags = "clients") public Response generateClient( @@ -77,7 +88,7 @@ public class SwaggerResource { String host = scheme + "://" + request.getServerName() + port; if (filename != null) { - String code = String.valueOf(System.currentTimeMillis()); + String code = String.valueOf(UUID.randomUUID().toString()); Generated g = new Generated(); g.setFilename(filename); g.setFriendlyName(language + "-client"); @@ -90,6 +101,50 @@ public class SwaggerResource { } } + @GET + @Path("/clients/{language}") + @Produces({MediaType.APPLICATION_JSON}) + @ApiOperation( + value = "Returns options for a client library", + response = CliOption.class, + responseContainer = "map", + tags = "clients") + public Response getClientOptions( + @Context HttpServletRequest request, + @ApiParam(value = "The target language for the client library", required = true) + @PathParam("language") String language) throws Exception { + + Map opts = Generator.getOptions(language); + + if (opts != null) { + return Response.ok().entity(opts).build(); + } else { + return Response.status(404).build(); + } + } + + @GET + @Path("/servers/{framework}") + @Produces({MediaType.APPLICATION_JSON}) + @ApiOperation( + value = "Returns options for a server framework", + response = CliOption.class, + responseContainer = "map", + tags = "servers") + public Response getServerOptions( + @Context HttpServletRequest request, + @ApiParam(value = "The target language for the server framework", required = true) + @PathParam("framework") String framework) throws Exception { + + Map opts = Generator.getOptions(framework); + + if (opts != null) { + return Response.ok().entity(opts).build(); + } else { + return Response.status(404).build(); + } + } + @GET @Path("/clients") @ApiOperation(value = "Gets languages supported by the client generator", @@ -116,7 +171,8 @@ public class SwaggerResource { @POST @Path("/servers/{framework}") - @ApiOperation(value = "Generates a server library for the supplied server framework", + @ApiOperation(value = "Generates a server library", + notes = "Accepts a `GeneratorInput` options map for spec location and generation options.", response = ResponseCode.class, tags = "servers") public Response generateServerForLanguage( @@ -133,7 +189,7 @@ public class SwaggerResource { String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); if (filename != null) { - String code = String.valueOf(System.currentTimeMillis()); + String code = String.valueOf(UUID.randomUUID().toString()); Generated g = new Generated(); g.setFilename(filename); g.setFriendlyName(framework + "-server"); diff --git a/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml b/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml index b7e33258a5f..74e3828a8f4 100644 --- a/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml +++ b/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml @@ -42,6 +42,14 @@ Bootstrap io.swagger.generator.Bootstrap 2 + + generator.host + localhost:8001 + + + generator.protocol + http + ApiOriginFilter diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java index e6eb42abb35..fc015f433ea 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineGeneratorOptionsTest.java @@ -1,37 +1,94 @@ package io.swagger.generator.online; +import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.assertNotNull; +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfigLoader; +import io.swagger.codegen.options.AkkaScalaClientOptionsProvider; +import io.swagger.codegen.options.AndroidClientOptionsProvider; +import io.swagger.codegen.options.AsyncScalaClientOptionsProvider; +import io.swagger.codegen.options.CSharpClientOptionsProvider; +import io.swagger.codegen.options.CsharpDotNet2ClientOptionsProvider; +import io.swagger.codegen.options.DartClientOptionsProvider; +import io.swagger.codegen.options.FlashClienOptionsProvider; +import io.swagger.codegen.options.JavaInflectorServerOptionsProvider; +import io.swagger.codegen.options.JavaOptionsProvider; +import io.swagger.codegen.options.JaxRSServerOptionsProvider; +import io.swagger.codegen.options.NodeJSServerOptionsProvider; +import io.swagger.codegen.options.ObjcClientOptionsProvider; +import io.swagger.codegen.options.OptionsProvider; +import io.swagger.codegen.options.PerlClientOptionsProvider; +import io.swagger.codegen.options.PhpClientOptionsProvider; +import io.swagger.codegen.options.PythonClientOptionsProvider; +import io.swagger.codegen.options.Qt5CPPOptionsProvider; +import io.swagger.codegen.options.RubyClientOptionsProvider; +import io.swagger.codegen.options.ScalaClientOptionsProvider; +import io.swagger.codegen.options.ScalatraServerOptionsProvider; +import io.swagger.codegen.options.SilexServerOptionsProvider; +import io.swagger.codegen.options.SinatraServerOptionsProvider; +import io.swagger.codegen.options.SpringMVCServerOptionsProvider; +import io.swagger.codegen.options.StaticDocOptionsProvider; +import io.swagger.codegen.options.StaticHtmlOptionsProvider; +import io.swagger.codegen.options.SwaggerOptionsProvider; +import io.swagger.codegen.options.SwaggerYamlOptionsProvider; +import io.swagger.codegen.options.SwiftOptionsProvider; +import io.swagger.codegen.options.TizenClientOptionsProvider; +import io.swagger.codegen.options.TypeScriptAngularClientOptionsProvider; +import io.swagger.codegen.options.TypeScriptNodeClientOptionsProvider; import io.swagger.generator.exception.ApiException; import io.swagger.generator.model.GeneratorInput; -import io.swagger.generator.online.Generator; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Function; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Objects; -public abstract class OnlineGeneratorOptionsTest { - private final boolean isServer; - private final String language; +import javax.annotation.Nullable; - protected OnlineGeneratorOptionsTest(String language, boolean isServer) { - this.language = language; - this.isServer = isServer; +public class OnlineGeneratorOptionsTest { + private static final String OPTIONS_PROVIDER = "optionsProvider"; + + @DataProvider(name = OPTIONS_PROVIDER) + private Object[][] listOptions() { + return new Object[][]{{new AkkaScalaClientOptionsProvider()}, {new AndroidClientOptionsProvider()}, + {new AsyncScalaClientOptionsProvider()}, {new CSharpClientOptionsProvider()}, + {new CsharpDotNet2ClientOptionsProvider()}, {new DartClientOptionsProvider()}, + {new FlashClienOptionsProvider()}, {new JavaInflectorServerOptionsProvider()}, + {new JavaOptionsProvider()}, {new JaxRSServerOptionsProvider()}, + {new NodeJSServerOptionsProvider()}, {new ObjcClientOptionsProvider()}, + {new PerlClientOptionsProvider()}, {new PhpClientOptionsProvider()}, + {new PythonClientOptionsProvider()}, {new Qt5CPPOptionsProvider()}, + {new RubyClientOptionsProvider()}, {new ScalaClientOptionsProvider()}, + {new ScalatraServerOptionsProvider()}, {new SilexServerOptionsProvider()}, + {new SinatraServerOptionsProvider()}, {new SpringMVCServerOptionsProvider()}, + {new StaticDocOptionsProvider()}, {new StaticHtmlOptionsProvider()}, + {new SwaggerOptionsProvider()}, {new SwaggerYamlOptionsProvider()}, + {new SwiftOptionsProvider()}, {new TizenClientOptionsProvider()}, + {new TypeScriptAngularClientOptionsProvider()}, {new TypeScriptNodeClientOptionsProvider()} + }; } - @Test - public void optionsTest() throws ApiException, IOException { + @Test(dataProvider = OPTIONS_PROVIDER) + public void generateOptionsTest(OptionsProvider provider) throws ApiException, IOException { final GeneratorInput input = new GeneratorInput(); - final HashMap options = convertOptions(); + final HashMap options = convertOptions(provider); final Maps.EntryTransformer transformer = new Maps.EntryTransformer() { @@ -44,10 +101,10 @@ public abstract class OnlineGeneratorOptionsTest { final ObjectMapper mapper = new ObjectMapper(); input.setSpec(mapper.readTree(loadClassResource(getClass(), "petstore.json"))); String outputFilename; - if (isServer) { - outputFilename = Generator.generateServer(language, input); + if (provider.isServer()) { + outputFilename = Generator.generateServer(provider.getLanguage(), input); } else { - outputFilename = Generator.generateClient(language, input); + outputFilename = Generator.generateClient(provider.getLanguage(), input); } final File dir = new File(new File(outputFilename).getParent()); FileUtils.deleteDirectory(dir); @@ -57,11 +114,9 @@ public abstract class OnlineGeneratorOptionsTest { } } - protected abstract Map getOptions(); - - private HashMap convertOptions() { + private HashMap convertOptions(OptionsProvider provider) { HashMap options = new HashMap(); - for (Map.Entry entry : getOptions().entrySet()) { + for (Map.Entry entry : provider.createOptions().entrySet()) { options.put(entry.getKey(), new InvocationCounter(entry.getValue())); } return options; @@ -94,4 +149,53 @@ public abstract class OnlineGeneratorOptionsTest { return value; } } + + @Test(dataProvider = OPTIONS_PROVIDER) + public void getOptionsTest(OptionsProvider provider) throws ApiException { + final Map opts = Generator.getOptions(provider.getLanguage()); + + final Function cliOptionWrapper = new Function() { + @Nullable + @Override + public CliOptionProxy apply(@Nullable CliOption option) { + return new CliOptionProxy(option); + } + }; + + final List actual = Lists.transform(new ArrayList(opts.values()), cliOptionWrapper); + final List expected = Lists.transform( + CodegenConfigLoader.forName(provider.getLanguage()).cliOptions(), cliOptionWrapper); + assertEquals(actual, expected); + } + + private static class CliOptionProxy { + private final CliOption wrapped; + + public CliOptionProxy(CliOption wrapped){ + this.wrapped = wrapped; + } + + public CliOption getWrapped() { + return wrapped; + } + + @Override + public int hashCode() { + return Objects.hash(wrapped.getOpt(), wrapped.getDescription(), wrapped.getType(), + wrapped.getDefault(), wrapped.getEnum()); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof CliOptionProxy) { + final CliOption that = ((CliOptionProxy) obj).getWrapped(); + return Objects.equals(wrapped.getOpt(), that.getOpt()) + && Objects.equals(wrapped.getDescription(), that.getDescription()) + && Objects.equals(wrapped.getType(), that.getType()) + && Objects.equals(wrapped.getDefault(), that.getDefault()) + && Objects.equals(wrapped.getEnum(), that.getEnum()); + } + return false; + } + } } diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java index 50605cff110..93277a6a2f9 100644 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java @@ -1,34 +1,26 @@ package io.swagger.generator.online; -import com.google.common.collect.ImmutableMap; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.codegen.options.JavaOptionsProvider; +import io.swagger.generator.exception.ApiException; + +import org.testng.annotations.Test; import java.util.Map; -public class OnlineJavaClientOptionsTest extends OnlineGeneratorOptionsTest { +public class OnlineJavaClientOptionsTest { - public OnlineJavaClientOptionsTest() { - super("java", false); - } - - protected OnlineJavaClientOptionsTest(String language, boolean isServer) { - super(language, isServer); - } - - @Override - protected Map getOptions() { - ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put("modelPackage", "package") - .put("apiPackage", "apiPackage") - .put("sortParamsByRequiredFlag", "false") - .put("invokerPackage", "io.swagger.client.test") - .put("groupId", "io.swagger.test") - .put("artifactId", "swagger-java-client-test") - .put("artifactVersion", "1.0.0-SNAPSHOT") - .put("sourceFolder", "src/main/java/test") - .put("localVariablePrefix", "tst") - .put("serializableModel", "false") - .put("fullJavaUtil", "true") - .put("library", "jersey2") - .build(); + @Test + public void getOptionsTest() throws ApiException { + final Map options = Generator.getOptions(new JavaOptionsProvider().getLanguage()); + assertNotNull(options); + final CliOption opt = options.get(CodegenConstants.LIBRARY); + assertNotNull(opt); + assertEquals(opt.getDefault(), JavaClientCodegen.DEFAULT_LIBRARY); } } diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJaxRSServerOptionsTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJaxRSServerOptionsTest.java deleted file mode 100644 index c64466fe696..00000000000 --- a/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJaxRSServerOptionsTest.java +++ /dev/null @@ -1,9 +0,0 @@ -package io.swagger.generator.online; - -public class OnlineJaxRSServerOptionsTest extends OnlineJavaClientOptionsTest{ - - public OnlineJaxRSServerOptionsTest() { - super("jaxrs", true); - } - -} diff --git a/pom.xml b/pom.xml index 86986c96060..1aec3d4beb5 100644 --- a/pom.xml +++ b/pom.xml @@ -353,6 +353,18 @@ samples/client/petstore/java/retrofit + + java-client-retrofit2 + + + env + java + + + + samples/client/petstore/java/retrofit2 + + scala-client @@ -427,6 +439,7 @@ samples/client/petstore/java/jersey2 samples/client/petstore/java/okhttp-gson samples/client/petstore/java/retrofit + samples/client/petstore/java/retrofit2 samples/client/petstore/scala samples/server/petstore/spring-mvc @@ -517,7 +530,7 @@ - 1.0.11 + 1.0.12 2.11.1 2.3.4 1.5.5-SNAPSHOT diff --git a/samples/client/petstore/clojure/.gitignore b/samples/client/petstore/clojure/.gitignore new file mode 100644 index 00000000000..c53038ec0e3 --- /dev/null +++ b/samples/client/petstore/clojure/.gitignore @@ -0,0 +1,11 @@ +/target +/classes +/checkouts +pom.xml +pom.xml.asc +*.jar +*.class +/.lein-* +/.nrepl-port +.hgignore +.hg/ diff --git a/samples/client/petstore/clojure/project.clj b/samples/client/petstore/clojure/project.clj new file mode 100644 index 00000000000..34dcb2d99a7 --- /dev/null +++ b/samples/client/petstore/clojure/project.clj @@ -0,0 +1,7 @@ +(defproject swagger-petstore "1.0.0" + :description "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters" + :license {:name "Apache 2.0" + :url "http://www.apache.org/licenses/LICENSE-2.0.html"} + :dependencies [[org.clojure/clojure "1.7.0"] + [clj-http "2.0.0"] + [cheshire "5.5.0"]]) diff --git a/samples/client/petstore/clojure/resources/hello.txt b/samples/client/petstore/clojure/resources/hello.txt new file mode 100644 index 00000000000..6769dd60bdf --- /dev/null +++ b/samples/client/petstore/clojure/resources/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj b/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj new file mode 100644 index 00000000000..c331444c886 --- /dev/null +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/pet.clj @@ -0,0 +1,108 @@ +(ns swagger-petstore.api.pet + (:require [swagger-petstore.core :refer [call-api check-required-params]]) + (:import (java.io File))) + +(defn update-pet + "Update an existing pet + " + ([] (update-pet nil)) + ([{:keys [body ]}] + (call-api "/pet" :put + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :body-param body + :content-types ["application/json" "application/xml"] + :accepts ["application/json" "application/xml"]}))) + +(defn add-pet + "Add a new pet to the store + " + ([] (add-pet nil)) + ([{:keys [body ]}] + (call-api "/pet" :post + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :body-param body + :content-types ["application/json" "application/xml"] + :accepts ["application/json" "application/xml"]}))) + +(defn find-pets-by-status + "Finds Pets by status + Multiple status values can be provided with comma seperated strings" + ([] (find-pets-by-status nil)) + ([{:keys [status ]}] + (call-api "/pet/findByStatus" :get + {:path-params {} + :header-params {} + :query-params {"status" status } + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"]}))) + +(defn find-pets-by-tags + "Finds Pets by tags + Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." + ([] (find-pets-by-tags nil)) + ([{:keys [tags ]}] + (call-api "/pet/findByTags" :get + {:path-params {} + :header-params {} + :query-params {"tags" tags } + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"]}))) + +(defn get-pet-by-id + "Find pet by ID + Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions" + [pet-id ] + (call-api "/pet/{petId}" :get + {:path-params {"petId" pet-id } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"]})) + +(defn update-pet-with-form + "Updates a pet in the store with form data + " + ([pet-id ] (update-pet-with-form pet-id nil)) + ([pet-id {:keys [name status ]}] + (call-api "/pet/{petId}" :post + {:path-params {"petId" pet-id } + :header-params {} + :query-params {} + :form-params {"name" name "status" status } + :content-types ["application/x-www-form-urlencoded"] + :accepts ["application/json" "application/xml"]}))) + +(defn delete-pet + "Deletes a pet + " + ([pet-id ] (delete-pet pet-id nil)) + ([pet-id {:keys [api-key ]}] + (call-api "/pet/{petId}" :delete + {:path-params {"petId" pet-id } + :header-params {"api_key" api-key } + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"]}))) + +(defn upload-file + "uploads an image + " + ([pet-id ] (upload-file pet-id nil)) + ([pet-id {:keys [additional-metadata ^File file ]}] + (call-api "/pet/{petId}/uploadImage" :post + {:path-params {"petId" pet-id } + :header-params {} + :query-params {} + :form-params {"additionalMetadata" additional-metadata "file" file } + :content-types ["multipart/form-data"] + :accepts ["application/json" "application/xml"]}))) diff --git a/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj b/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj new file mode 100644 index 00000000000..f2a18cea2e8 --- /dev/null +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/store.clj @@ -0,0 +1,53 @@ +(ns swagger-petstore.api.store + (:require [swagger-petstore.core :refer [call-api check-required-params]]) + (:import (java.io File))) + +(defn get-inventory + "Returns pet inventories by status + Returns a map of status codes to quantities" + [] + (call-api "/store/inventory" :get + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"]})) + +(defn place-order + "Place an order for a pet + " + ([] (place-order nil)) + ([{:keys [body ]}] + (call-api "/store/order" :post + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :body-param body + :content-types [] + :accepts ["application/json" "application/xml"]}))) + +(defn get-order-by-id + "Find purchase order by ID + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions" + [order-id ] + (call-api "/store/order/{orderId}" :get + {:path-params {"orderId" order-id } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"]})) + +(defn delete-order + "Delete purchase order by ID + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors" + [order-id ] + (call-api "/store/order/{orderId}" :delete + {:path-params {"orderId" order-id } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"]})) diff --git a/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj b/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj new file mode 100644 index 00000000000..15d41515ebb --- /dev/null +++ b/samples/client/petstore/clojure/src/swagger_petstore/api/user.clj @@ -0,0 +1,108 @@ +(ns swagger-petstore.api.user + (:require [swagger-petstore.core :refer [call-api check-required-params]]) + (:import (java.io File))) + +(defn create-user + "Create user + This can only be done by the logged in user." + ([] (create-user nil)) + ([{:keys [body ]}] + (call-api "/user" :post + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :body-param body + :content-types [] + :accepts ["application/json" "application/xml"]}))) + +(defn create-users-with-array-input + "Creates list of users with given input array + " + ([] (create-users-with-array-input nil)) + ([{:keys [body ]}] + (call-api "/user/createWithArray" :post + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :body-param body + :content-types [] + :accepts ["application/json" "application/xml"]}))) + +(defn create-users-with-list-input + "Creates list of users with given input array + " + ([] (create-users-with-list-input nil)) + ([{:keys [body ]}] + (call-api "/user/createWithList" :post + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :body-param body + :content-types [] + :accepts ["application/json" "application/xml"]}))) + +(defn login-user + "Logs user into the system + " + ([] (login-user nil)) + ([{:keys [username password ]}] + (call-api "/user/login" :get + {:path-params {} + :header-params {} + :query-params {"username" username "password" password } + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"]}))) + +(defn logout-user + "Logs out current logged in user session + " + [] + (call-api "/user/logout" :get + {:path-params {} + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"]})) + +(defn get-user-by-name + "Get user by user name + " + [username ] + (call-api "/user/{username}" :get + {:path-params {"username" username } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"]})) + +(defn update-user + "Updated user + This can only be done by the logged in user." + ([username ] (update-user username nil)) + ([username {:keys [body ]}] + (call-api "/user/{username}" :put + {:path-params {"username" username } + :header-params {} + :query-params {} + :form-params {} + :body-param body + :content-types [] + :accepts ["application/json" "application/xml"]}))) + +(defn delete-user + "Delete user + This can only be done by the logged in user." + [username ] + (call-api "/user/{username}" :delete + {:path-params {"username" username } + :header-params {} + :query-params {} + :form-params {} + :content-types [] + :accepts ["application/json" "application/xml"]})) diff --git a/samples/client/petstore/clojure/src/swagger_petstore/core.clj b/samples/client/petstore/clojure/src/swagger_petstore/core.clj new file mode 100644 index 00000000000..e7c55258e79 --- /dev/null +++ b/samples/client/petstore/clojure/src/swagger_petstore/core.clj @@ -0,0 +1,178 @@ +(ns swagger-petstore.core + (:require [cheshire.core :refer [generate-string parse-string]] + [clojure.string :as str] + [clj-http.client :as client]) + (:import (com.fasterxml.jackson.core JsonParseException) + (java.io File) + (java.util Date TimeZone) + (java.text SimpleDateFormat))) + +(def default-api-context + "Default API context." + {:base-url "http://petstore.swagger.io/v2" + :date-format "yyyy-MM-dd" + :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" + :debug false}) + +(def ^:dynamic *api-context* + "Dynamic API context to be applied in API calls." + default-api-context) + +(defmacro with-api-context + "A helper macro to wrap *api-context* with default values." + [context & body] + `(binding [*api-context* (merge *api-context* ~context)] + ~@body)) + +(defmacro check-required-params + "Throw exception if the given parameter value is nil." + [& params] + (->> params + (map (fn [p] + `(if (nil? ~p) + (throw (IllegalArgumentException. ~(str "The parameter \"" p "\" is required")))))) + (list* 'do))) + +(defn- make-date-format + ([format-str] (make-date-format format-str nil)) + ([format-str time-zone] + (let [date-format (SimpleDateFormat. format-str)] + (when time-zone + (.setTimeZone date-format (TimeZone/getTimeZone time-zone))) + date-format))) + +(defn format-date + "Format the given Date object with the :date-format defined in *api-options*. + NOTE: The UTC time zone is used." + [^Date date] + (let [{:keys [date-format]} *api-context*] + (-> (make-date-format date-format "UTC") + (.format date)))) + +(defn parse-date + "Parse the given string to a Date object with the :date-format defined in *api-options*. + NOTE: The UTC time zone is used." + [^String s] + (let [{:keys [date-format]} *api-context*] + (-> (make-date-format date-format "UTC") + (.parse s)))) + +(defn format-datetime + "Format the given Date object with the :datetime-format defined in *api-options*. + NOTE: The system's default time zone is used when not provided." + ([^Date date] (format-datetime date nil)) + ([^Date date ^String time-zone] + (let [{:keys [datetime-format]} *api-context*] + (-> (make-date-format datetime-format time-zone) + (.format date))))) + +(defn parse-datetime + "Parse the given string to a Date object with the :datetime-format defined in *api-options*. + NOTE: The system's default time zone is used when not provided." + ([^String s] (parse-datetime s nil)) + ([^String s ^String time-zone] + (let [{:keys [datetime-format]} *api-context*] + (-> (make-date-format datetime-format time-zone) + (.parse s))))) + +(defn param-to-str [param] + "Format the given parameter value to string." + (cond + (instance? Date param) (format-datetime param) + (sequential? param) (str/join "," param) + :else (str param))) + +(defn make-url + "Make full URL by adding base URL and filling path parameters." + [path path-params] + (let [path (reduce (fn [p [k v]] + (str/replace p (re-pattern (str "\\{" k "\\}")) (param-to-str v))) + path + path-params)] + (str (:base-url *api-context*) path))) + +(defn normalize-param + "Normalize parameter value, handling three cases: + for sequential value, normalize each elements of it; + for File value, do nothing with it; + otherwise, call `param-to-string`." + [param] + (cond + (sequential? param) (map normalize-param param) + (instance? File param) param + :else (param-to-str param))) + +(defn normalize-params + "Normalize parameters values: remove nils, format to string with `param-to-str`." + [params] + (->> params + (remove (comp nil? second)) + (map (fn [[k v]] [k (normalize-param v)])) + (into {}))) + +(defn json-mime? [mime] + "Check if the given MIME is a standard JSON MIME or :json." + (if mime + (or (= :json mime) + (re-matches #"application/json(;.*)?" (name mime))))) + +(defn json-preferred-mime [mimes] + "Choose a MIME from the given MIMEs with JSON preferred, + i.e. return JSON if included, otherwise return the first one." + (-> (filter json-mime? mimes) + first + (or (first mimes)))) + +(defn serialize + "Serialize the given data according to content-type. + Only JSON is supported for now." + [data content-type] + (if (json-mime? content-type) + (generate-string data {:date-format (:datetime-format *api-context*)}) + (throw (IllegalArgumentException. (str "Content type \"" content-type "\" is not support for serialization"))))) + +(defn deserialize + "Deserialize the given HTTP response according to the Content-Type header." + [{:keys [body] {:keys [content-type]} :headers}] + (cond + (json-mime? content-type) + (try + (parse-string body true) + (catch JsonParseException e + ;; return the body string directly on JSON parsing error + body)) + ;; for non-JSON response, return the body string directly + :else body)) + +(defn form-params-to-multipart + "Convert the given form parameters map into a vector as clj-http's :multipart option." + [form-params] + (->> form-params + (map (fn [[k v]] (array-map :name k :content v))) + vec)) + +(defn call-api + "Call an API by making HTTP request and return its response." + [path method {:keys [path-params query-params header-params form-params body-param content-types accepts]}] + (let [{:keys [debug]} *api-context* + url (make-url path path-params) + content-type (or (json-preferred-mime content-types) + (and body-param :json)) + accept (or (json-preferred-mime accepts) :json) + multipart? (= "multipart/form-data" content-type) + opts (cond-> {:url url :method method} + accept (assoc :accept accept) + (seq query-params) (assoc :query-params (normalize-params query-params)) + (seq header-params) (assoc :header-params (normalize-params header-params)) + (and content-type (not multipart?)) (assoc :content-type content-type) + multipart? (assoc :multipart (-> form-params + normalize-params + form-params-to-multipart)) + (and (not multipart?) (seq form-params)) (assoc :form-params (normalize-params form-params)) + body-param (assoc :body (serialize body-param content-type)) + debug (assoc :debug true :debug-body true)) + resp (client/request opts)] + (when debug + (println "Response:") + (println resp)) + (deserialize resp))) diff --git a/samples/client/petstore/clojure/test/swagger_petstore/api/pet_test.clj b/samples/client/petstore/clojure/test/swagger_petstore/api/pet_test.clj new file mode 100644 index 00000000000..7327b44c45d --- /dev/null +++ b/samples/client/petstore/clojure/test/swagger_petstore/api/pet_test.clj @@ -0,0 +1,85 @@ +(ns swagger-petstore.api.pet-test + (:require [clojure.test :refer :all] + [clojure.java.io :as io] + [swagger-petstore.api.pet :refer :all])) + +(defn- make-random-pet + ([] (make-random-pet nil)) + ([{:keys [id] :as attrs :or {id (System/currentTimeMillis)}}] + (merge {:id id + :name (str "pet-" id) + :status "available" + :photoUrls ["http://foo.bar.com/1" "http://foo.bar.com/2"] + :category {:name "really-happy"}} + attrs))) + +(deftest test-create-and-get-pet + (let [{:keys [id] :as pet} (make-random-pet) + _ (add-pet {:body pet}) + fetched (get-pet-by-id id)] + (is (identity fetched)) + (is (= id (:id fetched))) + (is (identity (:category fetched))) + (is (= (get-in pet [:category :name]) (get-in fetched [:category :name]))) + (delete-pet id))) + +(deftest test-find-pets-by-status + (let [status "pending" + {:keys [id] :as pet} (make-random-pet {:status status}) + _ (add-pet {:body pet}) + pets (find-pets-by-status {:status [status]})] + (is (seq pets)) + (is (some #{id} (map :id pets))) + (delete-pet id))) + +(deftest test-find-pets-by-tags + (let [tag-name (str "tag-" (rand-int 1000)) + tag {:name tag-name} + {:keys [id] :as pet} (make-random-pet {:tags [tag]}) + _ (add-pet {:body pet}) + pets (find-pets-by-tags {:tags [tag-name]})] + (is (seq pets)) + (is (some #{id} (map :id pets))) + (delete-pet id))) + +(deftest test-update-pet-with-form + (let [{pet-id :id :as pet} (make-random-pet {:name "new name" :status "available"}) + _ (add-pet {:body pet}) + {:keys [id name status]} (get-pet-by-id pet-id)] + (is (= pet-id id)) + (is (= "new name" name)) + (is (= "available" status)) + ;; update "name" only + (update-pet-with-form pet-id {:name "updated name 1"}) + (let [{:keys [id name status]} (get-pet-by-id pet-id)] + (is (= pet-id id)) + (is (= "updated name 1" name)) + (is (= "available" status))) + ;; update "status" only + (update-pet-with-form pet-id {:status "pending"}) + (let [{:keys [id name status]} (get-pet-by-id pet-id)] + (is (= pet-id id)) + (is (= "updated name 1" name)) + (is (= "pending" status))) + ;; update both "name" and "status" + (update-pet-with-form pet-id {:name "updated name 2" :status "sold"}) + (let [{:keys [id name status]} (get-pet-by-id pet-id)] + (is (= pet-id id)) + (is (= "updated name 2" name)) + (is (= "sold" status))) + (delete-pet pet-id))) + +(deftest test-delete-pet + (let [{:keys [id] :as pet} (make-random-pet) + _ (add-pet {:body pet}) + fetched (get-pet-by-id id)] + (is (= id (:id fetched))) + (delete-pet id) + (is (thrown? RuntimeException (get-pet-by-id id))))) + +(deftest test-upload-file + (let [{:keys [id] :as pet} (make-random-pet) + _ (add-pet {:body pet}) + file (io/file (io/resource "hello.txt"))] + ;; no errors with upload-file + (upload-file id {:file file :additional-metadata "uploading file with clojure client"}))) diff --git a/samples/client/petstore/clojure/test/swagger_petstore/api/store_test.clj b/samples/client/petstore/clojure/test/swagger_petstore/api/store_test.clj new file mode 100644 index 00000000000..5a453e3693e --- /dev/null +++ b/samples/client/petstore/clojure/test/swagger_petstore/api/store_test.clj @@ -0,0 +1,27 @@ +(ns swagger-petstore.api.store-test + (:require [clojure.test :refer :all] + [swagger-petstore.api.store :refer :all]) + (:import (java.util Date))) + +(defn- make-random-order [] + {:id (+ 90000 (rand-int 10000)) + :petId 200 + :quantity 13 + :shipDate (Date.) + :status "placed" + :complete true}) + +(deftest test-get-inventory + (let [inventory (get-inventory)] + (is (pos? (count inventory))))) + +(deftest test-place-and-delete-order + (let [order (make-random-order) + order-id (:id order) + _ (place-order {:body order}) + fetched (get-order-by-id order-id)] + (doseq [attr [:id :petId :quantity]] + (is (= (attr order) (attr fetched)))) + (delete-order order-id) + (comment "it seems that delete-order does not really delete the order" + (is (thrown? RuntimeException (get-order-by-id order-id)))))) diff --git a/samples/client/petstore/clojure/test/swagger_petstore/api/user_test.clj b/samples/client/petstore/clojure/test/swagger_petstore/api/user_test.clj new file mode 100644 index 00000000000..aa05b23f19a --- /dev/null +++ b/samples/client/petstore/clojure/test/swagger_petstore/api/user_test.clj @@ -0,0 +1,57 @@ +(ns swagger-petstore.api.user-test + (:require [clojure.test :refer :all] + [swagger-petstore.api.user :refer :all])) + +(defn- make-random-user + ([] (make-random-user nil)) + ([{:keys [id] :as attrs :or {id (System/currentTimeMillis)}}] + (merge {:id id + :username (str "user-" id) + :password "my-password" + :userStatus 0} + attrs))) + +(deftest test-create-and-delete-user + (let [user (make-random-user) + username (:username user) + _ (create-user {:body user}) + fetched (get-user-by-name username)] + (doseq [attr [:id :username :password :userStatus]] + (is (= (attr user) (attr fetched)))) + (delete-user username) + (is (thrown? RuntimeException (get-user-by-name username))))) + +(deftest test-create-users-with-array-input + (let [id1 (System/currentTimeMillis) + id2 (inc id1) + user1 (make-random-user {:id id1}) + user2 (make-random-user {:id id2})] + (create-users-with-array-input {:body [user1 user2]}) + (let [fetched (get-user-by-name (:username user1))] + (is (= id1 (:id fetched)))) + (let [fetched (get-user-by-name (:username user2))] + (is (= id2 (:id fetched)))) + (delete-user (:username user1)) + (delete-user (:username user2)))) + +(deftest test-create-users-with-list-input + (let [id1 (System/currentTimeMillis) + id2 (inc id1) + user1 (make-random-user {:id id1}) + user2 (make-random-user {:id id2})] + (create-users-with-list-input {:body [user1 user2]}) + (let [fetched (get-user-by-name (:username user1))] + (is (= id1 (:id fetched)))) + (let [fetched (get-user-by-name (:username user2))] + (is (= id2 (:id fetched)))) + (delete-user (:username user1)) + (delete-user (:username user2)))) + +(deftest test-login-and-lougout-user + (let [{:keys [username password] :as user} (make-random-user) + _ (create-user {:body user}) + result (login-user {:username username :password password})] + (is (re-matches #"logged in user session:.+" result)) + ;; no error with logout-user + (logout-user) + (delete-user username))) diff --git a/samples/client/petstore/clojure/test/swagger_petstore/core_test.clj b/samples/client/petstore/clojure/test/swagger_petstore/core_test.clj new file mode 100644 index 00000000000..394824aa4a9 --- /dev/null +++ b/samples/client/petstore/clojure/test/swagger_petstore/core_test.clj @@ -0,0 +1,135 @@ +(ns swagger-petstore.core-test + (:require [clojure.java.io :as io] + [clojure.test :refer :all] + [swagger-petstore.core :refer :all]) + (:import (java.text ParseException))) + +(deftest test-api-context + (testing "default" + (is (= {:base-url "http://petstore.swagger.io/v2" + :date-format "yyyy-MM-dd" + :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" + :debug false} + default-api-context + *api-context* + (with-api-context {} + *api-context*)))) + (testing "customize via with-api-context" + (with-api-context {:base-url "http://localhost" :debug true} + (is (= {:base-url "http://localhost" + :date-format "yyyy-MM-dd" + :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" + :debug true} + *api-context*)) + ;; nested with-api-context inherits values from the outer api context + (with-api-context {:datetime-format "yyyy-MM-dd HH:mm:ss"} + (is (= {:base-url "http://localhost" + :date-format "yyyy-MM-dd" + :datetime-format "yyyy-MM-dd HH:mm:ss" + :debug true} + *api-context*)))) + ;; back to default api context + (is (= {:base-url "http://petstore.swagger.io/v2" + :date-format "yyyy-MM-dd" + :datetime-format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" + :debug false} + *api-context*)))) + +(deftest test-check-required-params + (let [a nil b :not-nil] + (is (thrown? IllegalArgumentException (check-required-params a))) + (is (nil? (check-required-params b))))) + +(deftest test-parse-and-format-date + (testing "default date format" + (is (= "2015-11-07" (-> "2015-11-07T03:49:09.356+00:00" parse-datetime format-date))) + (is (= "2015-11-07" (-> "2015-11-07" parse-date format-date))) + (is (thrown? ParseException (parse-date "2015-11")))) + (testing "custom date format: without day" + (with-api-context {:date-format "yyyy-MM"} + (is (= "2015-11" (-> "2015-11-07T03:49:09.123Z" parse-datetime format-date))) + (is (= "2015-11" (-> "2015-11" parse-date format-date))) + (is (thrown? ParseException (parse-date "2015")))))) + +(deftest test-parse-and-format-datetime + (testing "default datetime format" + (are [s] + (is (= "2015-11-07T03:49:09.356Z" (-> s parse-datetime (format-datetime "UTC")))) + "2015-11-07T03:49:09.356+00:00" + "2015-11-07T05:49:09.356+02:00" + "2015-11-07T02:49:09.356-01:00" + "2015-11-07T03:49:09.356Z") + (is (thrown? ParseException (parse-datetime "2015-11-07 03:49:09")))) + (testing "custom datetime format: without milliseconds" + (with-api-context {:datetime-format "yyyy-MM-dd'T'HH:mm:ssXXX"} + (are [s] + (is (= "2015-11-07T13:49:09+10:00" (-> s parse-datetime (format-datetime "GMT+10")))) + "2015-11-07T03:49:09+00:00" + "2015-11-07T03:49:09Z" + "2015-11-07T00:49:09-03:00") + (is (thrown? ParseException (parse-datetime "2015-11-07T03:49:09.123Z")))))) + +(deftest test-param-to-str + (let [date (parse-datetime "2015-11-07T03:49:09.123Z")] + (are [param expected] + (is (= expected (param-to-str param))) + nil "" + "abc" "abc" + 123 "123" + 1.0 "1.0" + [12 "34"] "12,34" + date (format-datetime date)))) + +(deftest test-make-url + (are [path path-params url] + (is (= url (make-url path path-params))) + "/pet/{petId}" {"petId" 123} "http://petstore.swagger.io/v2/pet/123" + "/" nil "http://petstore.swagger.io/v2/" + "/pet" {"id" 1} "http://petstore.swagger.io/v2/pet" + "/pet/{id}" nil "http://petstore.swagger.io/v2/pet/{id}")) + +(deftest test-normalize-param + (let [file (-> "hello.txt" io/resource io/file)] + (are [param expected] + (is (= expected (normalize-param param))) + [12 "34"] ["12" "34"] + file file + "abc" "abc" + [[12 "34"] file "abc"] [["12" "34"] file "abc"]))) + +(deftest test-normalize-params + (is (= {:a "123" :b ["4" ["5" "6"]]} + (normalize-params {:a 123 :b [4 [5 "6"]] :c nil})))) + +(deftest test-json-mime? + (are [mime expected] + (is (= expected (boolean (json-mime? mime)))) + :json true + "application/json" true + "application/json; charset=utf8" true + nil false + :xml false + "application/pdf" false)) + +(deftest test-json-preferred-mime + (are [mimes expected] + (is (= expected (json-preferred-mime mimes))) + ["application/xml" "application/json"] "application/json" + [:json] :json + [] nil + nil nil + ["application/xml"] "application/xml")) + +(deftest test-serialize + (is (= "{\"aa\":1,\"bb\":\"2\"}" (serialize {:aa 1 :bb "2"} :json))) + (is (= "{}" (serialize {} "application/json"))) + (is (= "[1,\"2\"]" (serialize [1 "2"] "application/json; charset=UTF8"))) + (is (thrown? IllegalArgumentException (serialize {} "application/xml")))) + +(deftest test-deserialize + (are [body content-type expected] + (is (= expected (deserialize {:body body :headers {:content-type content-type}}))) + "{\"aa\": 1, \"bb\": \"2\"}" "application/json" {:aa 1 :bb "2"} + "[1, \"2\"]" "application/json; charset=UTF8" [1 "2"] + "{invalid json}" "application/json" "{invalid json}" + "plain text" "text/plain" "plain text")) \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs index 4e7e84fb725..00bd7a5e9f2 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs @@ -248,7 +248,7 @@ namespace IO.Swagger.Api { - var path = "/pet"; + var path_ = "/pet"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -279,7 +279,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content, response.Content); @@ -298,7 +298,7 @@ namespace IO.Swagger.Api { - var path = "/pet"; + var path_ = "/pet"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -329,7 +329,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content, response.Content); @@ -346,7 +346,7 @@ namespace IO.Swagger.Api { - var path = "/pet"; + var path_ = "/pet"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -377,7 +377,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content, response.Content); @@ -396,7 +396,7 @@ namespace IO.Swagger.Api { - var path = "/pet"; + var path_ = "/pet"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -427,7 +427,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content, response.Content); @@ -444,7 +444,7 @@ namespace IO.Swagger.Api { - var path = "/pet/findByStatus"; + var path_ = "/pet/findByStatus"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -475,14 +475,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.ErrorMessage, response.ErrorMessage); - return (List) ApiClient.Deserialize(response.Content, typeof(List), response.Headers); + return (List) ApiClient.Deserialize(response, typeof(List)); } /// @@ -494,7 +494,7 @@ namespace IO.Swagger.Api { - var path = "/pet/findByStatus"; + var path_ = "/pet/findByStatus"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -525,11 +525,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content, response.Content); - return (List) ApiClient.Deserialize(response.Content, typeof(List), response.Headers); + return (List) ApiClient.Deserialize(response, typeof(List)); } /// @@ -541,7 +541,7 @@ namespace IO.Swagger.Api { - var path = "/pet/findByTags"; + var path_ = "/pet/findByTags"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -572,14 +572,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.ErrorMessage, response.ErrorMessage); - return (List) ApiClient.Deserialize(response.Content, typeof(List), response.Headers); + return (List) ApiClient.Deserialize(response, typeof(List)); } /// @@ -591,7 +591,7 @@ namespace IO.Swagger.Api { - var path = "/pet/findByTags"; + var path_ = "/pet/findByTags"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -622,11 +622,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content, response.Content); - return (List) ApiClient.Deserialize(response.Content, typeof(List), response.Headers); + return (List) ApiClient.Deserialize(response, typeof(List)); } /// @@ -641,7 +641,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetById"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -669,17 +669,17 @@ namespace IO.Swagger.Api // authentication setting, if any - String[] authSettings = new String[] { "api_key", "petstore_auth" }; + String[] authSettings = new String[] { "api_key" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.ErrorMessage, response.ErrorMessage); - return (Pet) ApiClient.Deserialize(response.Content, typeof(Pet), response.Headers); + return (Pet) ApiClient.Deserialize(response, typeof(Pet)); } /// @@ -693,7 +693,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetById"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -721,14 +721,14 @@ namespace IO.Swagger.Api // authentication setting, if any - String[] authSettings = new String[] { "api_key", "petstore_auth" }; + String[] authSettings = new String[] { "api_key" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content, response.Content); - return (Pet) ApiClient.Deserialize(response.Content, typeof(Pet), response.Headers); + return (Pet) ApiClient.Deserialize(response, typeof(Pet)); } /// @@ -745,7 +745,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UpdatePetWithForm"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -778,7 +778,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); @@ -801,7 +801,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UpdatePetWithForm"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -834,7 +834,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content, response.Content); @@ -855,7 +855,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling DeletePet"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -887,7 +887,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content, response.Content); @@ -909,7 +909,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling DeletePet"); - var path = "/pet/{petId}"; + var path_ = "/pet/{petId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -941,7 +941,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content, response.Content); @@ -963,7 +963,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UploadFile"); - var path = "/pet/{petId}/uploadImage"; + var path_ = "/pet/{petId}/uploadImage"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -996,7 +996,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content, response.Content); @@ -1019,7 +1019,7 @@ namespace IO.Swagger.Api if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UploadFile"); - var path = "/pet/{petId}/uploadImage"; + var path_ = "/pet/{petId}/uploadImage"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -1052,7 +1052,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "petstore_auth" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content, response.Content); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs index f96b773c76f..b0a439ddf1a 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs @@ -155,7 +155,7 @@ namespace IO.Swagger.Api { - var path = "/store/inventory"; + var path_ = "/store/inventory"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -185,14 +185,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "api_key" }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.ErrorMessage, response.ErrorMessage); - return (Dictionary) ApiClient.Deserialize(response.Content, typeof(Dictionary), response.Headers); + return (Dictionary) ApiClient.Deserialize(response, typeof(Dictionary)); } /// @@ -203,7 +203,7 @@ namespace IO.Swagger.Api { - var path = "/store/inventory"; + var path_ = "/store/inventory"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -233,11 +233,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { "api_key" }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); - return (Dictionary) ApiClient.Deserialize(response.Content, typeof(Dictionary), response.Headers); + return (Dictionary) ApiClient.Deserialize(response, typeof(Dictionary)); } /// @@ -249,7 +249,7 @@ namespace IO.Swagger.Api { - var path = "/store/order"; + var path_ = "/store/order"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -280,14 +280,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.ErrorMessage, response.ErrorMessage); - return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers); + return (Order) ApiClient.Deserialize(response, typeof(Order)); } /// @@ -299,7 +299,7 @@ namespace IO.Swagger.Api { - var path = "/store/order"; + var path_ = "/store/order"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -330,11 +330,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); - return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers); + return (Order) ApiClient.Deserialize(response, typeof(Order)); } /// @@ -349,7 +349,7 @@ namespace IO.Swagger.Api if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling GetOrderById"); - var path = "/store/order/{orderId}"; + var path_ = "/store/order/{orderId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -380,14 +380,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.ErrorMessage, response.ErrorMessage); - return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers); + return (Order) ApiClient.Deserialize(response, typeof(Order)); } /// @@ -401,7 +401,7 @@ namespace IO.Swagger.Api if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling GetOrderById"); - var path = "/store/order/{orderId}"; + var path_ = "/store/order/{orderId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -432,11 +432,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); - return (Order) ApiClient.Deserialize(response.Content, typeof(Order), response.Headers); + return (Order) ApiClient.Deserialize(response, typeof(Order)); } /// @@ -451,7 +451,7 @@ namespace IO.Swagger.Api if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder"); - var path = "/store/order/{orderId}"; + var path_ = "/store/order/{orderId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -482,7 +482,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); @@ -503,7 +503,7 @@ namespace IO.Swagger.Api if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder"); - var path = "/store/order/{orderId}"; + var path_ = "/store/order/{orderId}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -534,7 +534,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs index f7c68cfbe35..b4c8d93c28c 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs @@ -240,7 +240,7 @@ namespace IO.Swagger.Api { - var path = "/user"; + var path_ = "/user"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -271,7 +271,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content, response.Content); @@ -290,7 +290,7 @@ namespace IO.Swagger.Api { - var path = "/user"; + var path_ = "/user"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -321,7 +321,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content, response.Content); @@ -338,7 +338,7 @@ namespace IO.Swagger.Api { - var path = "/user/createWithArray"; + var path_ = "/user/createWithArray"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -369,7 +369,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); @@ -388,7 +388,7 @@ namespace IO.Swagger.Api { - var path = "/user/createWithArray"; + var path_ = "/user/createWithArray"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -419,7 +419,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content, response.Content); @@ -436,7 +436,7 @@ namespace IO.Swagger.Api { - var path = "/user/createWithList"; + var path_ = "/user/createWithList"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -467,7 +467,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); @@ -486,7 +486,7 @@ namespace IO.Swagger.Api { - var path = "/user/createWithList"; + var path_ = "/user/createWithList"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -517,7 +517,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content, response.Content); @@ -535,7 +535,7 @@ namespace IO.Swagger.Api { - var path = "/user/login"; + var path_ = "/user/login"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -567,14 +567,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.ErrorMessage, response.ErrorMessage); - return (string) ApiClient.Deserialize(response.Content, typeof(string), response.Headers); + return (string) ApiClient.Deserialize(response, typeof(string)); } /// @@ -587,7 +587,7 @@ namespace IO.Swagger.Api { - var path = "/user/login"; + var path_ = "/user/login"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -619,11 +619,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content, response.Content); - return (string) ApiClient.Deserialize(response.Content, typeof(string), response.Headers); + return (string) ApiClient.Deserialize(response, typeof(string)); } /// @@ -634,7 +634,7 @@ namespace IO.Swagger.Api { - var path = "/user/logout"; + var path_ = "/user/logout"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -664,7 +664,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content, response.Content); @@ -682,7 +682,7 @@ namespace IO.Swagger.Api { - var path = "/user/logout"; + var path_ = "/user/logout"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -712,7 +712,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content, response.Content); @@ -732,7 +732,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling GetUserByName"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -763,14 +763,14 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content, response.Content); else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.ErrorMessage, response.ErrorMessage); - return (User) ApiClient.Deserialize(response.Content, typeof(User), response.Headers); + return (User) ApiClient.Deserialize(response, typeof(User)); } /// @@ -784,7 +784,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling GetUserByName"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -815,11 +815,11 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content, response.Content); - return (User) ApiClient.Deserialize(response.Content, typeof(User), response.Headers); + return (User) ApiClient.Deserialize(response, typeof(User)); } /// @@ -835,7 +835,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling UpdateUser"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -867,7 +867,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content, response.Content); @@ -889,7 +889,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling UpdateUser"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -921,7 +921,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content, response.Content); @@ -941,7 +941,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling DeleteUser"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -972,7 +972,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content, response.Content); @@ -993,7 +993,7 @@ namespace IO.Swagger.Api if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling DeleteUser"); - var path = "/user/{username}"; + var path_ = "/user/{username}"; var pathParams = new Dictionary(); var queryParams = new Dictionary(); @@ -1024,7 +1024,7 @@ namespace IO.Swagger.Api String[] authSettings = new String[] { }; // make the HTTP request - IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); + IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings); if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content, response.Content); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs index 74b898be626..36217fde02d 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 @@ -10,7 +10,6 @@ using System.Net; using System.Text; using Newtonsoft.Json; using RestSharp; -using RestSharp.Extensions; namespace IO.Swagger.Client { @@ -171,7 +170,7 @@ namespace IO.Swagger.Client /// Escaped string. public string EscapeString(string str) { - return RestSharp.Extensions.StringExtensions.UrlEncode(str); + return UrlEncode(str); } /// @@ -183,9 +182,9 @@ namespace IO.Swagger.Client public FileParameter ParameterToFile(string name, Stream stream) { if (stream is FileStream) - return FileParameter.Create(name, stream.ReadAsBytes(), Path.GetFileName(((FileStream)stream).Name)); + return FileParameter.Create(name, ReadAsBytes(stream), Path.GetFileName(((FileStream)stream).Name)); else - return FileParameter.Create(name, stream.ReadAsBytes(), "no_file_name_provided"); + return FileParameter.Create(name, ReadAsBytes(stream), "no_file_name_provided"); } /// @@ -214,12 +213,14 @@ namespace IO.Swagger.Client /// /// Deserialize the JSON string into a proper object. /// - /// HTTP body (e.g. string, JSON). + /// The HTTP response. /// Object type. - /// /// Object representation of the JSON string. - public object Deserialize(string content, Type type, IList headers=null) + public object Deserialize(IRestResponse response, Type type) { + byte[] data = response.RawBytes; + string content = response.Content; + IList headers = response.Headers; if (type == typeof(Object)) // return an object { return content; @@ -227,21 +228,22 @@ namespace IO.Swagger.Client if (type == typeof(Stream)) { - var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) - ? Path.GetTempPath() - : Configuration.TempFolderPath; - - var fileName = filePath + Guid.NewGuid(); if (headers != null) { + var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath) + ? Path.GetTempPath() + : Configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$"); var match = regex.Match(headers.ToString()); if (match.Success) - fileName = filePath + match.Value.Replace("\"", "").Replace("'", ""); + { + string fileName = filePath + match.Value.Replace("\"", "").Replace("'", ""); + File.WriteAllBytes(fileName, data); + return new FileStream(fileName, FileMode.Open); + } } - File.WriteAllText(fileName, content); - return new FileStream(fileName, FileMode.Open); - + var stream = new MemoryStream(data); + return stream; } if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object @@ -317,12 +319,10 @@ namespace IO.Swagger.Client case "api_key": headerParams["api_key"] = GetApiKeyWithPrefix("api_key"); - break; case "petstore_auth": - - //TODO support oauth + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; break; default: @@ -368,6 +368,62 @@ namespace IO.Swagger.Client public static dynamic ConvertType(dynamic source, Type dest) { return Convert.ChangeType(source, dest); } + + /// + /// Convert stream to byte array + /// Credit/Ref: http://stackoverflow.com/a/221941/677735 + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream input) + { + byte[] buffer = new byte[16*1024]; + using (MemoryStream ms = new MemoryStream()) + { + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) > 0) + { + ms.Write(buffer, 0, read); + } + return ms.ToArray(); + } + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// String to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + } } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs index 80df0f4ec72..4168d69a2ea 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs @@ -37,6 +37,12 @@ namespace IO.Swagger.Client /// The password. public static String Password { get; set; } + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// The access token. + public static String AccessToken { get; set; } + /// /// Gets or sets the API key based on the authentication name. /// diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs index c402188b9fc..56ebfdb3b7b 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs index 07b3d14e598..1fa62c1605a 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs index 41216b52802..37c80259944 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs index 10ace1ad185..7d2ea38833b 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs index d22ac54c094..5430d1182cb 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs index 10c2758ea5e..31e5cba141b 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -2,7 +2,7 @@ - + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll index 74b5b6455e3..c975e54d4be 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb index 9700c554fbd..5c1092d07fc 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt index 286fb333c48..3ed0e98c4f7 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt +++ b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt @@ -1,8 +1,8 @@ -/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs -/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll -/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll -/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll -/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb -/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll -/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll -/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb +/Users/williamcheng/Code/csharp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs +/Users/williamcheng/Code/csharp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb +/Users/williamcheng/Code/csharp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll +/Users/williamcheng/Code/csharp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll +/Users/williamcheng/Code/csharp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb +/Users/williamcheng/Code/csharp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll +/Users/williamcheng/Code/csharp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll +/Users/williamcheng/Code/csharp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll index 74b5b6455e3..c975e54d4be 100755 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb index 9700c554fbd..5c1092d07fc 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/java/default/README.md b/samples/client/petstore/java/default/README.md new file mode 100644 index 00000000000..8afc37518fc --- /dev/null +++ b/samples/client/petstore/java/default/README.md @@ -0,0 +1,43 @@ +# swagger-java-client + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation & Usage + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: + +```xml + + io.swagger + swagger-java-client + 1.0.0 + compile + + +``` + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +apiteam@swagger.io + + diff --git a/samples/client/petstore/java/default/build.gradle b/samples/client/petstore/java/default/build.gradle index baa5ce97b01..b7ccd1df774 100644 --- a/samples/client/petstore/java/default/build.gradle +++ b/samples/client/petstore/java/default/build.gradle @@ -18,72 +18,76 @@ repositories { if(hasProperty('target') && target == 'android') { - apply plugin: 'com.android.library' - apply plugin: 'com.github.dcendents.android-maven' - - android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' - defaultConfig { - minSdkVersion 14 - targetSdkVersion 22 - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - } - - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.each { output -> - def outputFile = output.outputFile - if (outputFile != null && outputFile.name.endsWith('.aar')) { - def fileName = "${project.name}-${variant.baseName}-${version}.aar" - output.outputFile = new File(outputFile.parent, fileName) - } - } - } - } - - afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDir - task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } - } - - task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' - } - - artifacts { - archives sourcesJar - } + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } } else { - apply plugin: 'java' - apply plugin: 'maven' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - - install { - repositories.mavenInstaller { - pom.artifactId = 'swagger-java-client' - } - } - - task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath - } + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-java-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } } ext { diff --git a/samples/client/petstore/java/default/pom.xml b/samples/client/petstore/java/default/pom.xml index da49f3b2fb0..894e318b5f3 100644 --- a/samples/client/petstore/java/default/pom.xml +++ b/samples/client/petstore/java/default/pom.xml @@ -6,11 +6,7 @@ jar swagger-java-client 1.0.0 - - scm:git:git@github.com:swagger-api/swagger-mustache.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen - + 2.2.0 diff --git a/samples/client/petstore/java/default/src/main/AndroidManifest.xml b/samples/client/petstore/java/default/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/default/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index 17709ee88dc..bb8aaa7b990 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -39,7 +39,7 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-07T15:05:10.376+08:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); @@ -55,24 +55,33 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { - // Use ISO 8601 format for date and datetime. - // See https://en.wikipedia.org/wiki/ISO_8601 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + this.json.setDateFormat((DateFormat) dateFormat.clone()); + // Set default User-Agent. setUserAgent("Java-Swagger"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } + /** + * Gets the JSON instance to do JSON serialization and deserialization. + */ + public JSON getJSON() { + return json; + } + public String getBasePath() { return basePath; } @@ -165,6 +174,19 @@ public class ApiClient { throw new RuntimeException("No API key authentication configured!"); } + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + /** * Set the User-Agent header's value (by adding to the default header map). */ @@ -213,6 +235,8 @@ public class ApiClient { */ public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; + // also set the date format for model (de)serialization with Date properties + this.json.setDateFormat((DateFormat) dateFormat.clone()); return this; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java index c09e4939e94..4ed22daabcd 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java @@ -3,7 +3,7 @@ package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java index 692018a52d3..8d0b098e28d 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java index 1986a6badbf..180f9b8cc19 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java @@ -4,9 +4,11 @@ import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.datatype.joda.*; +import java.text.DateFormat; + import java.io.IOException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:29.717+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-07T15:05:10.376+08:00") public class JSON { private ObjectMapper mapper; @@ -20,6 +22,13 @@ public class JSON { mapper.registerModule(new JodaModule()); } + /** + * Set the date format for JSON (de)serialization with Date properties. + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } + /** * Serialize the given Java object into JSON string. */ diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java index bc45efb5ce0..58afaafb158 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java index c2f943c731f..e1536c68473 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java index c30d70add6b..b1ba48408db 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java @@ -3,7 +3,7 @@ package io.swagger.client; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class TypeRef { private final Type type; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index 23782e03e72..17e9a0e299e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -11,7 +11,7 @@ import java.io.File; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:29.717+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-04T19:58:40.953+08:00") public class PetApi { private ApiClient apiClient; @@ -367,7 +367,7 @@ public class PetApi { if (apiKey != null) - headerParams.put("api_key", apiClient.parameterToString(apiKey)); + headerParams.put("api_key", apiClient.parameterToString(apiKey)); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java index f8c0fc58682..a2f2900dd40 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java @@ -11,7 +11,7 @@ import io.swagger.client.model.Order; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:29.717+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class StoreApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java index f6ab0ae0814..9be6bbfa67f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java @@ -11,7 +11,7 @@ import java.util.*; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:29.717+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class UserApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index bc6e2f87def..14891e3504f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java index 45a92c1323c..d74fd356989 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index bb14cab5a2c..99ff90e4c6f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -8,7 +8,7 @@ import java.util.List; import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java index 3e0fade5e80..1ab313d67ca 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,10 +5,22 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-02T21:16:46.418+08:00") public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + @Override public void applyToParams(List queryParams, Map headerParams) { - // TODO: support oauth + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java index b12b44dd1c8..1d1d9e1d1b5 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java index 7e4e43420c9..9c6094aefbf 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -10,7 +10,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class Order { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java index ba497232881..b842a7800de 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java @@ -12,7 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java index 68918590789..d52ef12d01c 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java index 271bf3b19d7..8aa9e34283f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T10:56:59.550-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-30T16:36:47.681+08:00") public class User { private Long id = null; diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java index 802c0cae3b9..3d57f3fa84c 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/ApiClientTest.java @@ -2,6 +2,8 @@ package io.swagger.client; import io.swagger.client.auth.*; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.*; import org.junit.*; @@ -16,6 +18,26 @@ public class ApiClientTest { apiClient = new ApiClient(); } + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07T03:49:09.356Z"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); + + // custom date format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); + } + @Test public void testSelectHeaderAccept() { String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/client/JSONTest.java new file mode 100644 index 00000000000..1250a135078 --- /dev/null +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/client/JSONTest.java @@ -0,0 +1,52 @@ +package io.swagger.client; + +import io.swagger.client.model.Order; + +import java.lang.Exception; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.TimeZone; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class JSONTest { + JSON json = null; + Order order = null; + + @Before + public void setup() { + json = new JSON(); + order = new Order(); + } + + @Test + public void testDefaultDate() throws Exception { + final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(dateFormat.parse(dateStr)); + + String str = json.serialize(order); + TypeRef typeRef = new TypeRef() { }; + Order o = json.deserialize(str, typeRef); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(dateFormat.parse(dateStr)); + + json.setDateFormat(dateFormat); + String str = json.serialize(order); + TypeRef typeRef = new TypeRef() { }; + Order o = json.deserialize(str, typeRef); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java index a1fd7e345a8..6094f2242e1 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -8,6 +8,7 @@ import io.swagger.client.auth.*; import io.swagger.client.model.*; import java.util.Map; +import java.text.SimpleDateFormat; import org.junit.*; import static org.junit.Assert.*; @@ -21,6 +22,8 @@ public class StoreApiTest { // setup authentication ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); apiKeyAuth.setApiKey("special-key"); + // set custom date format that is used by the petstore server + api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); } @Test diff --git a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java index 26e46bfa602..a3f257f568b 100644 --- a/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/default/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -73,7 +73,7 @@ public class UserApiTest { private User createUser() { User user = new User(); user.setId(System.currentTimeMillis()); - user.setUsername("fred"); + user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); user.setEmail("fred@fredmeyer.com"); diff --git a/samples/client/petstore/java/jersey2/README.md b/samples/client/petstore/java/jersey2/README.md new file mode 100644 index 00000000000..473892d2321 --- /dev/null +++ b/samples/client/petstore/java/jersey2/README.md @@ -0,0 +1,43 @@ +# swagger-petstore-jersey2 + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation & Usage + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: + +```xml + + io.swagger + swagger-petstore-jersey2 + 1.0.0 + compile + + +``` + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +apiteam@swagger.io + + diff --git a/samples/client/petstore/java/jersey2/build.gradle b/samples/client/petstore/java/jersey2/build.gradle index 9727e5693e6..85ad4f048b9 100644 --- a/samples/client/petstore/java/jersey2/build.gradle +++ b/samples/client/petstore/java/jersey2/build.gradle @@ -18,72 +18,76 @@ repositories { if(hasProperty('target') && target == 'android') { - apply plugin: 'com.android.library' - apply plugin: 'com.github.dcendents.android-maven' - - android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' - defaultConfig { - minSdkVersion 14 - targetSdkVersion 22 - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - } - - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.each { output -> - def outputFile = output.outputFile - if (outputFile != null && outputFile.name.endsWith('.aar')) { - def fileName = "${project.name}-${variant.baseName}-${version}.aar" - output.outputFile = new File(outputFile.parent, fileName) - } - } - } - } - - afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDir - task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } - } - - task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' - } - - artifacts { - archives sourcesJar - } + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } } else { - apply plugin: 'java' - apply plugin: 'maven' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - - install { - repositories.mavenInstaller { - pom.artifactId = 'swagger-petstore-jersey2' - } - } - - task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath - } + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-jersey2' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } } ext { diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index eee88cd2429..e5353a66ea5 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -162,7 +162,7 @@ 1.5.0 - 2.6 + 2.12 2.4.2 2.3 1.0.0 diff --git a/samples/client/petstore/java/jersey2/src/main/AndroidManifest.xml b/samples/client/petstore/java/jersey2/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index 4734b5d5077..c74c6e6ba29 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -43,8 +43,9 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class ApiClient { + private Client client; private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); private boolean debugging = false; @@ -59,24 +60,35 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { - // Use ISO 8601 format for date and datetime. - // See https://en.wikipedia.org/wiki/ISO_8601 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + this.json.setDateFormat((DateFormat) dateFormat.clone()); + // Set default User-Agent. setUserAgent("Java-Swagger"); + buildClient(); + // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } + /** + * Gets the JSON instance to do JSON serialization and deserialization. + */ + public JSON getJSON() { + return json; + } + public String getBasePath() { return basePath; } @@ -169,6 +181,19 @@ public class ApiClient { throw new RuntimeException("No API key authentication configured!"); } + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + /** * Set the User-Agent header's value (by adding to the default header map). */ @@ -202,6 +227,7 @@ public class ApiClient { */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; + buildClient(); return this; } @@ -217,6 +243,8 @@ public class ApiClient { */ public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; + // also set the date format for model (de)serialization with Date properties + this.json.setDateFormat((DateFormat) dateFormat.clone()); return this; } @@ -418,13 +446,6 @@ public class ApiClient { public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); - final ClientConfig clientConfig = new ClientConfig(); - clientConfig.register(MultiPartFeature.class); - if (debugging) { - clientConfig.register(LoggingFilter.class); - } - Client client = ClientBuilder.newClient(clientConfig); - WebTarget target = client.target(this.basePath).path(path); if (queryParams != null) { @@ -536,6 +557,15 @@ public class ApiClient { } } + private void buildClient() { + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + if (debugging) { + clientConfig.register(LoggingFilter.class); + } + this.client = ClientBuilder.newClient(clientConfig); + } + private Map> buildResponseHeaders(Response response) { Map> responseHeaders = new HashMap>(); for (Entry> entry: response.getHeaders().entrySet()) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java index 7c505d33b96..80bf3d260ca 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java @@ -3,7 +3,7 @@ package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java index f678452b1a0..82b8e0459bc 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java index 8ce930ce5c1..a05975c0e59 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -4,9 +4,11 @@ import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.datatype.joda.*; +import java.text.DateFormat; + import java.io.IOException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:20.020+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class JSON { private ObjectMapper mapper; @@ -20,6 +22,13 @@ public class JSON { mapper.registerModule(new JodaModule()); } + /** + * Set the date format for JSON (de)serialization with Date properties. + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } + /** * Serialize the given Java object into JSON string. */ diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java index a8337005dec..aae34092fc2 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java index ac7d51e2497..02e52457fef 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java index f2f9d8a31cc..0452e40e0c4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java @@ -3,7 +3,7 @@ package io.swagger.client; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class TypeRef { private final Type type; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index 57c087a7b5f..10134d4f3ea 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -11,7 +11,7 @@ import java.io.File; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:20.020+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class PetApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java index b035cde9658..d7e30dd2b0e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -11,7 +11,7 @@ import io.swagger.client.model.Order; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:20.020+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class StoreApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java index 51bac269b53..db04594b56b 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -11,7 +11,7 @@ import java.util.*; import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-21T11:55:20.020+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class UserApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 60f3aa7c5b5..d7d3d3e63b0 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java index ff1fc732015..0861802a7d3 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java @@ -5,7 +5,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index f3b643a7839..390502ab9e5 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -8,7 +8,7 @@ import java.util.List; import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java index e3ec46f0b81..144d4c9681f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,10 +5,22 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + @Override public void applyToParams(List queryParams, Map headerParams) { - // TODO: support oauth + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java index 1e5b0410731..26e1b89bba7 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index 3239bdd4faf..6efc0786703 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -10,7 +10,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class Order { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java index 2840137e85d..02f0b88d6f5 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -2,8 +2,8 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import io.swagger.client.model.Tag; import java.util.*; +import io.swagger.client.model.Tag; @@ -12,7 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java index e71aacd8011..9dc8e017f9f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index 2f35e770e03..8ad399fcc6b 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:29:47.599-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-17T11:17:50.535-05:00") public class User { private Long id = null; diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java index 802c0cae3b9..3d57f3fa84c 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/ApiClientTest.java @@ -2,6 +2,8 @@ package io.swagger.client; import io.swagger.client.auth.*; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.*; import org.junit.*; @@ -16,6 +18,26 @@ public class ApiClientTest { apiClient = new ApiClient(); } + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07T03:49:09.356Z"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); + + // custom date format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00"))); + } + @Test public void testSelectHeaderAccept() { String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java new file mode 100644 index 00000000000..1250a135078 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java @@ -0,0 +1,52 @@ +package io.swagger.client; + +import io.swagger.client.model.Order; + +import java.lang.Exception; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.TimeZone; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class JSONTest { + JSON json = null; + Order order = null; + + @Before + public void setup() { + json = new JSON(); + order = new Order(); + } + + @Test + public void testDefaultDate() throws Exception { + final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(dateFormat.parse(dateStr)); + + String str = json.serialize(order); + TypeRef typeRef = new TypeRef() { }; + Order o = json.deserialize(str, typeRef); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(dateFormat.parse(dateStr)); + + json.setDateFormat(dateFormat); + String str = json.serialize(order); + TypeRef typeRef = new TypeRef() { }; + Order o = json.deserialize(str, typeRef); + assertEquals(dateStr, dateFormat.format(o.getShipDate())); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java index a1fd7e345a8..6094f2242e1 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -8,6 +8,7 @@ import io.swagger.client.auth.*; import io.swagger.client.model.*; import java.util.Map; +import java.text.SimpleDateFormat; import org.junit.*; import static org.junit.Assert.*; @@ -21,6 +22,8 @@ public class StoreApiTest { // setup authentication ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); apiKeyAuth.setApiKey("special-key"); + // set custom date format that is used by the petstore server + api.getApiClient().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); } @Test diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java index 26e46bfa602..a3f257f568b 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -73,7 +73,7 @@ public class UserApiTest { private User createUser() { User user = new User(); user.setId(System.currentTimeMillis()); - user.setUsername("fred"); + user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); user.setEmail("fred@fredmeyer.com"); diff --git a/samples/client/petstore/java/okhttp-gson/README.md b/samples/client/petstore/java/okhttp-gson/README.md new file mode 100644 index 00000000000..be7ff686b7a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/README.md @@ -0,0 +1,43 @@ +# swagger-petstore-okhttp-gson + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation & Usage + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: + +```xml + + io.swagger + swagger-petstore-okhttp-gson + 1.0.0 + compile + + +``` + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +apiteam@swagger.io + + diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle index ada6a992573..c739b5e1a23 100644 --- a/samples/client/petstore/java/okhttp-gson/build.gradle +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -1,11 +1,93 @@ -apply plugin: 'java' -apply plugin: 'maven' +group = 'io.swagger' +version = '1.0.0' -sourceCompatibility = JavaVersion.VERSION_1_7 -targetCompatibility = JavaVersion.VERSION_1_7 +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} repositories { - mavenCentral() + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-okhttp-gson' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } } dependencies { @@ -15,17 +97,3 @@ dependencies { compile 'com.brsanthu:migbase64:2.2' testCompile 'junit:junit:4.8.1' } - -group = 'io.swagger' -version = '1.0.0' - -install { - repositories.mavenInstaller { - pom.artifactId = 'swagger-petstore-okhttp-gson' - } -} - -task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath -} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/AndroidManifest.xml b/samples/client/petstore/java/okhttp-gson/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 52a414252c5..51c3d5464f2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -75,13 +75,11 @@ public class ApiClient { private int statusCode; private Map> responseHeaders; - private String dateFormat; - private DateFormat dateFormatter; + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; private int dateLength; - private String datetimeFormat; - private DateFormat datetimeFormatter; - private InputStream sslCaCert; private boolean verifyingSsl; @@ -95,18 +93,27 @@ public class ApiClient { json = new JSON(this); - // Use ISO 8601 format for date and datetime. - // See https://en.wikipedia.org/wiki/ISO_8601 - setDateFormat("yyyy-MM-dd"); - setDatetimeFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + /* + * Use RFC3339 format for date and datetime. + * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + */ + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + // Always use UTC as the default time zone when dealing with date (without time). + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + // Use the system's default time zone when dealing with datetime (mainly formatting). + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + // Be lenient on datetime formats when parsing datetime from string. + // See parseDatetime. + this.lenientDatetimeFormat = true; // Set default User-Agent. setUserAgent("Java-Swagger"); // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); authentications.put("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } @@ -185,32 +192,35 @@ public class ApiClient { return this; } - public String getDateFormat() { + public DateFormat getDateFormat() { return dateFormat; } - public ApiClient setDateFormat(String dateFormat) { + public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; - - this.dateFormatter = new SimpleDateFormat(dateFormat); - // Use UTC as the default time zone. - this.dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); - - this.dateLength = this.dateFormatter.format(new Date()).length(); - + this.dateLength = this.dateFormat.format(new Date()).length(); return this; } - public String getDatetimeFormat() { + public DateFormat getDatetimeFormat() { return datetimeFormat; } - public ApiClient setDatetimeFormat(String datetimeFormat) { + public ApiClient setDatetimeFormat(DateFormat datetimeFormat) { this.datetimeFormat = datetimeFormat; + return this; + } - this.datetimeFormatter = new SimpleDateFormat(datetimeFormat); - // Note: The datetime formatter uses the system's default time zone. + /** + * Whether to allow various ISO 8601 datetime formats when parsing a datetime string. + * @see #parseDatetime(String) + */ + public boolean isLenientDatetimeFormat() { + return lenientDatetimeFormat; + } + public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) { + this.lenientDatetimeFormat = lenientDatetimeFormat; return this; } @@ -224,15 +234,15 @@ public class ApiClient { if (str == null) return null; try { - return dateFormatter.parse(str); + return dateFormat.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } } /** - * Parse the given date-time string into Date object. - * The default datetimeFormat supports these ISO 8601 datetime formats: + * Parse the given datetime string into Date object. + * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported: * 2015-08-16T08:20:05Z * 2015-8-16T8:20:05Z * 2015-08-16T08:20:05+00:00 @@ -252,25 +262,25 @@ public class ApiClient { if (str == null) return null; - if ("yyyy-MM-dd'T'HH:mm:ss.SSSZ".equals(datetimeFormat)) { + if (lenientDatetimeFormat) { /* - * When the default datetime format is used, process the given string + * When lenientDatetimeFormat is enabled, process the given string * to support various formats defined by ISO 8601. */ // normalize time zone - // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 - str = str.replaceAll("[zZ]\\z", "+0000"); - // remove colon: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); - // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 - str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+00:00 + str = str.replaceAll("[zZ]\\z", "+00:00"); + // add colon: 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05+00:00 + str = str.replaceAll("([+-]\\d{2})(\\d{2})\\z", "$1:$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+00:00 + str = str.replaceAll("([+-]\\d{2})\\z", "$1:00"); // add milliseconds when missing - // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 - str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + // 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05.000+00:00 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{2}:\\d{2})\\z", "$1.000$2"); } try { - return datetimeFormatter.parse(str); + return datetimeFormat.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } @@ -289,14 +299,14 @@ public class ApiClient { * Format the given Date object into string. */ public String formatDate(Date date) { - return dateFormatter.format(date); + return dateFormat.format(date); } /** * Format the given Date object into string. */ public String formatDatetime(Date date) { - return datetimeFormatter.format(date); + return datetimeFormat.format(date); } /** @@ -368,6 +378,19 @@ public class ApiClient { throw new RuntimeException("No API key authentication configured!"); } + /** + * Helper method to set access token for the first OAuth2 authentication. + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + /** * Set the User-Agent header's value (by adding to the default header map). */ diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java index dfa75184014..bc6473d110f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,10 +5,22 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-20T11:42:25.339-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-02T22:14:00.422+08:00") public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + @Override public void applyToParams(List queryParams, Map headerParams) { - // TODO: support oauth + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } } } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java index 802c0cae3b9..aaf4f33c49e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java @@ -2,7 +2,10 @@ package io.swagger.client; import io.swagger.client.auth.*; +import java.text.DateFormat; +import java.text.SimpleDateFormat; import java.util.*; +import java.util.TimeZone; import org.junit.*; import static org.junit.Assert.*; @@ -16,6 +19,64 @@ public class ApiClientTest { apiClient = new ApiClient(); } + @Test + public void testParseAndFormatDatetime() { + // default datetime format with UTC time zone + apiClient.getDatetimeFormat().setTimeZone(TimeZone.getTimeZone("UTC")); + String dateStr = "2015-11-07T03:49:09.356Z"; + assertTrue(apiClient.isLenientDatetimeFormat()); + assertEquals(dateStr, apiClient.formatDatetime(apiClient.parseDatetime("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDatetime(apiClient.parseDatetime("2015-11-07T05:49:09.356+02:00"))); + assertEquals(dateStr, apiClient.formatDatetime(apiClient.parseDatetime("2015-11-07T02:49:09.356-01:00"))); + // support various cases + assertEquals(dateStr, apiClient.formatDatetime(apiClient.parseDatetime("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDatetime(apiClient.parseDatetime("2015-11-07T03:49:09.356+00"))); + assertEquals(dateStr, apiClient.formatDatetime(apiClient.parseDatetime("2015-11-07T02:49:09.356-0100"))); + dateStr = "2015-11-07T03:49:09.000Z"; + assertEquals(dateStr, apiClient.formatDatetime(apiClient.parseDatetime("2015-11-07T05:49:09+02"))); + + // custom datetime format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDatetimeFormat(format); + // disable support of various datetime format + apiClient.setLenientDatetimeFormat(false); + dateStr = "2015-11-07T13:49:09+10:00"; + assertEquals(dateStr, apiClient.formatDatetime(apiClient.parseDatetime("2015-11-07T03:49:09+00:00"))); + assertEquals(dateStr, apiClient.formatDatetime(apiClient.parseDatetime("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDatetime(apiClient.parseDatetime("2015-11-07T00:49:09-03:00"))); + + try { + // invalid time zone format + apiClient.parseDatetime("2015-11-07T03:49:09+00"); + fail("parseDatetime should fail"); + } catch (RuntimeException e) { + // OK + } + try { + // unexpected miliseconds + apiClient.parseDatetime("2015-11-07T03:49:09.000Z"); + fail("parseDatetime should fail"); + } catch (RuntimeException e) { + // OK + } + } + + @Test + public void testParseAndFormatDate() { + // default date format + String dateStr = "2015-11-07"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDatetime("2015-11-07T03:49:09.356+00:00"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07"))); + + // custom date format: without day + DateFormat format = new SimpleDateFormat("yyyy-MM"); + apiClient.setDateFormat(format); + dateStr = "2015-11"; + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDatetime("2015-11-07T03:49:09Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11"))); + } + @Test public void testSelectHeaderAccept() { String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java new file mode 100644 index 00000000000..fdc2e4c7d4a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java @@ -0,0 +1,55 @@ +package io.swagger.client; + +import com.google.gson.reflect.TypeToken; + +import io.swagger.client.model.Order; + +import java.lang.Exception; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +import org.junit.*; +import static org.junit.Assert.*; + +public class JSONTest { + ApiClient apiClient = null; + JSON json = null; + Order order = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + json = new JSON(apiClient); + order = new Order(); + } + + @Test + public void testDefaultDate() throws Exception { + final DateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(datetimeFormat.parse(dateStr)); + + String str = json.serialize(order); + Type type = new TypeToken() { }.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + datetimeFormat.setTimeZone(TimeZone.getTimeZone("GMT-2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(datetimeFormat.parse(dateStr)); + + apiClient.setDatetimeFormat(datetimeFormat); + apiClient.setLenientDatetimeFormat(false); + String str = json.serialize(order); + Type type = new TypeToken() { }.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java index a1fd7e345a8..589dae1a3ca 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -8,6 +8,7 @@ import io.swagger.client.auth.*; import io.swagger.client.model.*; import java.util.Map; +import java.text.SimpleDateFormat; import org.junit.*; import static org.junit.Assert.*; @@ -21,6 +22,12 @@ public class StoreApiTest { // setup authentication ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); apiKeyAuth.setApiKey("special-key"); + // set custom date format that is used by the petstore server + // Note: it would still work without this setting as okhttp-gson Java client supports + // various date formats by default (with lenientDatetimeFormat enabled), including + // the one used by petstore server + api.getApiClient().setDatetimeFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")); + api.getApiClient().setLenientDatetimeFormat(false); } @Test diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java index 26e46bfa602..a3f257f568b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -73,7 +73,7 @@ public class UserApiTest { private User createUser() { User user = new User(); user.setId(System.currentTimeMillis()); - user.setUsername("fred"); + user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); user.setEmail("fred@fredmeyer.com"); diff --git a/samples/client/petstore/java/retrofit/README.md b/samples/client/petstore/java/retrofit/README.md new file mode 100644 index 00000000000..b687b09ab26 --- /dev/null +++ b/samples/client/petstore/java/retrofit/README.md @@ -0,0 +1,43 @@ +# swagger-petstore-retrofit + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation & Usage + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +After the client libarary is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: + +```xml + + io.swagger + swagger-petstore-retrofit + 1.0.0 + compile + + +``` + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +apiteam@swagger.io + + diff --git a/samples/client/petstore/java/retrofit/build.gradle b/samples/client/petstore/java/retrofit/build.gradle index 710d9da9a54..255a76e0403 100644 --- a/samples/client/petstore/java/retrofit/build.gradle +++ b/samples/client/petstore/java/retrofit/build.gradle @@ -18,72 +18,76 @@ repositories { if(hasProperty('target') && target == 'android') { - apply plugin: 'com.android.library' - apply plugin: 'com.github.dcendents.android-maven' - - android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' - defaultConfig { - minSdkVersion 14 - targetSdkVersion 22 - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 - } - - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.each { output -> - def outputFile = output.outputFile - if (outputFile != null && outputFile.name.endsWith('.aar')) { - def fileName = "${project.name}-${variant.baseName}-${version}.aar" - output.outputFile = new File(outputFile.parent, fileName) - } - } - } - } - - afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDir - task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } - } - - task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' - } - - artifacts { - archives sourcesJar - } + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } } else { - apply plugin: 'java' - apply plugin: 'maven' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - - install { - repositories.mavenInstaller { - pom.artifactId = 'swagger-petstore-retrofit' - } - } - - task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath - } + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-retrofit' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } } ext { diff --git a/samples/client/petstore/java/retrofit/src/main/AndroidManifest.xml b/samples/client/petstore/java/retrofit/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java index 343e545e83d..6540997c319 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java @@ -28,6 +28,7 @@ import com.squareup.okhttp.OkHttpClient; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; +import io.swagger.client.auth.OAuth.AccessTokenListener; import io.swagger.client.auth.OAuthFlow; @@ -44,12 +45,7 @@ public class ApiClient { public ApiClient(String[] authNames) { this(); - okClient = new OkHttpClient(); - adapterBuilder.setClient(new OkClient(okClient)); - for(String authName : authNames) { - if (apiAuthorizations.containsKey(authName)) { - throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); - } + for(String authName : authNames) { Interceptor auth; if (authName == "petstore_auth") { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); @@ -58,9 +54,8 @@ public class ApiClient { } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } - apiAuthorizations.put(authName, auth); + addAuthorization(authName, auth); } - addAuthsToOkClient(okClient); } /** @@ -114,9 +109,12 @@ public class ApiClient { .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .create(); + okClient = new OkHttpClient(); + adapterBuilder = new RestAdapter .Builder() .setEndpoint("http://petstore.swagger.io/v2") + .setClient(new OkClient(okClient)) .setConverter(new GsonConverterWrapper(gson)); } @@ -223,6 +221,33 @@ public class ApiClient { } } + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener + */ + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; + } + } + } + + /** + * Adds an authorization to be used by the client + * @param authName + * @param authorization + */ + public void addAuthorization(String authName, Interceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + apiAuthorizations.put(authName, authorization); + okClient.interceptors().add(authorization); + } + public Map getApiAuthorizations() { return apiAuthorizations; } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java index f7e488e0499..80614f0f56a 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java @@ -14,6 +14,7 @@ import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; import org.apache.oltu.oauth2.common.exception.OAuthProblemException; import org.apache.oltu.oauth2.common.exception.OAuthSystemException; import org.apache.oltu.oauth2.common.message.types.GrantType; +import org.apache.oltu.oauth2.common.token.BasicOAuthToken; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; @@ -23,12 +24,18 @@ import com.squareup.okhttp.Response; public class OAuth implements Interceptor { + public interface AccessTokenListener { + public void notify(BasicOAuthToken token); + } + private volatile String accessToken; private OAuthClient oauthClient; private TokenRequestBuilder tokenRequestBuilder; private AuthenticationRequestBuilder authenticationRequestBuilder; + private AccessTokenListener accessTokenListener; + public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) { this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client)); this.tokenRequestBuilder = requestBuilder; @@ -110,9 +117,11 @@ public class OAuth implements Interceptor { public synchronized void updateAccessToken(String requestAccessToken) throws IOException { if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { try { - OAuthJSONAccessTokenResponse accessTokenResponse; - accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); + OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } } catch (OAuthSystemException e) { throw new IOException(e); } catch (OAuthProblemException e) { @@ -121,6 +130,10 @@ public class OAuth implements Interceptor { } } + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; + } + public synchronized String getAccessToken() { return accessToken; } diff --git a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java index 373218465f0..f99d7f513cc 100644 --- a/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -71,7 +71,7 @@ public class UserApiTest { private User createUser() { User user = new User(); user.setId(System.currentTimeMillis()); - user.setUsername("fred"); + user.setUsername("fred" + user.getId()); user.setFirstName("Fred"); user.setLastName("Meyer"); user.setEmail("fred@fredmeyer.com"); diff --git a/samples/client/petstore/java/retrofit2/build.gradle b/samples/client/petstore/java/retrofit2/build.gradle new file mode 100644 index 00000000000..0deeeea2e37 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/build.gradle @@ -0,0 +1,106 @@ +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-retrofit2' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + okhttp_version = "2.5.0" + oltu_version = "1.0.0" + retrofit_version = "2.0.0-beta2" + gson_version = "2.4" + swagger_annotations_version = "1.5.0" + junit_version = "4.12" +} + +dependencies { + compile "com.squareup.okhttp:okhttp:$okhttp_version" + compile "com.squareup.retrofit:retrofit:$retrofit_version" + compile 'com.google.code.gson:gson:$gson_version' + compile 'com.squareup.retrofit:converter-gson:$retrofit_version' + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/retrofit2/gradle.properties b/samples/client/petstore/java/retrofit2/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/retrofit2/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml new file mode 100644 index 00000000000..109cbc0d95c --- /dev/null +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -0,0 +1,158 @@ + + 4.0.0 + io.swagger + swagger-petstore-retrofit2 + jar + swagger-petstore-retrofit2 + 1.0.0 + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + com.squareup.retrofit + retrofit + ${retrofit-version} + + + com.squareup.retrofit + converter-gson + ${retrofit-version} + + + com.google.code.gson + gson + ${gson-version} + + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} + + + com.squareup.okhttp + okhttp + ${okhttp-version} + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.0.0-beta2 + 2.5.0 + 2.4 + 1.0.0 + 1.0.0 + 4.12 + + diff --git a/samples/client/petstore/java/retrofit2/settings.gradle b/samples/client/petstore/java/retrofit2/settings.gradle new file mode 100644 index 00000000000..c42bfff90c4 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-retrofit2" \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..2138c3a172b --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,342 @@ +package io.swagger.client; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; + +import retrofit.Converter; +import retrofit.Retrofit; +import retrofit.GsonConverterFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.ResponseBody; + +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; +import io.swagger.client.auth.OAuth.AccessTokenListener; +import io.swagger.client.auth.OAuthFlow; + + +public class ApiClient { + + private Map apiAuthorizations; + private OkHttpClient okClient; + private Retrofit.Builder adapterBuilder; + + public ApiClient() { + apiAuthorizations = new LinkedHashMap(); + createDefaultAdapter(); + } + + public ApiClient(String[] authNames) { + this(); + for(String authName : authNames) { + Interceptor auth; + if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); + } else { + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + addAuthorization(authName, auth); + } + } + + /** + * Basic constructor for single auth name + * @param authName + */ + public ApiClient(String authName) { + this(new String[]{authName}); + } + + /** + * Helper constructor for single api key + * @param authName + * @param apiKey + */ + public ApiClient(String authName, String apiKey) { + this(authName); + this.setApiKey(apiKey); + } + + /** + * Helper constructor for single basic auth or password oauth2 + * @param authName + * @param username + * @param password + */ + public ApiClient(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); + } + + /** + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password + */ + public ApiClient(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); + } + + public void createDefaultAdapter() { + Gson gson = new GsonBuilder() + .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .create(); + + okClient = new OkHttpClient(); + + String baseUrl = "http://petstore.swagger.io/v2"; + if(!baseUrl.endsWith("/")) + baseUrl = baseUrl + "/"; + + adapterBuilder = new Retrofit + .Builder() + .baseUrl(baseUrl) + .client(okClient) + .addConverterFactory(GsonCustomConverterFactory.create(gson)); + } + + public S createService(Class serviceClass) { + return adapterBuilder.build().create(serviceClass); + + } + + /** + * Helper method to configure the first api key found + * @param apiKey + */ + private void setApiKey(String apiKey) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; + keyAuth.setApiKey(apiKey); + return; + } + } + } + + /** + * Helper method to configure the username/password for basic auth or password oauth + * @param username + * @param password + */ + private void setCredentials(String username, String password) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + return; + } + } + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public TokenRequestBuilder getTokenEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public AuthenticationRequestBuilder getAuthorizationEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + return oauth.getAuthenticationRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken + */ + public void setAccessToken(String accessToken) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.setAccessToken(accessToken); + return; + } + } + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId + * @param clientSecret + * @param redirectURI + */ + public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; + } + } + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener + */ + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; + } + } + } + + /** + * Adds an authorization to be used by the client + * @param authName + * @param authorization + */ + public void addAuthorization(String authName, Interceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + apiAuthorizations.put(authName, authorization); + okClient.interceptors().add(authorization); + } + + public Map getApiAuthorizations() { + return apiAuthorizations; + } + + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; + } + + public Retrofit.Builder getAdapterBuilder() { + return adapterBuilder; + } + + public void setAdapterBuilder(Retrofit.Builder adapterBuilder) { + this.adapterBuilder = adapterBuilder; + } + + public OkHttpClient getOkClient() { + return okClient; + } + + public void addAuthsToOkClient(OkHttpClient okClient) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + okClient.interceptors().add(apiAuthorization); + } + } + + /** + * Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the Retrofit + * @param okClient + */ + public void configureFromOkclient(OkHttpClient okClient) { + OkHttpClient clone = okClient.clone(); + addAuthsToOkClient(clone); + adapterBuilder.client(clone); + } +} + +/** + * 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 GsonResponseBodyConverterToString implements Converter { + private final Gson gson; + private final Type type; + + GsonResponseBodyConverterToString(Gson gson, Type type) { + this.gson = gson; + this.type = type; + } + + @Override public T convert(ResponseBody value) throws IOException { + String returned = value.string(); + try { + return gson.fromJson(returned, type); + } + catch (JsonParseException e) { + return (T) returned; + } + } +} + +class GsonCustomConverterFactory extends Converter.Factory +{ + public static GsonCustomConverterFactory create(Gson gson) { + return new GsonCustomConverterFactory(gson); + } + + private final Gson gson; + private final GsonConverterFactory gsonConverterFactory; + + private GsonCustomConverterFactory(Gson gson) { + if (gson == null) throw new NullPointerException("gson == null"); + this.gson = gson; + this.gsonConverterFactory = GsonConverterFactory.create(gson); + } + + @Override + public Converter fromResponseBody(Type type, Annotation[] annotations) { + if(type.equals(String.class)) + return new GsonResponseBodyConverterToString(gson, type); + else + return gsonConverterFactory.fromResponseBody(type, annotations); + } + + @Override + public Converter toRequestBody(Type type, Annotation[] annotations) { + return gsonConverterFactory.toRequestBody(type, annotations); + } +} + diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java new file mode 100644 index 00000000000..c3cf5257514 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/CollectionFormats.java @@ -0,0 +1,95 @@ +package io.swagger.client; + +import java.util.Arrays; +import java.util.List; + +public class CollectionFormats { + + public static class CSVParams { + + protected List params; + + public CSVParams() { + } + + public CSVParams(List params) { + this.params = params; + } + + public CSVParams(String... params) { + this.params = Arrays.asList(params); + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), ","); + } + + } + + public static class SSVParams extends CSVParams { + + public SSVParams() { + } + + public SSVParams(List params) { + super(params); + } + + public SSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), " "); + } + } + + public static class TSVParams extends CSVParams { + + public TSVParams() { + } + + public TSVParams(List params) { + super(params); + } + + public TSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join( params.toArray(new String[0]), "\t"); + } + } + + public static class PIPESParams extends CSVParams { + + public PIPESParams() { + } + + public PIPESParams(List params) { + super(params); + } + + public PIPESParams(String... params) { + super(params); + } + + @Override + public String toString() { + return StringUtil.join(params.toArray(new String[0]), "|"); + } + } + +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java similarity index 79% rename from samples/server/petstore/jaxrs/src/test/java/io/swagger/client/StringUtil.java rename to samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java index c80bc8a1647..5125ae3e55b 100644 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-10T12:25:26.227+01:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). @@ -39,4 +39,13 @@ public class StringUtil { } return out.toString(); } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + public static String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 00000000000..a55cf74da76 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,127 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import retrofit.Call; +import retrofit.http.*; +import com.squareup.okhttp.RequestBody; + +import io.swagger.client.model.Pet; +import java.io.File; + +import java.util.*; + +public interface PetApi { + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return Call + */ + + @PUT("pet") + Call updatePet( + @Body Pet body + ); + + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return Call + */ + + @POST("pet") + Call 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 Call> + */ + + @GET("pet/findByStatus") + Call> 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 Call> + */ + + @GET("pet/findByTags") + Call> 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 Call + */ + + @GET("pet/{petId}") + Call 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 Call + */ + + @FormUrlEncoded + @POST("pet/{petId}") + Call updatePetWithForm( + @Path("petId") String petId, @Field("name") String name, @Field("status") String status + ); + + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + * @return Call + */ + + @DELETE("pet/{petId}") + Call deletePet( + @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 Call + */ + + @Multipart + @POST("pet/{petId}/uploadImage") + Call uploadFile( + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file\"; filename=\"file\"") RequestBody file + ); + + +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..2fca1e02e39 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,66 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import retrofit.Call; +import retrofit.http.*; +import com.squareup.okhttp.RequestBody; + +import java.util.Map; +import io.swagger.client.model.Order; + +import java.util.*; + +public interface StoreApi { + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Call> + */ + + @GET("store/inventory") + Call> getInventory(); + + + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Call + */ + + @POST("store/order") + Call placeOrder( + @Body Order body + ); + + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @return Call + */ + + @GET("store/order/{orderId}") + Call getOrderById( + @Path("orderId") String orderId + ); + + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @return Call + */ + + @DELETE("store/order/{orderId}") + Call deleteOrder( + @Path("orderId") String orderId + ); + + +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..928bd623020 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,120 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + +import retrofit.Call; +import retrofit.http.*; +import com.squareup.okhttp.RequestBody; + +import io.swagger.client.model.User; +import java.util.*; + +import java.util.*; + +public interface UserApi { + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return Call + */ + + @POST("user") + Call createUser( + @Body User body + ); + + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return Call + */ + + @POST("user/createWithArray") + Call createUsersWithArrayInput( + @Body List body + ); + + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return Call + */ + + @POST("user/createWithList") + Call createUsersWithListInput( + @Body List body + ); + + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return Call + */ + + @GET("user/login") + Call loginUser( + @Query("username") String username, @Query("password") String password + ); + + + /** + * Logs out current logged in user session + * + * @return Call + */ + + @GET("user/logout") + Call logoutUser(); + + + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return Call + */ + + @GET("user/{username}") + Call getUserByName( + @Path("username") String username + ); + + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @return Call + */ + + @PUT("user/{username}") + Call updateUser( + @Path("username") String username, @Body User body + ); + + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return Call + */ + + @DELETE("user/{username}") + Call deleteUser( + @Path("username") String username + ); + + +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..59d01238796 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,68 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class ApiKeyAuth implements Interceptor { + private final String location; + private final String paramName; + + private String apiKey; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + @Override + public Response intercept(Chain chain) throws IOException { + String paramValue; + Request request = chain.request(); + + if (location == "query") { + String newQuery = request.uri().getQuery(); + paramValue = paramName + "=" + apiKey; + if (newQuery == null) { + newQuery = paramValue; + } else { + newQuery += "&" + paramValue; + } + + URI newUri; + try { + newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(), + request.uri().getPath(), newQuery, request.uri().getFragment()); + } catch (URISyntaxException e) { + throw new IOException(e); + } + + request = request.newBuilder().url(newUri.toURL()).build(); + } else if (location == "header") { + request = request.newBuilder() + .addHeader(paramName, apiKey) + .build(); + } + return chain.proceed(request); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..cb7c617767b --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,49 @@ +package io.swagger.client.auth; + +import java.io.IOException; + +import com.squareup.okhttp.Credentials; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class HttpBasicAuth implements Interceptor { + + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setCredentials(String username, String password) { + this.username = username; + this.password = password; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") == null) { + String credentials = Credentials.basic(username, password); + request = request.newBuilder() + .addHeader("Authorization", credentials) + .build(); + } + return chain.proceed(request); + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..80614f0f56a --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,161 @@ +package io.swagger.client.auth; + +import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; + +import java.io.IOException; +import java.util.Map; + +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; +import org.apache.oltu.oauth2.common.token.BasicOAuthToken; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Request.Builder; +import com.squareup.okhttp.Response; + +public class OAuth implements Interceptor { + + public interface AccessTokenListener { + public void notify(BasicOAuthToken token); + } + + private volatile String accessToken; + private OAuthClient oauthClient; + + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + + private AccessTokenListener accessTokenListener; + + public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) { + this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client)); + this.tokenRequestBuilder = requestBuilder; + } + + public OAuth(TokenRequestBuilder requestBuilder ) { + this(new OkHttpClient(), requestBuilder); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case accessCode: + case implicit: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) + throws IOException { + + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") != null) { + return chain.proceed(request); + } + + // If first time, get the token + OAuthClientRequest oAuthRequest; + if (getAccessToken() == null) { + updateAccessToken(null); + } + + // Build the request + Builder rb = request.newBuilder(); + + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.urlString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response.code() == HTTP_UNAUTHORIZED ) { + updateAccessToken(requestAccessToken); + return intercept( chain ); + } + return response; + } + + public synchronized void updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + try { + OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); + setAccessToken(accessTokenResponse.getAccessToken()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + } catch (OAuthSystemException e) { + throw new IOException(e); + } catch (OAuthProblemException e) { + throw new IOException(e); + } + } + } + + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { + return authenticationRequestBuilder; + } + + public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { + this.authenticationRequestBuilder = authenticationRequestBuilder; + } + +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 00000000000..597ec99b48b --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -0,0 +1,5 @@ +package io.swagger.client.auth; + +public enum OAuthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java new file mode 100644 index 00000000000..c872901ba24 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java @@ -0,0 +1,69 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; + + +public class OAuthOkHttpClient implements HttpClient { + + private OkHttpClient client; + + public OAuthOkHttpClient() { + this.client = new OkHttpClient(); + } + + public OAuthOkHttpClient(OkHttpClient client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + MediaType mediaType = MediaType.parse("application/json"); + Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); + + if(headers != null) { + for (Entry entry : headers.entrySet()) { + if (entry.getKey().equalsIgnoreCase("Content-Type")) { + mediaType = MediaType.parse(entry.getValue()); + } else { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; + requestBuilder.method(requestMethod, body); + + try { + Response response = client.newCall(requestBuilder.build()).execute(); + return OAuthClientResponseFactory.createCustomResponse( + response.body().string(), + response.body().contentType().toString(), + response.code(), + responseClass); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + } + + public void shutdown() { + // Nothing to do here + } + +} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java similarity index 64% rename from samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Category.java rename to samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java index 0d1945b5804..0a7023ac7a5 100644 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Category.java @@ -1,24 +1,29 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") public class Category { + @SerializedName("id") private Long id = null; + + @SerializedName("name") private String name = null; + /** **/ @ApiModelProperty(value = "") - @JsonProperty("id") public Long getId() { return id; } @@ -30,7 +35,6 @@ public class Category { /** **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } @@ -45,9 +49,9 @@ public class Category { StringBuilder sb = new StringBuilder(); sb.append("class Category {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java similarity index 57% rename from samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Order.java rename to samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java index 2a3892f2918..df8e77b6fb3 100644 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Order.java @@ -1,32 +1,65 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; import java.util.Date; +import com.google.gson.annotations.SerializedName; + import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") public class Order { + @SerializedName("id") private Long id = null; + + @SerializedName("petId") private Long petId = null; + + @SerializedName("quantity") private Integer quantity = null; + + @SerializedName("shipDate") private Date shipDate = null; - public enum StatusEnum { - placed, approved, delivered, - }; + + +public enum StatusEnum { + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") private StatusEnum status = null; + + @SerializedName("complete") private Boolean complete = null; + /** **/ @ApiModelProperty(value = "") - @JsonProperty("id") public Long getId() { return id; } @@ -38,7 +71,6 @@ public class Order { /** **/ @ApiModelProperty(value = "") - @JsonProperty("petId") public Long getPetId() { return petId; } @@ -50,7 +82,6 @@ public class Order { /** **/ @ApiModelProperty(value = "") - @JsonProperty("quantity") public Integer getQuantity() { return quantity; } @@ -62,7 +93,6 @@ public class Order { /** **/ @ApiModelProperty(value = "") - @JsonProperty("shipDate") public Date getShipDate() { return shipDate; } @@ -75,7 +105,6 @@ public class Order { * Order Status **/ @ApiModelProperty(value = "Order Status") - @JsonProperty("status") public StatusEnum getStatus() { return status; } @@ -87,7 +116,6 @@ public class Order { /** **/ @ApiModelProperty(value = "") - @JsonProperty("complete") public Boolean getComplete() { return complete; } @@ -102,13 +130,13 @@ public class Order { StringBuilder sb = new StringBuilder(); sb.append("class Order {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" petId: ").append(petId).append("\n"); - sb.append(" quantity: ").append(quantity).append("\n"); - sb.append(" shipDate: ").append(shipDate).append("\n"); - sb.append(" status: ").append(status).append("\n"); - sb.append(" complete: ").append(complete).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(StringUtil.toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(StringUtil.toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(StringUtil.toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(StringUtil.toIndentedString(complete)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java similarity index 60% rename from samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Pet.java rename to samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java index 6cb7df1fde5..9ab5457e26a 100644 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Pet.java @@ -1,34 +1,67 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import io.swagger.client.model.Tag; import java.util.*; +import io.swagger.client.model.Tag; + +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") public class Pet { + @SerializedName("id") private Long id = null; + + @SerializedName("category") private Category category = null; + + @SerializedName("name") private String name = null; + + @SerializedName("photoUrls") private List photoUrls = new ArrayList(); + + @SerializedName("tags") private List tags = new ArrayList(); - public enum StatusEnum { - available, pending, sold, - }; + + +public enum StatusEnum { + @SerializedName("available") + AVAILABLE("available"), + + @SerializedName("pending") + PENDING("pending"), + + @SerializedName("sold") + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") private StatusEnum status = null; + /** **/ @ApiModelProperty(value = "") - @JsonProperty("id") public Long getId() { return id; } @@ -40,7 +73,6 @@ public class Pet { /** **/ @ApiModelProperty(value = "") - @JsonProperty("category") public Category getCategory() { return category; } @@ -52,7 +84,6 @@ public class Pet { /** **/ @ApiModelProperty(required = true, value = "") - @JsonProperty("name") public String getName() { return name; } @@ -64,7 +95,6 @@ public class Pet { /** **/ @ApiModelProperty(required = true, value = "") - @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } @@ -76,7 +106,6 @@ public class Pet { /** **/ @ApiModelProperty(value = "") - @JsonProperty("tags") public List getTags() { return tags; } @@ -89,7 +118,6 @@ public class Pet { * pet status in the store **/ @ApiModelProperty(value = "pet status in the store") - @JsonProperty("status") public StatusEnum getStatus() { return status; } @@ -104,13 +132,13 @@ public class Pet { StringBuilder sb = new StringBuilder(); sb.append("class Pet {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" category: ").append(category).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append(" photoUrls: ").append(photoUrls).append("\n"); - sb.append(" tags: ").append(tags).append("\n"); - sb.append(" status: ").append(status).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" category: ").append(StringUtil.toIndentedString(category)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(StringUtil.toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(StringUtil.toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java similarity index 64% rename from samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Tag.java rename to samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java index fe212ea8ab6..9935b744f2d 100644 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Tag.java @@ -1,24 +1,29 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") public class Tag { + @SerializedName("id") private Long id = null; + + @SerializedName("name") private String name = null; + /** **/ @ApiModelProperty(value = "") - @JsonProperty("id") public Long getId() { return id; } @@ -30,7 +35,6 @@ public class Tag { /** **/ @ApiModelProperty(value = "") - @JsonProperty("name") public String getName() { return name; } @@ -45,9 +49,9 @@ public class Tag { StringBuilder sb = new StringBuilder(); sb.append("class Tag {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java similarity index 64% rename from samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/User.java rename to samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java index 5b9230b8e01..cba6abef8dd 100644 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/User.java @@ -1,30 +1,47 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; + @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") public class User { + @SerializedName("id") private Long id = null; + + @SerializedName("username") private String username = null; + + @SerializedName("firstName") private String firstName = null; + + @SerializedName("lastName") private String lastName = null; + + @SerializedName("email") private String email = null; + + @SerializedName("password") private String password = null; + + @SerializedName("phone") private String phone = null; + + @SerializedName("userStatus") private Integer userStatus = null; + /** **/ @ApiModelProperty(value = "") - @JsonProperty("id") public Long getId() { return id; } @@ -36,7 +53,6 @@ public class User { /** **/ @ApiModelProperty(value = "") - @JsonProperty("username") public String getUsername() { return username; } @@ -48,7 +64,6 @@ public class User { /** **/ @ApiModelProperty(value = "") - @JsonProperty("firstName") public String getFirstName() { return firstName; } @@ -60,7 +75,6 @@ public class User { /** **/ @ApiModelProperty(value = "") - @JsonProperty("lastName") public String getLastName() { return lastName; } @@ -72,7 +86,6 @@ public class User { /** **/ @ApiModelProperty(value = "") - @JsonProperty("email") public String getEmail() { return email; } @@ -84,7 +97,6 @@ public class User { /** **/ @ApiModelProperty(value = "") - @JsonProperty("password") public String getPassword() { return password; } @@ -96,7 +108,6 @@ public class User { /** **/ @ApiModelProperty(value = "") - @JsonProperty("phone") public String getPhone() { return phone; } @@ -109,7 +120,6 @@ public class User { * User Status **/ @ApiModelProperty(value = "User Status") - @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } @@ -124,15 +134,15 @@ public class User { StringBuilder sb = new StringBuilder(); sb.append("class User {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" username: ").append(username).append("\n"); - sb.append(" firstName: ").append(firstName).append("\n"); - sb.append(" lastName: ").append(lastName).append("\n"); - sb.append(" email: ").append(email).append("\n"); - sb.append(" password: ").append(password).append("\n"); - sb.append(" phone: ").append(phone).append("\n"); - sb.append(" userStatus: ").append(userStatus).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" username: ").append(StringUtil.toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(StringUtil.toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(StringUtil.toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(StringUtil.toIndentedString(email)).append("\n"); + sb.append(" password: ").append(StringUtil.toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(StringUtil.toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(StringUtil.toIndentedString(userStatus)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 00000000000..8522c4f30ad --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,160 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.*; + +import retrofit.Response; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.RequestBody; + +import static org.junit.Assert.*; + +public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(PetApi.class); + } + + @Test + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + Response rp2 = api.addPet(pet).execute(); + + Response rp = api.getPetById(pet.getId()).execute(); + Pet fetched = rp.body(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet).execute(); + + Pet fetched = api.getPetById(pet.getId()).execute().body(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet).execute(); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})).execute().body(); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet).execute(); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})).execute().body(); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet).execute(); + + Pet fetched = api.getPetById(pet.getId()).execute().body(); + + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null).execute(); + Pet updated = api.getPetById(fetched.getId()).execute().body(); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).execute(); + + Pet fetched = api.getPetById(pet.getId()).execute().body(); + api.deletePet(fetched.getId(), null).execute(); + + assertFalse(api.getPetById(fetched.getId()).execute().isSuccess()); + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet).execute(); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", RequestBody.create(MediaType.parse("text/plain"), file)).execute(); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(System.currentTimeMillis()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/StoreApiTest.java new file mode 100644 index 00000000000..786b0708702 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -0,0 +1,64 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.util.Map; + +import org.junit.*; + +import retrofit.Response; +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(StoreApi.class); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory().execute().body(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order).execute(); + + Order fetched = api.getOrderById(String.valueOf(order.getId())).execute().body(); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + Response aa = api.placeOrder(order).execute(); + + Order fetched = api.getOrderById(String.valueOf(order.getId())).execute().body(); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())).execute(); + + api.getOrderById(String.valueOf(order.getId())).execute(); + //also in retrofit 1 should return an error but don't, check server api impl. + } + + private Order createOrder() { + Order order = new Order(); + order.setId(new Long(System.currentTimeMillis())); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(new java.util.Date()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + return order; + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/UserApiTest.java new file mode 100644 index 00000000000..d496144c9f2 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -0,0 +1,84 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new ApiClient().createService(UserApi.class); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user).execute(); + + User fetched = api.getUserByName(user.getUsername()).execute().body(); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})).execute(); + + User fetched = api.getUserByName(user1.getUsername()).execute().body(); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})).execute(); + + User fetched = api.getUserByName(user1.getUsername()).execute().body(); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user).execute(); + + String token = api.loginUser(user.getUsername(), user.getPassword()).execute().body(); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser().execute(); + } + + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} \ No newline at end of file diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md new file mode 100644 index 00000000000..adfe2455d65 --- /dev/null +++ b/samples/client/petstore/perl/README.md @@ -0,0 +1,281 @@ +# NAME + +My::App + +# VERSION + +## Swagger Petstore version: 1.0.0 + +Automatically generated by the Perl Swagger Codegen project: + +- Build date: 2015-11-13T20:46:43.271Z +- Build package: class io.swagger.codegen.languages.PerlClientCodegen +- Codegen version: + +# INHERITANCE + +## Base class(es) + +Moose::Object + +## Direct subclasses + +## All subclasses + +# COMPOSITION + +My::App composes the following roles: + +## `WWW::SwaggerClient::Role` + +Requires: + +# METHODS + +## `add_pet()` + + Defined in: WWW::SwaggerClient::PetApi + Delegates to: add_pet() + On: WWW::SwaggerClient::PetApi + Via: pet_api() + Doc: Add a new pet to the store + Same as: $self->pet_api->add_pet() + +## `create_user()` + + Defined in: WWW::SwaggerClient::UserApi + Delegates to: create_user() + On: WWW::SwaggerClient::UserApi + Via: user_api() + Doc: Create user + Same as: $self->user_api->create_user() + +## `create_users_with_array_input()` + + Defined in: WWW::SwaggerClient::UserApi + Delegates to: create_users_with_array_input() + On: WWW::SwaggerClient::UserApi + Via: user_api() + Doc: Creates list of users with given input array + Same as: $self->user_api->create_users_with_array_input() + +## `create_users_with_list_input()` + + Defined in: WWW::SwaggerClient::UserApi + Delegates to: create_users_with_list_input() + On: WWW::SwaggerClient::UserApi + Via: user_api() + Doc: Creates list of users with given input array + Same as: $self->user_api->create_users_with_list_input() + +## `delete_order()` + + Defined in: WWW::SwaggerClient::StoreApi + Delegates to: delete_order() + On: WWW::SwaggerClient::StoreApi + Via: store_api() + Doc: Delete purchase order by ID + Same as: $self->store_api->delete_order() + +## `delete_pet()` + + Defined in: WWW::SwaggerClient::PetApi + Delegates to: delete_pet() + On: WWW::SwaggerClient::PetApi + Via: pet_api() + Doc: Deletes a pet + Same as: $self->pet_api->delete_pet() + +## `delete_user()` + + Defined in: WWW::SwaggerClient::UserApi + Delegates to: delete_user() + On: WWW::SwaggerClient::UserApi + Via: user_api() + Doc: Delete user + Same as: $self->user_api->delete_user() + +## `find_pets_by_status()` + + Defined in: WWW::SwaggerClient::PetApi + Delegates to: find_pets_by_status() + On: WWW::SwaggerClient::PetApi + Via: pet_api() + Doc: Finds Pets by status + Same as: $self->pet_api->find_pets_by_status() + +## `find_pets_by_tags()` + + Defined in: WWW::SwaggerClient::PetApi + Delegates to: find_pets_by_tags() + On: WWW::SwaggerClient::PetApi + Via: pet_api() + Doc: Finds Pets by tags + Same as: $self->pet_api->find_pets_by_tags() + +## `get_inventory()` + + Defined in: WWW::SwaggerClient::StoreApi + Delegates to: get_inventory() + On: WWW::SwaggerClient::StoreApi + Via: store_api() + Doc: Returns pet inventories by status + Same as: $self->store_api->get_inventory() + +## `get_order_by_id()` + + Defined in: WWW::SwaggerClient::StoreApi + Delegates to: get_order_by_id() + On: WWW::SwaggerClient::StoreApi + Via: store_api() + Doc: Find purchase order by ID + Same as: $self->store_api->get_order_by_id() + +## `get_pet_by_id()` + + Defined in: WWW::SwaggerClient::PetApi + Delegates to: get_pet_by_id() + On: WWW::SwaggerClient::PetApi + Via: pet_api() + Doc: Find pet by ID + Same as: $self->pet_api->get_pet_by_id() + +## `get_user_by_name()` + + Defined in: WWW::SwaggerClient::UserApi + Delegates to: get_user_by_name() + On: WWW::SwaggerClient::UserApi + Via: user_api() + Doc: Get user by user name + Same as: $self->user_api->get_user_by_name() + +## `login_user()` + + Defined in: WWW::SwaggerClient::UserApi + Delegates to: login_user() + On: WWW::SwaggerClient::UserApi + Via: user_api() + Doc: Logs user into the system + Same as: $self->user_api->login_user() + +## `logout_user()` + + Defined in: WWW::SwaggerClient::UserApi + Delegates to: logout_user() + On: WWW::SwaggerClient::UserApi + Via: user_api() + Doc: Logs out current logged in user session + Same as: $self->user_api->logout_user() + +## `place_order()` + + Defined in: WWW::SwaggerClient::StoreApi + Delegates to: place_order() + On: WWW::SwaggerClient::StoreApi + Via: store_api() + Doc: Place an order for a pet + Same as: $self->store_api->place_order() + +## `update_pet()` + + Defined in: WWW::SwaggerClient::PetApi + Delegates to: update_pet() + On: WWW::SwaggerClient::PetApi + Via: pet_api() + Doc: Update an existing pet + Same as: $self->pet_api->update_pet() + +## `update_pet_with_form()` + + Defined in: WWW::SwaggerClient::PetApi + Delegates to: update_pet_with_form() + On: WWW::SwaggerClient::PetApi + Via: pet_api() + Doc: Updates a pet in the store with form data + Same as: $self->pet_api->update_pet_with_form() + +## `update_user()` + + Defined in: WWW::SwaggerClient::UserApi + Delegates to: update_user() + On: WWW::SwaggerClient::UserApi + Via: user_api() + Doc: Updated user + Same as: $self->user_api->update_user() + +## `upload_file()` + + Defined in: WWW::SwaggerClient::PetApi + Delegates to: upload_file() + On: WWW::SwaggerClient::PetApi + Via: pet_api() + Doc: uploads an image + Same as: $self->pet_api->upload_file() + +# ATTRIBUTES + +## `api_factory` + + is: ro + isa: WWW::SwaggerClient::ApiFactory + reqd: no + lazy: yes + doc: Builds an instance of the endpoint API class + handles: + +## `base_url` + + is: ro + isa: Str + reqd: no + lazy: no + doc: Root of the server that requests are sent to + handles: + +## `pet_api` + + is: ro + isa: WWW::SwaggerClient::PetApi + reqd: no + lazy: yes + doc: + handles: add_pet, delete_pet, find_pets_by_status, find_pets_by_tags, + get_pet_by_id, update_pet, update_pet_with_form, upload_file + +## `store_api` + + is: ro + isa: WWW::SwaggerClient::StoreApi + reqd: no + lazy: yes + doc: + handles: delete_order, get_inventory, get_order_by_id, place_order + +## `tokens` + + is: ro + isa: HashRef + reqd: no + lazy: no + doc: The auth tokens required by the application - basic, OAuth and/or API key(s) + handles: + +## `user_api` + + is: ro + isa: WWW::SwaggerClient::UserApi + reqd: no + lazy: yes + doc: + handles: create_user, create_users_with_array_input, + create_users_with_list_input, delete_user, get_user_by_name, + login_user, logout_user, update_user + +## `version_info` + + is: ro + isa: HashRef + reqd: no + lazy: no + doc: Information about the application version and the codegen codebase version + handles: diff --git a/samples/client/petstore/perl/bin/autodoc b/samples/client/petstore/perl/bin/autodoc new file mode 100644 index 00000000000..049fcf7fecf --- /dev/null +++ b/samples/client/petstore/perl/bin/autodoc @@ -0,0 +1,77 @@ +#!/usr/bin/perl +use FindBin; +use File::Spec; +use lib File::Spec->catdir($FindBin::Bin, '..', 'lib'); + +use Moose::Util qw(apply_all_roles); +use Getopt::Std; + +my %options=(); +getopts("wnphmHc:", \%options); +help if $options{h}; + +my $my_app = $options{c} || 'My::App'; + +if ($options{c}) { + eval <new; + +if ($options{H}) { + my $pod2html = "pod2html --backlink --css http://st.pimg.net/tucs/style.css?3"; + open STDOUT, "| $pod2html" or die "Can't fork: $!"; + $api->autodoc($opt); + close STDOUT or die "Can't close: $!"; +} +elsif ($options{m}) { + my $pod2markdown = "pod2markdown --html-encode-chars 1"; + open STDOUT, "| $pod2markdown" or die "Can't fork: $!"; + $api->autodoc($opt); + close STDOUT or die "Can't close: $!"; +} +else { + $api->autodoc($opt); +} + +exit(0); + +# -------------------- +sub help { + print <{ua}->timeout($self->{http_timeout} || $WWW::SwaggerClient::Configuration::http_timeout); $self->{ua}->agent($self->{http_user_agent} || $WWW::SwaggerClient::Configuration::http_user_agent); + $log->debugf("REQUEST: %s", $_request->as_string); my $_response = $self->{ua}->request($_request); + $log->debugf("RESPONSE: %s", $_response->as_string); unless ($_response->is_success) { - croak("API Exception(".$_response->code."): ".$_response->message); + croak(sprintf "API Exception(%s): %s\n%s", $_response->code, $_response->message, $_response->content); } return $_response->content; @@ -146,8 +152,8 @@ sub to_path_value { # @return string the serialized object sub to_query_value { my ($self, $object) = @_; - if (is_array($object)) { - return implode(',', $object); + if (ref($object) eq 'ARRAY') { + return join(',', @$object); } else { return $self->to_string($object); } @@ -286,23 +292,26 @@ sub select_header_content_type # @return string API key with the prefix sub get_api_key_with_prefix { - my ($self, $api_key) = @_; - if ($WWW::SwaggerClient::Configuration::api_key_prefix->{$api_key}) { - return $WWW::SwaggerClient::Configuration::api_key_prefix->{$api_key}." ".$WWW::SwaggerClient::Configuration::api_key->{$api_key}; - } else { - return $WWW::SwaggerClient::Configuration::api_key->{$api_key}; - } -} + my ($self, $key_name) = @_; -# update hearder and query param based on authentication setting + my $api_key = $WWW::SwaggerClient::Configuration::api_key->{$key_name}; + + return unless $api_key; + + my $prefix = $WWW::SwaggerClient::Configuration::api_key_prefix->{$key_name}; + return $prefix ? "$prefix $api_key" : $api_key; +} + +# update header and query param based on authentication setting # # @param array $headerParams header parameters (by ref) # @param array $queryParams query parameters (by ref) # @param array $authSettings array of authentication scheme (e.g ['api_key']) sub update_params_for_auth { my ($self, $header_params, $query_params, $auth_settings) = @_; - - return if (!defined($auth_settings) || scalar(@$auth_settings) == 0); + + return $self->_global_auth_setup($header_params, $query_params) + unless $auth_settings && @$auth_settings; # one endpoint can have more than 1 auth settings foreach my $auth (@$auth_settings) { @@ -315,14 +324,51 @@ sub update_params_for_auth { } elsif ($auth eq 'petstore_auth') { - # TODO support oauth + $header_params->{'Authorization'} = 'Bearer ' . $WWW::SwaggerClient::Configuration::access_token; } else { - # TODO show warning about security definition not found + # TODO show warning about security definition not found } } } +# The endpoint API class has not found any settings for auth. This may be deliberate, +# in which case update_params_for_auth() will be a no-op. But it may also be that the +# swagger spec does not describe the intended authorization. So we check in the config for any +# auth tokens and if we find any, we use them for all endpoints; +sub _global_auth_setup { + my ($self, $header_params, $query_params) = @_; + + my $tokens = $self->_cfg->get_tokens; + return unless keys %$tokens; + + # basic + if (my $uname = delete $tokens->{username}) { + my $pword = delete $tokens->{password}; + $header_params->{'Authorization'} = 'Basic '.encode_base64($uname.":".$pword); + } + + # oauth + if (my $access_token = delete $tokens->{access_token}) { + $header_params->{'Authorization'} = 'Bearer ' . $access_token; + } + + # other keys + foreach my $token_name (keys %$tokens) { + my $in = $tokens->{$token_name}->{in}; + my $token = $self->get_api_key_with_prefix($token_name); + if ($in eq 'head') { + $header_params->{$token_name} = $token; + } + elsif ($in eq 'query') { + $query_params->{$token_name} = $token; + } + else { + die "Don't know where to put token '$token_name' ('$in' is not 'head' or 'query')"; + } + } +} + 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm new file mode 100644 index 00000000000..f0846a9b594 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm @@ -0,0 +1,100 @@ +package WWW::SwaggerClient::ApiFactory; + +use strict; +use warnings; +use utf8; + +use Carp; +use Module::Find; + +usesub WWW::SwaggerClient::Object; + +use WWW::SwaggerClient::ApiClient; + +=head1 Name + + WWW::SwaggerClient::ApiFactory - constructs APIs to retrieve SwaggerClient objects + +=head1 Synopsis + + package My::Petstore::App; + + use WWW::SwaggerClient::ApiFactory; + + my $api_factory = WWW::SwaggerClient::ApiFactory->new( ... ); # any args for ApiClient constructor + + # later... + my $pet_api = $api_factory->get_api('Pet'); + + # $pet_api isa WWW::SwaggerClient::PetApi + + my $pet = $pet_api->get_pet_by_id(pet_id => $pet_id); + + # object attributes have proper accessors: + printf "Pet's name is %s", $pet->name; + + # change the value stored on the object: + $pet->name('Dave'); + +=cut + +# Load all the API classes and construct a lookup table at startup time +my %_apis = map { $_ =~ /^WWW::SwaggerClient::(.*)$/; $1 => $_ } + grep {$_ =~ /Api$/} + usesub 'WWW::SwaggerClient'; + +=head1 new() + + Any parameters are optional, and are passed to and stored on the api_client object. + + base_url: (optional) + supply this to change the default base URL taken from the Swagger definition. + +=cut + +sub new { + my ($class, %p) = (shift, @_); + $p{api_client} = WWW::SwaggerClient::ApiClient->instance(%p); + return bless \%p, $class; +} + +=head1 get_api($which) + + Returns an API object of the requested type. + + $which is a nickname for the class: + + WWW::FooBarClient::BazApi has nickname 'Baz' + +=cut + +sub get_api { + my ($self, $which) = @_; + croak "API not specified" unless $which; + my $api_class = $_apis{"${which}Api"} || croak "No known API for '$which'"; + return $api_class->new(api_client => $self->api_client); +} + +=head1 api_client() + + Returns the api_client object, should you ever need it. + +=cut + +sub api_client { $_[0]->{api_client} } + +=head1 apis_available() +=cut + +sub apis_available { return map { $_ =~ s/Api$//; $_ } sort keys %_apis } + +=head1 classname_for() +=cut + +sub classname_for { + my ($self, $api_name) = @_; + return $_apis{"${api_name}Api"}; +} + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm index aaa387236d9..150db4cfac2 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm @@ -10,15 +10,71 @@ use Carp; use constant VERSION => '1.0.0'; # class/static variables -our $api_client; our $http_timeout = 180; our $http_user_agent = 'Perl-Swagger'; # authenticaiton setting our $api_key = {}; our $api_key_prefix = {}; -our $username; -our $password; +our $api_key_in = {}; +# username and password for HTTP basic authentication +our $username = ''; +our $password = ''; + +# access token for OAuth +our $access_token = ''; + +sub get_tokens { + my $class = shift; + + my $tokens = {}; + $tokens->{username} = $username if $username; + $tokens->{password} = $password if $password; + $tokens->{access_token} = $access_token if $access_token; + + foreach my $token_name (keys %{ $api_key }) { + $tokens->{$token_name}->{token} = $api_key->{$token_name}; + $tokens->{$token_name}->{prefix} = $api_key_prefix->{$token_name}; + $tokens->{$token_name}->{in} = $api_key_in->{$token_name}; + } + + return $tokens; +} + +sub clear_tokens { + my $class = shift; + my %tokens = %{$class->get_tokens}; # copy + + $username = undef; + $password = undef; + $access_token = undef; + + $api_key = {}; + $api_key_prefix = {}; + $api_key_in = {}; + + return \%tokens; +} + +sub accept_tokens { + my ($class, $tokens) = @_; + + foreach my $known_name (qw(username password access_token)) { + next unless $tokens->{$known_name}; + eval "\$$known_name = delete \$tokens->{\$known_name}"; + die $@ if $@; + } + + foreach my $token_name (keys %$tokens) { + $api_key->{$token_name} = $tokens->{$token_name}->{token}; + if ($tokens->{$token_name}->{prefix}) { + $api_key_prefix->{$token_name} = $tokens->{$token_name}->{prefix}; + } + my $in = $tokens->{$token_name}->{in} || 'head'; + croak "Tokens can only go in 'head' or 'query' (not in '$in')" unless $in =~ /^(?:head|query)$/; + $api_key_in->{$token_name} = $in; + } +} 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm index af1ac1c6017..f99b7715ae8 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm @@ -11,6 +11,8 @@ use Log::Any qw($log); use Date::Parse; use DateTime; +use base ("Class::Accessor", "Class::Data::Inheritable"); + # # @@ -18,8 +20,26 @@ use DateTime; #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); -# return json string +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash sub to_hash { return decode_json(JSON->new->convert_blessed->encode( shift )); } @@ -28,36 +48,38 @@ sub to_hash { sub TO_JSON { my $self = shift; my $_data = {}; - foreach my $_key (keys %{$self->get_attribute_map}) { + foreach my $_key (keys %{$self->attribute_map}) { if (defined $self->{$_key}) { - $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; } } return $_data; } -# from json string +# from Perl hashref sub from_hash { my ($self, $hash) = @_; + # loop through attributes and use swagger_types to deserialize the data - while ( my ($_key, $_type) = each %{$self->get_swagger_types} ) { + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; if ($_type =~ /^array\[/i) { # array my $_subclass = substr($_type, 6, -1); my @_array = (); - foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { + foreach my $_element (@{$hash->{$_json_attribute}}) { push @_array, $self->_deserialize($_subclass, $_element); } $self->{$_key} = \@_array; - } elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime - $self->{$_key} = $self->_deserialize($_type, $hash->{$_key}); + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); } else { - $log->debugf("warning: %s not defined\n", $_key); + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); } } return $self; } - + # deserialize non-array data sub _deserialize { my ($self, $type, $data) = @_; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm index 2b2c0beceac..43c12b040c7 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm @@ -19,37 +19,39 @@ use base "WWW::SwaggerClient::Object::BaseObject"; #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # -my $swagger_types = { +__PACKAGE__->class_documentation({description => '', + class => 'Category', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'id' => { + datatype => 'int', + base_name => 'id', + description => '', + format => '', + read_only => '', + }, + 'name' => { + datatype => 'string', + base_name => 'name', + description => '', + format => '', + read_only => '', + }, + +}); + +__PACKAGE__->swagger_types( { 'id' => 'int', 'name' => 'string' -}; +} ); -my $attribute_map = { +__PACKAGE__->attribute_map( { 'id' => 'id', 'name' => 'name' -}; +} ); -# new object -sub new { - my ($class, %args) = @_; - my $self = { - # - 'id' => $args{'id'}, - # - 'name' => $args{'name'} - }; - - return bless $self, $class; -} - -# get swagger type of the attribute -sub get_swagger_types { - return $swagger_types; -} - -# get attribute mappping -sub get_attribute_map { - return $attribute_map; -} +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm index 14da4a5f3af..ea5f6160ee5 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm @@ -19,53 +19,75 @@ use base "WWW::SwaggerClient::Object::BaseObject"; #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # -my $swagger_types = { +__PACKAGE__->class_documentation({description => '', + class => 'Order', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'id' => { + datatype => 'int', + base_name => 'id', + description => '', + format => '', + read_only => '', + }, + 'pet_id' => { + datatype => 'int', + base_name => 'petId', + description => '', + format => '', + read_only => '', + }, + 'quantity' => { + datatype => 'int', + base_name => 'quantity', + description => '', + format => '', + read_only => '', + }, + 'ship_date' => { + datatype => 'DateTime', + base_name => 'shipDate', + description => '', + format => '', + read_only => '', + }, + 'status' => { + datatype => 'string', + base_name => 'status', + description => 'Order Status', + format => '', + read_only => '', + }, + 'complete' => { + datatype => 'boolean', + base_name => 'complete', + description => '', + format => '', + read_only => '', + }, + +}); + +__PACKAGE__->swagger_types( { 'id' => 'int', 'pet_id' => 'int', 'quantity' => 'int', 'ship_date' => 'DateTime', 'status' => 'string', 'complete' => 'boolean' -}; +} ); -my $attribute_map = { +__PACKAGE__->attribute_map( { 'id' => 'id', 'pet_id' => 'petId', 'quantity' => 'quantity', 'ship_date' => 'shipDate', 'status' => 'status', 'complete' => 'complete' -}; +} ); -# new object -sub new { - my ($class, %args) = @_; - my $self = { - # - 'id' => $args{'id'}, - # - 'pet_id' => $args{'petId'}, - # - 'quantity' => $args{'quantity'}, - # - 'ship_date' => $args{'shipDate'}, - #Order Status - 'status' => $args{'status'}, - # - 'complete' => $args{'complete'} - }; - - return bless $self, $class; -} - -# get swagger type of the attribute -sub get_swagger_types { - return $swagger_types; -} - -# get attribute mappping -sub get_attribute_map { - return $attribute_map; -} +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm index eb74ad3f368..a1aeb134178 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm @@ -19,53 +19,75 @@ use base "WWW::SwaggerClient::Object::BaseObject"; #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # -my $swagger_types = { +__PACKAGE__->class_documentation({description => '', + class => 'Pet', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'id' => { + datatype => 'int', + base_name => 'id', + description => '', + format => '', + read_only => '', + }, + 'category' => { + datatype => 'Category', + base_name => 'category', + description => '', + format => '', + read_only => '', + }, + 'name' => { + datatype => 'string', + base_name => 'name', + description => '', + format => '', + read_only => '', + }, + 'photo_urls' => { + datatype => 'ARRAY[string]', + base_name => 'photoUrls', + description => '', + format => '', + read_only => '', + }, + 'tags' => { + datatype => 'ARRAY[Tag]', + base_name => 'tags', + description => '', + format => '', + read_only => '', + }, + 'status' => { + datatype => 'string', + base_name => 'status', + description => 'pet status in the store', + format => '', + read_only => '', + }, + +}); + +__PACKAGE__->swagger_types( { 'id' => 'int', 'category' => 'Category', 'name' => 'string', 'photo_urls' => 'ARRAY[string]', 'tags' => 'ARRAY[Tag]', 'status' => 'string' -}; +} ); -my $attribute_map = { +__PACKAGE__->attribute_map( { 'id' => 'id', 'category' => 'category', 'name' => 'name', 'photo_urls' => 'photoUrls', 'tags' => 'tags', 'status' => 'status' -}; +} ); -# new object -sub new { - my ($class, %args) = @_; - my $self = { - # - 'id' => $args{'id'}, - # - 'category' => $args{'category'}, - # - 'name' => $args{'name'}, - # - 'photo_urls' => $args{'photoUrls'}, - # - 'tags' => $args{'tags'}, - #pet status in the store - 'status' => $args{'status'} - }; - - return bless $self, $class; -} - -# get swagger type of the attribute -sub get_swagger_types { - return $swagger_types; -} - -# get attribute mappping -sub get_attribute_map { - return $attribute_map; -} +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm index 1b136d5fbfc..a50eded7cde 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm @@ -19,37 +19,39 @@ use base "WWW::SwaggerClient::Object::BaseObject"; #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # -my $swagger_types = { +__PACKAGE__->class_documentation({description => '', + class => 'Tag', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'id' => { + datatype => 'int', + base_name => 'id', + description => '', + format => '', + read_only => '', + }, + 'name' => { + datatype => 'string', + base_name => 'name', + description => '', + format => '', + read_only => '', + }, + +}); + +__PACKAGE__->swagger_types( { 'id' => 'int', 'name' => 'string' -}; +} ); -my $attribute_map = { +__PACKAGE__->attribute_map( { 'id' => 'id', 'name' => 'name' -}; +} ); -# new object -sub new { - my ($class, %args) = @_; - my $self = { - # - 'id' => $args{'id'}, - # - 'name' => $args{'name'} - }; - - return bless $self, $class; -} - -# get swagger type of the attribute -sub get_swagger_types { - return $swagger_types; -} - -# get attribute mappping -sub get_attribute_map { - return $attribute_map; -} +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm index 1beb8f0b201..cb431b1e059 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm @@ -19,7 +19,72 @@ use base "WWW::SwaggerClient::Object::BaseObject"; #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # -my $swagger_types = { +__PACKAGE__->class_documentation({description => '', + class => 'User', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'id' => { + datatype => 'int', + base_name => 'id', + description => '', + format => '', + read_only => '', + }, + 'username' => { + datatype => 'string', + base_name => 'username', + description => '', + format => '', + read_only => '', + }, + 'first_name' => { + datatype => 'string', + base_name => 'firstName', + description => '', + format => '', + read_only => '', + }, + 'last_name' => { + datatype => 'string', + base_name => 'lastName', + description => '', + format => '', + read_only => '', + }, + 'email' => { + datatype => 'string', + base_name => 'email', + description => '', + format => '', + read_only => '', + }, + 'password' => { + datatype => 'string', + base_name => 'password', + description => '', + format => '', + read_only => '', + }, + 'phone' => { + datatype => 'string', + base_name => 'phone', + description => '', + format => '', + read_only => '', + }, + 'user_status' => { + datatype => 'int', + base_name => 'userStatus', + description => 'User Status', + format => '', + read_only => '', + }, + +}); + +__PACKAGE__->swagger_types( { 'id' => 'int', 'username' => 'string', 'first_name' => 'string', @@ -28,9 +93,9 @@ my $swagger_types = { 'password' => 'string', 'phone' => 'string', 'user_status' => 'int' -}; +} ); -my $attribute_map = { +__PACKAGE__->attribute_map( { 'id' => 'id', 'username' => 'username', 'first_name' => 'firstName', @@ -39,41 +104,8 @@ my $attribute_map = { 'password' => 'password', 'phone' => 'phone', 'user_status' => 'userStatus' -}; +} ); -# new object -sub new { - my ($class, %args) = @_; - my $self = { - # - 'id' => $args{'id'}, - # - 'username' => $args{'username'}, - # - 'first_name' => $args{'firstName'}, - # - 'last_name' => $args{'lastName'}, - # - 'email' => $args{'email'}, - # - 'password' => $args{'password'}, - # - 'phone' => $args{'phone'}, - #User Status - 'user_status' => $args{'userStatus'} - }; - - return bless $self, $class; -} - -# get swagger type of the attribute -sub get_swagger_types { - return $swagger_types; -} - -# get attribute mappping -sub get_attribute_map { - return $attribute_map; -} +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 19a3d88b299..06ccfca98e8 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -30,11 +30,14 @@ use Log::Any qw($log); use WWW::SwaggerClient::ApiClient; use WWW::SwaggerClient::Configuration; +use base "Class::Data::Inheritable"; + +__PACKAGE__->mk_classdata('method_documentation' => {}); + sub new { my $class = shift; - my $default_api_client = $WWW::SwaggerClient::Configuration::api_client ? $WWW::SwaggerClient::Configuration::api_client : WWW::SwaggerClient::ApiClient->new; my (%self) = ( - 'api_client' => $default_api_client, + 'api_client' => WWW::SwaggerClient::ApiClient->instance, @_ ); @@ -47,12 +50,27 @@ sub new { } + # # update_pet # # Update an existing pet # # @param Pet $body Pet object that needs to be added to the store (optional) +{ + my $params = { + 'body' => { + data_type => 'Pet', + description => 'Pet object that needs to be added to the store', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ update_pet } = { + summary => 'Update an existing pet', + params => $params, + returns => undef, + }; +} # @return void # sub update_pet { @@ -87,7 +105,7 @@ sub update_pet { } # authentication setting, if any - my $auth_settings = ['petstore_auth']; + my $auth_settings = [qw(petstore_auth )]; # make the API Call @@ -97,12 +115,27 @@ sub update_pet { return; } + # # add_pet # # Add a new pet to the store # # @param Pet $body Pet object that needs to be added to the store (optional) +{ + my $params = { + 'body' => { + data_type => 'Pet', + description => 'Pet object that needs to be added to the store', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ add_pet } = { + summary => 'Add a new pet to the store', + params => $params, + returns => undef, + }; +} # @return void # sub add_pet { @@ -137,7 +170,7 @@ sub add_pet { } # authentication setting, if any - my $auth_settings = ['petstore_auth']; + my $auth_settings = [qw(petstore_auth )]; # make the API Call @@ -147,12 +180,27 @@ sub add_pet { return; } + # # find_pets_by_status # # Finds Pets by status # # @param ARRAY[string] $status Status values that need to be considered for filter (optional) +{ + my $params = { + 'status' => { + data_type => 'ARRAY[string]', + description => 'Status values that need to be considered for filter', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ find_pets_by_status } = { + summary => 'Finds Pets by status', + params => $params, + returns => 'ARRAY[Pet]', + }; +} # @return ARRAY[Pet] # sub find_pets_by_status { @@ -187,7 +235,7 @@ sub find_pets_by_status { # authentication setting, if any - my $auth_settings = ['petstore_auth']; + my $auth_settings = [qw(petstore_auth )]; # make the API Call my $response = $self->{api_client}->call_api($_resource_path, $_method, @@ -200,12 +248,27 @@ sub find_pets_by_status { return $_response_object; } + # # find_pets_by_tags # # Finds Pets by tags # # @param ARRAY[string] $tags Tags to filter by (optional) +{ + my $params = { + 'tags' => { + data_type => 'ARRAY[string]', + description => 'Tags to filter by', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ find_pets_by_tags } = { + summary => 'Finds Pets by tags', + params => $params, + returns => 'ARRAY[Pet]', + }; +} # @return ARRAY[Pet] # sub find_pets_by_tags { @@ -240,7 +303,7 @@ sub find_pets_by_tags { # authentication setting, if any - my $auth_settings = ['petstore_auth']; + my $auth_settings = [qw(petstore_auth )]; # make the API Call my $response = $self->{api_client}->call_api($_resource_path, $_method, @@ -253,12 +316,27 @@ sub find_pets_by_tags { return $_response_object; } + # # get_pet_by_id # # Find pet by ID # # @param int $pet_id ID of pet that needs to be fetched (required) +{ + my $params = { + 'pet_id' => { + data_type => 'int', + description => 'ID of pet that needs to be fetched', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ get_pet_by_id } = { + summary => 'Find pet by ID', + params => $params, + returns => 'Pet', + }; +} # @return Pet # sub get_pet_by_id { @@ -300,7 +378,7 @@ sub get_pet_by_id { # authentication setting, if any - my $auth_settings = ['api_key', 'petstore_auth']; + my $auth_settings = [qw(api_key )]; # make the API Call my $response = $self->{api_client}->call_api($_resource_path, $_method, @@ -313,6 +391,7 @@ sub get_pet_by_id { return $_response_object; } + # # update_pet_with_form # @@ -321,6 +400,30 @@ sub get_pet_by_id { # @param string $pet_id ID of pet that needs to be updated (required) # @param string $name Updated name of the pet (optional) # @param string $status Updated status of the pet (optional) +{ + my $params = { + 'pet_id' => { + data_type => 'string', + description => 'ID of pet that needs to be updated', + required => '1', + }, + 'name' => { + data_type => 'string', + description => 'Updated name of the pet', + required => '0', + }, + 'status' => { + data_type => 'string', + description => 'Updated status of the pet', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ update_pet_with_form } = { + summary => 'Updates a pet in the store with form data', + params => $params, + returns => undef, + }; +} # @return void # sub update_pet_with_form { @@ -372,7 +475,7 @@ sub update_pet_with_form { # authentication setting, if any - my $auth_settings = ['petstore_auth']; + my $auth_settings = [qw(petstore_auth )]; # make the API Call @@ -382,6 +485,7 @@ sub update_pet_with_form { return; } + # # delete_pet # @@ -389,6 +493,25 @@ sub update_pet_with_form { # # @param int $pet_id Pet id to delete (required) # @param string $api_key (optional) +{ + my $params = { + 'pet_id' => { + data_type => 'int', + description => 'Pet id to delete', + required => '1', + }, + 'api_key' => { + data_type => 'string', + description => '', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ delete_pet } = { + summary => 'Deletes a pet', + params => $params, + returns => undef, + }; +} # @return void # sub delete_pet { @@ -433,7 +556,7 @@ sub delete_pet { # authentication setting, if any - my $auth_settings = ['petstore_auth']; + my $auth_settings = [qw(petstore_auth )]; # make the API Call @@ -443,6 +566,7 @@ sub delete_pet { return; } + # # upload_file # @@ -451,6 +575,30 @@ sub delete_pet { # @param int $pet_id ID of pet to update (required) # @param string $additional_metadata Additional data to pass to server (optional) # @param file $file file to upload (optional) +{ + my $params = { + 'pet_id' => { + data_type => 'int', + description => 'ID of pet to update', + required => '1', + }, + 'additional_metadata' => { + data_type => 'string', + description => 'Additional data to pass to server', + required => '0', + }, + 'file' => { + data_type => 'file', + description => 'file to upload', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ upload_file } = { + summary => 'uploads an image', + params => $params, + returns => undef, + }; +} # @return void # sub upload_file { @@ -495,7 +643,7 @@ sub upload_file { }# form params if ( exists $args{'file'} ) { $form_params->{'file'} = [] unless defined $form_params->{'file'}; - push $form_params->{'file'}, $args{'file'}; + push @{$form_params->{'file'}}, $args{'file'}; } @@ -503,7 +651,7 @@ sub upload_file { # authentication setting, if any - my $auth_settings = ['petstore_auth']; + my $auth_settings = [qw(petstore_auth )]; # make the API Call diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm new file mode 100644 index 00000000000..feb5228cb61 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm @@ -0,0 +1,323 @@ +package WWW::SwaggerClient::Role; +use utf8; + +use Moose::Role; +use namespace::autoclean; +use Class::Inspector; +use Log::Any qw($log); +use WWW::SwaggerClient::ApiFactory; + +has base_url => ( is => 'ro', + required => 0, + isa => 'Str', + documentation => 'Root of the server that requests are sent to', + ); + +has api_factory => ( is => 'ro', + isa => 'WWW::SwaggerClient::ApiFactory', + builder => '_build_af', + lazy => 1, + documentation => 'Builds an instance of the endpoint API class', + ); + +has tokens => ( is => 'ro', + isa => 'HashRef', + required => 0, + default => sub { {} }, + documentation => 'The auth tokens required by the application - basic, OAuth and/or API key(s)', + ); + +has _cfg => ( is => 'ro', + isa => 'Str', + default => 'WWW::SwaggerClient::Configuration', + ); + +has version_info => ( is => 'ro', + isa => 'HashRef', + default => sub { { + app_name => 'Swagger Petstore', + app_version => '1.0.0', + generated_date => '2015-11-13T20:46:43.271Z', + generator_class => 'class io.swagger.codegen.languages.PerlClientCodegen', + } }, + documentation => 'Information about the application version and the codegen codebase version' + ); + +sub BUILD { + my $self = shift; + + $self->_cfg->accept_tokens( $self->tokens ) if keys %{$self->tokens}; + + # ignore these symbols imported into API namespaces + my %outsiders = map {$_ => 1} qw( croak ); + + my %delegates; + + # collect the methods callable on each API + foreach my $api_name ($self->api_factory->apis_available) { + my $api_class = $self->api_factory->classname_for($api_name); + my $methods = Class::Inspector->methods($api_class, 'expanded'); # not Moose, so use CI instead + my @local_methods = grep {! /^_/} grep {! $outsiders{$_}} map {$_->[2]} grep {$_->[1] eq $api_class} @$methods; + push( @{$delegates{$_}}, {api_name => $api_name, api_class => $api_class} ) for @local_methods; + } + + # remove clashes + foreach my $method (keys %delegates) { + if ( @{$delegates{$method}} > 1 ) { + my ($apis) = delete $delegates{$method}; + } + } + + # build the flattened API + foreach my $api_name ($self->api_factory->apis_available) { + my $att_name = sprintf "%s_api", lc($api_name); + my $api_class = $self->api_factory->classname_for($api_name); + my @delegated = grep { $delegates{$_}->[0]->{api_name} eq $api_name } keys %delegates; + $log->debugf("Adding API: '%s' handles %s", $att_name, join ', ', @delegated); + $self->meta->add_attribute( $att_name => ( + is => 'ro', + isa => $api_class, + default => sub {$self->api_factory->get_api($api_name)}, + lazy => 1, + handles => \@delegated, + ) ); + } +} + +sub _build_af { + my $self = shift; + my %args; + $args{base_url} = $self->base_url if $self->base_url; + return WWW::SwaggerClient::ApiFactory->new(%args); +} + +=head1 NAME + +WWW::SwaggerClient::Role - a Moose role for the Swagger Petstore + +=head2 Swagger Petstore version: 1.0.0 + +=head1 VERSION + +Automatically generated by the Perl Swagger Codegen project: + +=over 4 + +=item Build date: 2015-11-13T20:46:43.271Z + +=item Build package: class io.swagger.codegen.languages.PerlClientCodegen + +=item Codegen version: + +=back + +=head2 A note on Moose + +This role is the only component of the library that uses Moose. See +WWW::SwaggerClient::ApiFactory for non-Moosey usage. + +=head1 SYNOPSIS + +The Perl Swagger Codegen project builds a library of Perl modules to interact with +a web service defined by a Swagger specification. See below for how to build the +library. + +This module provides an interface to the generated library. All the classes, +objects, and methods (well, not quite *all*, see below) are flattened into this +role. + + package MyApp; + use Moose; + with 'WWW::SwaggerClient::Role'; + + package main; + + my $api = MyApp->new({ tokens => $tokens }); + + my $pet = $api->get_pet_by_id(pet_id => $pet_id); + +=head2 Structure of the library + +The library consists of a set of API classes, one for each endpoint. These APIs +implement the method calls available on each endpoint. + +Additionally, there is a set of "object" classes, which represent the objects +returned by and sent to the methods on the endpoints. + +An API factory class is provided, which builds instances of each endpoint API. + +This Moose role flattens all the methods from the endpoint APIs onto the consuming +class. It also provides methods to retrieve the endpoint API objects, and the API +factory object, should you need it. + +For documentation of all these methods, see AUTOMATIC DOCUMENTATION below. + +=head2 Configuring authentication + +In the normal case, the Swagger spec will describe what parameters are +required and where to put them. You just need to supply the tokens. + + my $tokens = { + # basic + username => $username, + password => $password, + + # oauth + access_token => $oauth_token, + + # keys + $some_key => { token => $token, + prefix => $prefix, + in => $in, # 'head||query', + }, + + $another => { token => $token, + prefix => $prefix, + in => $in, # 'head||query', + }, + ..., + + }; + + my $api = MyApp->new({ tokens => $tokens }); + +Note these are all optional, as are C and C, and depend on the API +you are accessing. Usually C and C will be determined by the code generator from +the spec and you will not need to set them at run time. If not, C will +default to 'head' and C to the empty string. + +The tokens will be placed in the C namespace +as follows, but you don't need to know about this. + +=over 4 + +=item C<$WWW::SwaggerClient::Configuration::username> + +String. The username for basic auth. + +=item C<$WWW::SwaggerClient::Configuration::password> + +String. The password for basic auth. + +=item C<$WWW::SwaggerClient::Configuration::api_key> + +Hashref. Keyed on the name of each key (there can be multiple tokens). + + $WWW::SwaggerClient::Configuration::api_key = { + secretKey => 'aaaabbbbccccdddd', + anotherKey => '1111222233334444', + }; + +=item C<$WWW::SwaggerClient::Configuration::api_key_prefix> + +Hashref. Keyed on the name of each key (there can be multiple tokens). Note not +all api keys require a prefix. + + $WWW::SwaggerClient::Configuration::api_key_prefix = { + secretKey => 'string', + anotherKey => 'same or some other string', + }; + +=item C<$WWW::SwaggerClient::Configuration::access_token> + +String. The OAuth access token. + +=back + +=head1 METHODS + +=head2 C + +The generated code has the C already set as a default value. This method +returns (and optionally sets, but only if the API client has not been +created yet) the current value of C. + +=head2 C + +Returns an API factory object. You probably won't need to call this directly. + + $self->api_factory('Pet'); # returns a WWW::SwaggerClient::PetApi instance + + $self->pet_api; # the same + +=head1 MISSING METHODS + +Most of the methods on the API are delegated to individual endpoint API objects +(e.g. Pet API, Store API, User API etc). Where different endpoint APIs use the +same method name (e.g. C), these methods can't be delegated. So you need +to call C<$api-Epet_api-Enew()>. + +In principle, every API is susceptible to the presence of a few, random, undelegatable +method names. In practice, because of the way method names are constructed, it's +unlikely in general that any methods will be undelegatable, except for: + + new() + class_documentation() + method_documentation() + +To call these methods, you need to get a handle on the relevant object, either +by calling C<$api-Efoo_api> or by retrieving an object, e.g. +C<$api-Eget_pet_by_id(pet_id =E $pet_id)>. They are class methods, so +you could also call them on class names. + +=head1 BUILDING YOUR LIBRARY + +See the homepage C for full details. +But briefly, clone the git repository, build the codegen codebase, set up your build +config file, then run the API build script. You will need git, Java 7 and Apache +maven 3.0.3 or better already installed. + +The config file should specify the project name for the generated library: + + {"moduleName":"MyProjectName"} + +Your library files will be built under C. + + $ git clone https://github.com/swagger-api/swagger-codegen.git + $ cd swagger-codegen + $ mvn package + $ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ + -i [URL or file path to JSON swagger API spec] \ + -l perl \ + -c /path/to/config/file.json \ + -o /path/to/output/folder + +Bang, all done. Run the C script in the C directory to see the API +you just built. + +=head1 AUTOMATIC DOCUMENTATION + +You can print out a summary of the generated API by running the included +C script in the C directory of your generated library. A few +output formats are supported: + + Usage: autodoc [OPTION] + + -w wide format (default) + -n narrow format + -p POD format + -H HTML format + -m Markdown format + -h print this help message + -c your application class + +The C<-c> option allows you to load and inspect your own application. A dummy +namespace is used if you don't supply your own class. + +=head1 DOCUMENTATION FROM THE SWAGGER SPEC + +Additional documentation for each class and method may be provided by the Swagger +spec. If so, this is available via the C and +C methods on each generated object class, and the +C method on the endpoint API classes: + + my $cmdoc = $api->pet_api->method_documentation->{$method_name}; + + my $odoc = $api->get_pet_by_id->(pet_id => $pet_id)->class_documentation; + my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; + +Each of these calls returns a hashref with various useful pieces of information. + +=cut + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm new file mode 100644 index 00000000000..0dc30dbfb90 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm @@ -0,0 +1,427 @@ +package WWW::SwaggerClient::Role::AutoDoc; +use List::MoreUtils qw(uniq); + +use Moose::Role; + +sub autodoc { + my ($self, $how) = @_; + + die "Unknown format '$how'" unless $how =~ /^(pod|wide|narrow)$/; + + $self->_printisa($how); + $self->_printmethods($how); + $self->_printattrs($how); + print "\n"; +} + +sub _printisa { + my ($self, $how) = @_; + my $meta = $self->meta; + + my $myclass = ref $self; + + my $super = join ', ', $meta->superclasses; + my @roles = $meta->calculate_all_roles; + #shift(@roles) if @roles > 1; # if > 1, the first is a composite, the rest are the roles + + my $isa = join ', ', grep {$_ ne $myclass} $meta->linearized_isa; + my $sub = join ', ', $meta->subclasses; + my $dsub = join ', ', $meta->direct_subclasses; + + my $app_name = $self->version_info->{app_name}; + my $app_version = $self->version_info->{app_version}; + my $generated_date = $self->version_info->{generated_date}; + my $generator_class = $self->version_info->{generator_class}; + + $~ = $how eq 'pod' ? 'INHERIT_POD' : 'INHERIT'; + write; + + my ($rolepkg, $role_reqs); + + foreach my $role (@roles) { + $rolepkg = $role->{package} || next; # some are anonymous, or something + next if $rolepkg eq 'WWW::SwaggerClient::Role::AutoDoc'; + $role_reqs = join ', ', keys %{$role->{required_methods}}; + $role_reqs ||= ''; + $~ = $how eq 'pod' ? 'ROLES_POD' : 'ROLES'; + write; + } + + if ($how eq 'pod') { + $~ = 'ROLES_POD_CLOSE'; + write; + } + +# ----- format specs ----- + format INHERIT = + +@* - +$myclass + ISA: @* + $isa + Direct subclasses: @* + $dsub + All subclasses: @* + $sub + + Target API: @* @* + $app_name, $app_version + Generated on: @* + $generated_date + Generator class: @* + $generator_class + +. + format ROLES = + Composes: ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ + $rolepkg + requires: ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ + $role_reqs + ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~ + $role_reqs +. + + format INHERIT_POD = +=head1 NAME + +@* +$myclass + +=head1 VERSION + +=head2 @* version: @* + $app_name, $app_version + +Automatically generated by the Perl Swagger Codegen project: + +=over 4 + +=item Build date: @* + $generated_date + +=item Build package: @* + $generator_class + +=item Codegen version: + + +=back + +=head1 INHERITANCE + +=head2 Base class(es) + +@* +$isa + +=head2 Direct subclasses + +@* +$dsub + +=head2 All subclasses + +@* +$sub + + +=head1 COMPOSITION + +@* composes the following roles: +$myclass + + +. + format ROLES_POD = +=head2 C<@*> + $rolepkg + +Requires: + +@* +$role_reqs + +. + format ROLES_POD_CLOSE = + + +. +# ----- / format specs ----- +} + +sub _printmethods { + my ($self, $how) = @_; + + if ($how eq 'narrow') { + print <_printmethod($_, $how) for uniq sort $self->meta->get_all_method_names; #$self->meta->get_method_list, + + if ($how eq 'pod') { + $~ = 'METHOD_POD_CLOSE'; + write; + } + + +} + +sub _printmethod { + my ($self, $methodname, $how) = @_; + return if $methodname =~ /^_/; + return if $self->meta->has_attribute($methodname); + my %internal = map {$_ => 1} qw(BUILD BUILDARGS meta can new DEMOLISHALL DESTROY + DOES isa BUILDALL does VERSION dump + ); + return if $internal{$methodname}; + my $method = $self->meta->get_method($methodname) or return; # symbols imported into namespaces i.e. not known by Moose + + return if $method->original_package_name eq __PACKAGE__; + + my $delegate_to = ''; + my $via = ''; + my $on = ''; + my $doc = ''; + my $original_pkg = $method->original_package_name; + if ($method->can('associated_attribute')) { + $delegate_to = $method->delegate_to_method; + my $aa = $method->associated_attribute; + $on = $aa->{isa}; + $via = $aa->{name}; + $original_pkg = $on; + $doc = $original_pkg->method_documentation->{$delegate_to}->{summary}; + } + else { + $doc = $method->documentation; + } + + if ($how eq 'narrow') { + $~ = 'METHOD_NARROW'; + write; + } + elsif ($how eq 'pod' and $delegate_to) { + $~ = 'METHOD_POD_DELEGATED'; + write; + } + elsif ($how eq 'pod') { + $~ = 'METHOD_POD'; + write; + } + else { + $~ = 'METHOD'; + write; + } + +# ----- format specs ----- + format METHODHEAD = + +METHODS +------- +Name delegates to on via +=========================================================================================================================================================================== +. + format METHOD = +@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<... @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<... @<<<<<<<<<<<<<<<<... +$methodname, $delegate_to, $on, $via +. + + format METHOD_NARROW = +@* +$methodname + original pkg: @* + $original_pkg + delegates to: @* + $delegate_to + on: @* + $on + via: @* + $via + +. + + format METHODHEAD_POD = + +=head1 METHODS + +. + + format METHOD_POD = + +=head2 C<@*()> + $methodname + + Defined in: @* + $original_pkg + + +. + format METHOD_POD_DELEGATED = + +=head2 C<@*()> + $methodname + + Defined in: @* + $original_pkg + Delegates to: @*() + $delegate_to + On: @* + $on + Via: @*() + $via + Doc: @* + $doc + Same as: $self->@*->@*() + $via, $delegate_to + +. + format METHOD_POD_CLOSE = + +. +# ----- / format specs ----- +} + +sub _printattrs { + my ($self, $how) = @_; + + if ($how eq 'narrow') { + print <_printattr($_, $how) for sort $self->meta->get_attribute_list; + + if ($how eq 'pod') { + $~ = 'ATTR_POD_CLOSE'; + write; + } +} + +sub _printattr { + my ($self, $attrname, $how) = @_; + return if $attrname =~ /^_/; + my $attr = $self->meta->get_attribute($attrname) or die "No attr for $attrname"; + + my $is; + $is = 'rw' if $attr->get_read_method && $attr->get_write_method; + $is = 'ro' if $attr->get_read_method && ! $attr->get_write_method; + $is = 'wo' if $attr->get_write_method && ! $attr->get_read_method; + $is = '--' if ! $attr->get_write_method && ! $attr->get_read_method; + $is or die "No \$is for $attrname"; + + my $tc = $attr->type_constraint || ''; + my $from = $attr->associated_class->name || ''; + my $reqd = $attr->is_required ? 'yes' : 'no'; + my $lazy = $attr->is_lazy ? 'yes' : 'no'; + my $has_doc = $attr->has_documentation ? 'yes' : 'no'; # *_api attributes will never have doc, but other attributes might have + my $doc = $attr->documentation || ''; + my $handles = join ', ', sort @{$attr->handles || []}; + $handles ||= ''; + + if ($how eq 'narrow') { + $~ = 'ATTR_NARROW'; + } + elsif ($how eq 'pod') { + $~ = 'ATTR_POD'; + } + else { + $~ = 'ATTR'; + } + + write; + +# ----- format specs ----- + format ATTRHEAD = + +ATTRIBUTES +---------- +Name is isa reqd lazy doc handles +============================================================================================================== +. + format ATTR = +@<<<<<<<<<<<<<<<<< @< @<<<<<<<<<<<<<<<<<<<<<<<< @<<< @<<< @<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< +$attrname, $is, $tc, $reqd, $lazy, $has_doc, $handles + ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~ + $handles +. + + format ATTR_NARROW = +@* +$attrname + is: @* + $is + isa: @* + $tc + reqd: @* + $reqd + lazy: @* + $lazy + doc: @* + $doc + handles: ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< + $handles + ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~ + $handles + +. + format ATTRHEAD_POD = +=head1 ATTRIBUTES + +. + format ATTR_POD = + +=head2 C<@*> + $attrname + + is: @* + $is + isa: @* + $tc + reqd: @* + $reqd + lazy: @* + $lazy + doc: @* + $doc + handles: ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< + $handles + ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~ + $handles + +. + format ATTR_POD_CLOSE = + + +. +# ----- / format specs ----- +} + + + +1; \ No newline at end of file diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index a2ac9010e77..abe936573e7 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -30,11 +30,14 @@ use Log::Any qw($log); use WWW::SwaggerClient::ApiClient; use WWW::SwaggerClient::Configuration; +use base "Class::Data::Inheritable"; + +__PACKAGE__->mk_classdata('method_documentation' => {}); + sub new { my $class = shift; - my $default_api_client = $WWW::SwaggerClient::Configuration::api_client ? $WWW::SwaggerClient::Configuration::api_client : WWW::SwaggerClient::ApiClient->new; my (%self) = ( - 'api_client' => $default_api_client, + 'api_client' => WWW::SwaggerClient::ApiClient->instance, @_ ); @@ -47,11 +50,21 @@ sub new { } + # # get_inventory # # Returns pet inventories by status # +{ + my $params = { + }; + __PACKAGE__->method_documentation->{ get_inventory } = { + summary => 'Returns pet inventories by status', + params => $params, + returns => 'HASH[string,int]', + }; +} # @return HASH[string,int] # sub get_inventory { @@ -83,7 +96,7 @@ sub get_inventory { # authentication setting, if any - my $auth_settings = ['api_key']; + my $auth_settings = [qw(api_key )]; # make the API Call my $response = $self->{api_client}->call_api($_resource_path, $_method, @@ -96,12 +109,27 @@ sub get_inventory { return $_response_object; } + # # place_order # # Place an order for a pet # # @param Order $body order placed for purchasing the pet (optional) +{ + my $params = { + 'body' => { + data_type => 'Order', + description => 'order placed for purchasing the pet', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ place_order } = { + summary => 'Place an order for a pet', + params => $params, + returns => 'Order', + }; +} # @return Order # sub place_order { @@ -136,7 +164,7 @@ sub place_order { } # authentication setting, if any - my $auth_settings = []; + my $auth_settings = [qw()]; # make the API Call my $response = $self->{api_client}->call_api($_resource_path, $_method, @@ -149,12 +177,27 @@ sub place_order { return $_response_object; } + # # get_order_by_id # # Find purchase order by ID # # @param string $order_id ID of pet that needs to be fetched (required) +{ + my $params = { + 'order_id' => { + data_type => 'string', + description => 'ID of pet that needs to be fetched', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ get_order_by_id } = { + summary => 'Find purchase order by ID', + params => $params, + returns => 'Order', + }; +} # @return Order # sub get_order_by_id { @@ -196,7 +239,7 @@ sub get_order_by_id { # authentication setting, if any - my $auth_settings = []; + my $auth_settings = [qw()]; # make the API Call my $response = $self->{api_client}->call_api($_resource_path, $_method, @@ -209,12 +252,27 @@ sub get_order_by_id { return $_response_object; } + # # delete_order # # Delete purchase order by ID # # @param string $order_id ID of the order that needs to be deleted (required) +{ + my $params = { + 'order_id' => { + data_type => 'string', + description => 'ID of the order that needs to be deleted', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ delete_order } = { + summary => 'Delete purchase order by ID', + params => $params, + returns => undef, + }; +} # @return void # sub delete_order { @@ -256,7 +314,7 @@ sub delete_order { # authentication setting, if any - my $auth_settings = []; + my $auth_settings = [qw()]; # make the API Call diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index e1088a0839e..9ba45815c8c 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -30,11 +30,14 @@ use Log::Any qw($log); use WWW::SwaggerClient::ApiClient; use WWW::SwaggerClient::Configuration; +use base "Class::Data::Inheritable"; + +__PACKAGE__->mk_classdata('method_documentation' => {}); + sub new { my $class = shift; - my $default_api_client = $WWW::SwaggerClient::Configuration::api_client ? $WWW::SwaggerClient::Configuration::api_client : WWW::SwaggerClient::ApiClient->new; my (%self) = ( - 'api_client' => $default_api_client, + 'api_client' => WWW::SwaggerClient::ApiClient->instance, @_ ); @@ -47,12 +50,27 @@ sub new { } + # # create_user # # Create user # # @param User $body Created user object (optional) +{ + my $params = { + 'body' => { + data_type => 'User', + description => 'Created user object', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ create_user } = { + summary => 'Create user', + params => $params, + returns => undef, + }; +} # @return void # sub create_user { @@ -87,7 +105,7 @@ sub create_user { } # authentication setting, if any - my $auth_settings = []; + my $auth_settings = [qw()]; # make the API Call @@ -97,12 +115,27 @@ sub create_user { return; } + # # create_users_with_array_input # # Creates list of users with given input array # # @param ARRAY[User] $body List of user object (optional) +{ + my $params = { + 'body' => { + data_type => 'ARRAY[User]', + description => 'List of user object', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ create_users_with_array_input } = { + summary => 'Creates list of users with given input array', + params => $params, + returns => undef, + }; +} # @return void # sub create_users_with_array_input { @@ -137,7 +170,7 @@ sub create_users_with_array_input { } # authentication setting, if any - my $auth_settings = []; + my $auth_settings = [qw()]; # make the API Call @@ -147,12 +180,27 @@ sub create_users_with_array_input { return; } + # # create_users_with_list_input # # Creates list of users with given input array # # @param ARRAY[User] $body List of user object (optional) +{ + my $params = { + 'body' => { + data_type => 'ARRAY[User]', + description => 'List of user object', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ create_users_with_list_input } = { + summary => 'Creates list of users with given input array', + params => $params, + returns => undef, + }; +} # @return void # sub create_users_with_list_input { @@ -187,7 +235,7 @@ sub create_users_with_list_input { } # authentication setting, if any - my $auth_settings = []; + my $auth_settings = [qw()]; # make the API Call @@ -197,6 +245,7 @@ sub create_users_with_list_input { return; } + # # login_user # @@ -204,6 +253,25 @@ sub create_users_with_list_input { # # @param string $username The user name for login (optional) # @param string $password The password for login in clear text (optional) +{ + my $params = { + 'username' => { + data_type => 'string', + description => 'The user name for login', + required => '0', + }, + 'password' => { + data_type => 'string', + description => 'The password for login in clear text', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ login_user } = { + summary => 'Logs user into the system', + params => $params, + returns => 'string', + }; +} # @return string # sub login_user { @@ -241,7 +309,7 @@ sub login_user { # authentication setting, if any - my $auth_settings = []; + my $auth_settings = [qw()]; # make the API Call my $response = $self->{api_client}->call_api($_resource_path, $_method, @@ -254,11 +322,21 @@ sub login_user { return $_response_object; } + # # logout_user # # Logs out current logged in user session # +{ + my $params = { + }; + __PACKAGE__->method_documentation->{ logout_user } = { + summary => 'Logs out current logged in user session', + params => $params, + returns => undef, + }; +} # @return void # sub logout_user { @@ -290,7 +368,7 @@ sub logout_user { # authentication setting, if any - my $auth_settings = []; + my $auth_settings = [qw()]; # make the API Call @@ -300,12 +378,27 @@ sub logout_user { return; } + # # get_user_by_name # # Get user by user name # # @param string $username The name that needs to be fetched. Use user1 for testing. (required) +{ + my $params = { + 'username' => { + data_type => 'string', + description => 'The name that needs to be fetched. Use user1 for testing.', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ get_user_by_name } = { + summary => 'Get user by user name', + params => $params, + returns => 'User', + }; +} # @return User # sub get_user_by_name { @@ -347,7 +440,7 @@ sub get_user_by_name { # authentication setting, if any - my $auth_settings = []; + my $auth_settings = [qw()]; # make the API Call my $response = $self->{api_client}->call_api($_resource_path, $_method, @@ -360,6 +453,7 @@ sub get_user_by_name { return $_response_object; } + # # update_user # @@ -367,6 +461,25 @@ sub get_user_by_name { # # @param string $username name that need to be deleted (required) # @param User $body Updated user object (optional) +{ + my $params = { + 'username' => { + data_type => 'string', + description => 'name that need to be deleted', + required => '1', + }, + 'body' => { + data_type => 'User', + description => 'Updated user object', + required => '0', + }, + }; + __PACKAGE__->method_documentation->{ update_user } = { + summary => 'Updated user', + params => $params, + returns => undef, + }; +} # @return void # sub update_user { @@ -411,7 +524,7 @@ sub update_user { } # authentication setting, if any - my $auth_settings = []; + my $auth_settings = [qw()]; # make the API Call @@ -421,12 +534,27 @@ sub update_user { return; } + # # delete_user # # Delete user # # @param string $username The name that needs to be deleted (required) +{ + my $params = { + 'username' => { + data_type => 'string', + description => 'The name that needs to be deleted', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ delete_user } = { + summary => 'Delete user', + params => $params, + returns => undef, + }; +} # @return void # sub delete_user { @@ -468,7 +596,7 @@ sub delete_user { # authentication setting, if any - my $auth_settings = []; + my $auth_settings = [qw()]; # make the API Call diff --git a/samples/client/petstore/perl/pom.xml b/samples/client/petstore/perl/pom.xml index 00d192b1e54..4aa0040f82e 100644 --- a/samples/client/petstore/perl/pom.xml +++ b/samples/client/petstore/perl/pom.xml @@ -52,6 +52,32 @@ + + Test::More for ApiFactory + integration-test + + exec + + + perl + + t/03_api_factory.t + + + + + Test::More for Role + integration-test + + exec + + + perl + + t/04_role.t + + + diff --git a/samples/client/petstore/perl/t/01_pet_api.t b/samples/client/petstore/perl/t/01_pet_api.t index 6b731b846fe..c7bcdf98a0a 100644 --- a/samples/client/petstore/perl/t/01_pet_api.t +++ b/samples/client/petstore/perl/t/01_pet_api.t @@ -1,4 +1,4 @@ -use Test::More tests => 33; +use Test::More tests => 38; use Test::Exception; use lib 'lib'; @@ -11,12 +11,18 @@ use_ok('WWW::SwaggerClient::Object::Pet'); use_ok('WWW::SwaggerClient::Object::Tag'); use_ok('WWW::SwaggerClient::Object::Category'); -my $api_client = WWW::SwaggerClient::ApiClient->new('base_url' => 'http://testing'); +my $api_client = WWW::SwaggerClient::ApiClient->instance('base_url' => 'http://testing'); my $pet_api = WWW::SwaggerClient::PetApi->new('api_client' => $api_client); is $pet_api->{api_client}->{base_url}, 'http://testing', 'get the proper base URL from api client'; my $api = WWW::SwaggerClient::PetApi->new(); +is $api->{api_client}->{base_url}, 'http://testing', 'we still get the original base URL from api client, because it\'s a singleton'; + +# reset the base_url - no direct access because an application shouldn't be changing +# its base URL halfway through +$api->{api_client}->{base_url} = 'http://petstore.swagger.io/v2'; + is $api->{api_client}->{base_url}, 'http://petstore.swagger.io/v2', 'get the default base URL from api client'; # test select_header_content_type @@ -59,6 +65,9 @@ is $get_pet_hash->{category}->{id}, '22', 'get the proper category id from get_p is $get_pet_hash->{category}->{name}, 'perl', 'get the proper category from get_pet_by_id'; is $get_pet_hash->{tags}[0]->{name}, 'just kidding', 'get the proper tag from get_pet_by_id'; is $get_pet_hash->{tags}[0]->{id}, '11', 'get the proper tag id from get_pet_by_id'; +is $get_pet_hash->{photoUrls}->[0], '123', 'get the proper photoUrl from get_pet_by_id'; +is $get_pet_hash->{photoUrls}->[1], 'oop', 'get the proper photoUrl from get_pet_by_id'; + my $update_pet_with_form = $api->update_pet_with_form(pet_id => $pet_id, name => 'test_name', status => 'sold'); is $update_pet_with_form, undef, 'get the null response from update_pet_wth_form'; @@ -74,3 +83,7 @@ is $delete_pet, undef, 'get the null response from delete_pet'; throws_ok{$api->get_pet_by_id(pet_id => $pet_id)} qr/API Exception\(404\): Not Found/, "throw 404 error about pet not found after delete"; #is $get_pet_after_delete->{status}, undef, 'get the updated status after update_pet_with_form'; +my $pets; +lives_ok {$pets = $api->find_pets_by_status(status => [qw(sold available)])} 'array query param processed correctly'; +isa_ok($pets->[0], 'WWW::SwaggerClient::Object::Pet'); + diff --git a/samples/client/petstore/perl/t/02_store_api.t b/samples/client/petstore/perl/t/02_store_api.t index f4687daad41..39b18381b0e 100644 --- a/samples/client/petstore/perl/t/02_store_api.t +++ b/samples/client/petstore/perl/t/02_store_api.t @@ -1,4 +1,4 @@ -use Test::More tests => 22; +use Test::More tests => 41; use Test::Exception; use lib 'lib'; @@ -12,15 +12,18 @@ use_ok('WWW::SwaggerClient::ApiClient'); use_ok('WWW::SwaggerClient::Object::Pet'); use_ok('WWW::SwaggerClient::Object::Tag'); use_ok('WWW::SwaggerClient::Object::Category'); +use_ok('WWW::SwaggerClient::Object::User'); -my $api_client = WWW::SwaggerClient::ApiClient->new(); + +my $api_client = WWW::SwaggerClient::ApiClient->instance(); my $store_api = WWW::SwaggerClient::StoreApi->new('api_client' => $api_client); is $store_api->{api_client}->{base_url}, 'http://petstore.swagger.io/v2', 'get the default base URL from api client'; my $get_inventory_response = $store_api->get_inventory(); -like ($get_inventory_response->{pending}, qr/^\d+$/, "pending is numeric"); +# comment out pending check as sometimes there's no object with pending status +#like ($get_inventory_response->{pending}, qr/^\d+$/, "pending is numeric"); like ($get_inventory_response->{sold}, qr/^\d+$/, "sold is numeric"); my $pet_json = <deserialize("HASH[string,Pet]", $pet_json)->{pet}->{category}->{ is ref $api_client->deserialize("HASH[string,Pet]", $pet_json)->{pet}->{category}, "WWW::SwaggerClient::Object::Category", "get the Category the Pet object"; is ref $api_client->deserialize("HASH[string,Pet]", $pet_json)->{pet}->{tags}[0], "WWW::SwaggerClient::Object::Tag", "get the Tag of the Pet object"; is $api_client->deserialize("HASH[string,Pet]", $pet_json)->{pet}->{tags}[0]->{name}, "tag string", "get the Tag name of the Pet object"; +is $api_client->deserialize("HASH[string,Pet]", $pet_json)->{pet}->{photo_urls}->[0], "string", "get the photoUrl from the Pet object"; my $array_json = <deserialize("ARRAY[Pet]", $array_json)->[0]->{category}->{name}, is ref $api_client->deserialize("ARRAY[Pet]", $array_json)->[0]->{category}, "WWW::SwaggerClient::Object::Category", "get the Category the Pet object"; is ref $api_client->deserialize("ARRAY[Pet]", $array_json)->[0]->{tags}->[0], "WWW::SwaggerClient::Object::Tag", "get the Tag[0] the Pet object"; is $api_client->deserialize("ARRAY[Pet]", $array_json)->[0]->{tags}->[0]->{name}, "tag string", "get the tag name the Pet object"; +is $api_client->deserialize("ARRAY[Pet]", $array_json)->[0]->{photo_urls}->[0], "string", "get the photoUrl from the Pet object"; + +my $pet_json_nopet = <deserialize("Pet", $pet_json_nopet), "WWW::SwaggerClient::Object::Pet", "get Pet object via from_hash()"; +is $api_client->deserialize("Pet", $pet_json_nopet)->{name}, "doggie", "get the name of the Pet object"; +is $api_client->deserialize("Pet", $pet_json_nopet)->{category}->{name}, "string", "get the category name of the Pet object"; +is ref $api_client->deserialize("Pet", $pet_json_nopet)->{category}, "WWW::SwaggerClient::Object::Category", "get the Category the Pet object"; +is ref $api_client->deserialize("Pet", $pet_json_nopet)->{tags}->[0], "WWW::SwaggerClient::Object::Tag", "get the Tag[0] the Pet object"; +is $api_client->deserialize("Pet", $pet_json_nopet)->{tags}->[0]->{name}, "tag string", "get the tag name the Pet object"; +is $api_client->deserialize("Pet", $pet_json_nopet)->{photo_urls}->[0], "string", "get the photoUrl from the Pet object"; + + +my %userdata = ( + id => 4000, + username => "tony", + firstName => "Tony", + lastName => "Tiger", + email => 'tony@fail.com', + password => "XXXXXXXXXXX", + phone => "408-867-5309", + userStatus => 1, + ); + +my $user = WWW::SwaggerClient::Object::User->new->from_hash(\%userdata); +is ref $user, 'WWW::SwaggerClient::Object::User', "built a User object via from_hash()"; +is $user->{id}, $userdata{id}, "got the id of the User object"; +is $user->{username}, $userdata{username}, "got the username of the User object"; +is $user->{first_name}, $userdata{firstName}, "got the firstName of the User object"; +is $user->{last_name}, $userdata{lastName}, "got the lastName of the User object"; +is $user->{email}, $userdata{email}, "got the email of the User object"; +is $user->{password}, $userdata{password}, "got the password of the User object"; +is $user->{phone}, $userdata{phone}, "got the phone of the User object"; +is $user->{user_status}, $userdata{userStatus}, "got the userStatus of the User object"; diff --git a/samples/client/petstore/perl/t/03_api_factory.t b/samples/client/petstore/perl/t/03_api_factory.t new file mode 100644 index 00000000000..a06805e2bcf --- /dev/null +++ b/samples/client/petstore/perl/t/03_api_factory.t @@ -0,0 +1,49 @@ +use Test::More tests => 19; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + +use_ok('WWW::SwaggerClient::ApiFactory'); + +my $api_factory = WWW::SwaggerClient::ApiFactory->new('base_url' => 'http://testing'); +my $pet_api = $api_factory->get_api('Pet'); +isa_ok($pet_api, 'WWW::SwaggerClient::PetApi'); +is $pet_api->{api_client}->{base_url}, 'http://testing', 'get the proper base URL from api client'; + +$api_factory = WWW::SwaggerClient::ApiFactory->new; +$pet_api = $api_factory->get_api('Pet'); + +# reset the base_url - no direct access because an application shouldn't be changing +# its base URL halfway through +$pet_api->{api_client}->{base_url} = 'http://petstore.swagger.io/v2'; +is $pet_api->{api_client}->{base_url}, 'http://petstore.swagger.io/v2', 'get the default base URL from api client'; + +# test accessor methods +my $pet_id = 10008; +# note - we don't need to 'use' these modules because they've already been loaded by ApiFactory +my ($category, $tag, $pet); +lives_ok { $category = WWW::SwaggerClient::Object::Category->new('id' => '22', 'name' => 'perl') } 'Category.pm loaded OK'; +lives_ok { $tag = WWW::SwaggerClient::Object::Tag->new('id' => '11', 'name' => 'just kidding') } 'Tag.pm loaded OK'; +lives_ok { $pet = WWW::SwaggerClient::Object::Pet->new('id' => $pet_id, 'name' => 'perl test', + "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'status' => 'pending', 'category' => $category) } 'Pet.pm loaded OK'; + +is $pet->id, '10008', 'got the proper pet id'; +is $pet->name, 'perl test', 'got the proper pet name'; +is $pet->category->id, '22', 'got the proper category id'; +is $pet->category->name, 'perl', 'got the proper category name'; +is $pet->tags->[0]->name, 'just kidding', 'got the proper tag name'; +is $pet->tags->[0]->id, '11', 'got the proper tag id'; + + +my $add_pet = $pet_api->add_pet(body => $pet); +my $get_pet = $pet_api->get_pet_by_id(pet_id => $pet_id); + +is $get_pet->id, '10008', 'stored and retrieved: got the proper pet id'; +is $get_pet->name, 'perl test', 'stored and retrieved: got the proper pet name'; +is $get_pet->category->id, '22', 'stored and retrieved: got the proper category id'; +is $get_pet->category->name, 'perl', 'stored and retrieved: got the proper category name'; +is $get_pet->tags->[0]->name, 'just kidding', 'stored and retrieved: got the proper tag name'; +is $get_pet->tags->[0]->id, '11', 'stored and retrieved: got the proper tag id'; + diff --git a/samples/client/petstore/perl/t/04_role.t b/samples/client/petstore/perl/t/04_role.t new file mode 100644 index 00000000000..73328fa6e62 --- /dev/null +++ b/samples/client/petstore/perl/t/04_role.t @@ -0,0 +1,143 @@ +use Test::More tests => 37; +use Test::Exception; +use Test::Warnings 'warnings'; +use Test::Deep; + +use lib 'lib'; +use strict; +use warnings; + +SKIP: { + eval " + package MyApp; + use Moose; + with 'WWW::SwaggerClient::Role'; + sub auth_setup_handler {} + "; + +# die $@ if $@; + skip 'Moose not installed', 37 if $@; + +my $api = MyApp->new; + +my $pet_id = 10008; +# note - we don't need to 'use' these modules because they've already been loaded by ApiFactory +my ($category, $tag, $pet); +lives_ok { $category = WWW::SwaggerClient::Object::Category->new('id' => '22', 'name' => 'perl') } 'Category.pm loaded OK'; +lives_ok { $tag = WWW::SwaggerClient::Object::Tag->new('id' => '11', 'name' => 'just kidding') } 'Tag.pm loaded OK'; +lives_ok { $pet = WWW::SwaggerClient::Object::Pet->new('id' => $pet_id, 'name' => 'perl test', + "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'status' => 'pending', 'category' => $category) } 'Pet.pm loaded OK'; + +is $pet->id, '10008', 'got the proper pet id'; +is $pet->name, 'perl test', 'got the proper pet name'; +is $pet->category->id, '22', 'got the proper category id'; +is $pet->category->name, 'perl', 'got the proper category name'; +is $pet->tags->[0]->name, 'just kidding', 'got the proper tag name'; +is $pet->tags->[0]->id, '11', 'got the proper tag id'; + + +my $add_pet = $api->add_pet(body => $pet); +my $get_pet = $api->get_pet_by_id(pet_id => $pet_id); + +is $get_pet->id, '10008', 'stored and retrieved: got the proper pet id'; +is $get_pet->name, 'perl test', 'stored and retrieved: got the proper pet name'; +is $get_pet->category->id, '22', 'stored and retrieved: got the proper category id'; +is $get_pet->category->name, 'perl', 'stored and retrieved: got the proper category name'; +is $get_pet->tags->[0]->name, 'just kidding', 'stored and retrieved: got the proper tag name'; +is $get_pet->tags->[0]->id, '11', 'stored and retrieved: got the proper tag id'; + +# documentation tests + +# API method docs +is_deeply( [sort keys %{$api->pet_api->method_documentation}], + [ 'add_pet', 'delete_pet', 'find_pets_by_status', 'find_pets_by_tags', 'get_pet_by_id', 'update_pet', 'update_pet_with_form', 'upload_file'], + "Pet API method_documentation has the correct keys"); +is $api->pet_api->method_documentation->{get_pet_by_id}->{params}->{pet_id}->{description}, + 'ID of pet that needs to be fetched', 'get_pet_by_id parameter pet_id description is correct'; +is $api->pet_api->method_documentation->{get_pet_by_id}->{params}->{pet_id}->{required}, + 1, 'get_pet_by_id parameter pet_id is required'; +is $api->pet_api->method_documentation->{get_pet_by_id}->{params}->{pet_id}->{data_type}, + 'int', 'get_pet_by_id parameter pet_id is an int'; +is $api->pet_api->method_documentation->{get_pet_by_id}->{returns}, + 'Pet', 'get_pet_by_id returns a Pet'; +is $api->pet_api->method_documentation->{get_pet_by_id}->{summary}, + 'Find pet by ID', 'get_pet_by_id summary is correct'; + +# object class docs +my $pet_class_doco = { 'description' => '', required => [], class => 'Pet' }; +is_deeply($get_pet->class_documentation, $pet_class_doco, 'Pet object class_documentation is available'); +is $get_pet->class_documentation->{description}, '', 'Pet object class_documentation is correct'; # right now it's blank +is $get_pet->class_documentation->{class}, 'Pet', 'Pet object class_documentation returns correct class name'; + +# object method docs +is $get_pet->method_documentation->{status}->{description}, 'pet status in the store', 'Pet object method_documentation for status() - description is correct'; +is $get_pet->method_documentation->{status}->{format}, '', 'Pet object method_documentation for status() - format is correct'; +is $get_pet->method_documentation->{status}->{base_name}, 'status', 'Pet object method_documentation for status() - base_name is correct'; +is $get_pet->method_documentation->{status}->{datatype}, 'string', 'Pet object method_documentation for status() - datatype is correct'; + + + +# / documentation tests + +my $tokens = { + username => 'UserName', + password => 'PassWord', + access_token => 'OAuth_token', + + someKey => { token => 'some_key_token', + prefix => 'some_key_prefix', + in => 'query', + }, + + anotherKey => { token => 'another_key_token', + }, + }; + +$api->_cfg->accept_tokens({%$tokens}); # pass a copy +no warnings 'once'; +is $WWW::SwaggerClient::Configuration::username, 'UserName', 'accept_tokens() correctly set the username'; +is $WWW::SwaggerClient::Configuration::password, 'PassWord', 'accept_tokens() correctly set the password'; +is $WWW::SwaggerClient::Configuration::access_token, 'OAuth_token', 'accept_tokens() correctly set the oauth'; + +my $api_key_href = { + 'anotherKey' => 'another_key_token', + 'someKey' => 'some_key_token' + }; +cmp_deeply( $WWW::SwaggerClient::Configuration::api_key, $api_key_href, 'accept_tokens() correctly set api_key' ); + +my $api_key_prefix_href = { + 'someKey' => 'some_key_prefix' + }; +cmp_deeply( $WWW::SwaggerClient::Configuration::api_key_prefix, $api_key_prefix_href, 'accept_tokens() correctly set api_key_prefix' ); + +my $api_key_in = { + 'someKey' => 'query', + 'anotherKey' => 'head' + }; +cmp_deeply( $WWW::SwaggerClient::Configuration::api_key_in, $api_key_in, 'accept_tokens() correctly set api_key_in' ); + +use warnings 'once'; + +my $cleared_tokens_cmp = { + 'anotherKey' => { + 'in' => 'head', + 'token' => 'another_key_token', + 'prefix' => undef + }, + 'access_token' => 'OAuth_token', + 'someKey' => { + 'token' => 'some_key_token', + 'in' => 'query', + 'prefix' => 'some_key_prefix' + }, + 'username' => 'UserName', + 'password' => 'PassWord' + }; +cmp_deeply( $api->_cfg->clear_tokens, $cleared_tokens_cmp, 'clear_tokens() returns the correct data structure' ); + +my $bad_token = { bad_token_name => 'bad token value' }; # value should should be hashref +dies_ok { $api->_cfg->accept_tokens($bad_token) } "bad token causes exception"; + + +} # / SKIP + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index cb0df4e8af0..a418ac90b43 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -136,7 +136,7 @@ class PetApi } - //TODO support oauth + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); // make the API Call try @@ -201,7 +201,7 @@ class PetApi } - //TODO support oauth + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); // make the API Call try @@ -265,7 +265,7 @@ class PetApi } - //TODO support oauth + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); // make the API Call try @@ -341,7 +341,7 @@ class PetApi } - //TODO support oauth + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); // make the API Call try @@ -431,9 +431,6 @@ class PetApi - - //TODO support oauth - // make the API Call try { @@ -509,10 +506,16 @@ class PetApi } // form params if ($name !== null) { + + $formParams['name'] = $this->apiClient->getSerializer()->toFormValue($name); + }// form params if ($status !== null) { + + $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); + } @@ -524,7 +527,7 @@ class PetApi } - //TODO support oauth + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); // make the API Call try @@ -600,7 +603,7 @@ class PetApi } - //TODO support oauth + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); // make the API Call try @@ -665,10 +668,22 @@ class PetApi } // form params if ($additional_metadata !== null) { + + $formParams['additionalMetadata'] = $this->apiClient->getSerializer()->toFormValue($additional_metadata); + }// form params if ($file !== null) { - $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); + + // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax + // See: https://wiki.php.net/rfc/curl-file-upload + if (function_exists('curl_file_create')) { + $formParams['file'] = curl_file_create($this->apiClient->getSerializer()->toFormValue($file)); + } else { + $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); + } + + } @@ -680,7 +695,7 @@ class PetApi } - //TODO support oauth + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); // make the API Call try diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 20150b7160b..982b8955a15 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -1,11 +1,11 @@ config = $config; $this->serializer = new ObjectSerializer(); } - + /** * Get the config * @return Configuration @@ -87,7 +87,7 @@ class ApiClient { return $this->config; } - + /** * Get the serializer * @return ObjectSerializer @@ -96,7 +96,7 @@ class ApiClient { return $this->serializer; } - + /** * Get API key (with prefix if set) * @param string $apiKeyIdentifier name of apikey @@ -106,20 +106,20 @@ class ApiClient { $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); $apiKey = $this->config->getApiKey($apiKeyIdentifier); - + if (!isset($apiKey)) { return null; } - + if (isset($prefix)) { $keyWithPrefix = $prefix." ".$apiKey; } else { $keyWithPrefix = $apiKey; } - + return $keyWithPrefix; } - + /** * Make the HTTP call (Sync) * @param string $resourcePath path to method endpoint @@ -133,28 +133,28 @@ class ApiClient */ public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) { - + $headers = array(); - + // construct the http header $headerParams = array_merge( - (array)$this->config->getDefaultHeaders(), + (array)$this->config->getDefaultHeaders(), (array)$headerParams ); - + foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; } - + // form data if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { $postData = http_build_query($postData); } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); } - + $url = $this->config->getHost() . $resourcePath; - + $curl = curl_init(); // set timeout, if needed if ($this->config->getCurlTimeout() != 0) { @@ -162,13 +162,19 @@ class ApiClient } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - + + // disable SSL verification, if needed + if ($this->config->getSSLVerification() == false) { + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); + } + if (! empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } - + if ($method == self::$POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); @@ -190,57 +196,62 @@ class ApiClient throw new ApiException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); - + // Set user agent curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); - + // debugging for curl if ($this->config->getDebug()) { error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); - + curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); } else { curl_setopt($curl, CURLOPT_VERBOSE, 0); } - + // obtain the HTTP response headers curl_setopt($curl, CURLOPT_HEADER, 1); - + // Make the request $response = curl_exec($curl); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $http_header = substr($response, 0, $http_header_size); $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); - + // debug HTTP response body if ($this->config->getDebug()) { error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); } - + // Handle the response if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { - // return raw body if response is a file + // return raw body if response is a file if ($responseType == '\SplFileObject') { return array($http_body, $http_header); } - + $data = json_decode($http_body); if (json_last_error() > 0) { // if response is a string $data = $http_body; } } else { + $data = json_decode($http_body); + if (json_last_error() > 0) { // if response is a string + $data = $http_body; + } + throw new ApiException( "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $http_body + $response_info['http_code'], $http_header, $data ); } return array($data, $http_header); } - + /** * Return the header 'Accept' based on an array of Accept provided * @@ -258,7 +269,7 @@ class ApiClient return implode(',', $accept); } } - + /** * Return the content type based on an array of content-type provided * diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index ce6c19e245f..0b8f5892a35 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -46,30 +46,30 @@ use \Exception; class ApiException extends Exception { - /** - * The HTTP body of the server response. - * @var string + /** + * The HTTP body of the server response either as Json or string. + * @var mixed */ protected $responseBody; - + /** * The HTTP header of the server response. * @var string[] */ protected $responseHeaders; - + /** * The deserialized response object * @var $responseObject; */ protected $responseObject; - + /** * Constructor * @param string $message Error message - * @param string $code HTTP status code + * @param int $code HTTP status code * @param string $responseHeaders HTTP response header - * @param string $responseBody Deseralized response object + * @param mixed $responseBody HTTP body of the server response either as Json or string */ public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { @@ -77,7 +77,7 @@ class ApiException extends Exception $this->responseHeaders = $responseHeaders; $this->responseBody = $responseBody; } - + /** * Gets the HTTP response header * @@ -87,17 +87,17 @@ class ApiException extends Exception { return $this->responseHeaders; } - + /** - * Gets the HTTP response body + * Gets the HTTP body of the server response either as Json or string * - * @return string HTTP response body + * @return mixed HTTP body of the server response either as Json or string */ public function getResponseBody() { return $this->responseBody; } - + /** * Sets the deseralized response object (during deserialization) * @param mixed $obj Deserialized response object diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index fcea7100ae4..1fdac785bfd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -27,8 +27,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * 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. */ @@ -48,70 +48,77 @@ class Configuration { private static $_defaultConfiguration = null; - - /** + + /** * Associate array to store API key(s) * * @var string[] */ protected $apiKeys = array(); - + /** * Associate array to store API prefix (e.g. Bearer) * * @var string[] */ protected $apiKeyPrefixes = array(); - - /** + + /** + * Access token for OAuth + * + * @var string + */ + protected $accessToken = ''; + + /** * Username for HTTP basic authentication * * @var string */ protected $username = ''; - + /** * Password for HTTP basic authentication * * @var string */ protected $password = ''; - + /** * The default instance of ApiClient * * @var \Swagger\Client\ApiClient */ protected $defaultHeaders = array(); - + /** * The host * * @var string */ protected $host = 'http://petstore.swagger.io/v2'; - + /** * Timeout (second) of the HTTP request, by default set to 0, no timeout * - * @var string + * @var string */ protected $curlTimeout = 0; - + /** * User agent of the HTTP request, set to "PHP-Swagger" by default * * @var string */ protected $userAgent = "PHP-Swagger/1.0.0"; - + /** * Debug switch (default set to false) * * @var bool */ protected $debug = false; - + /** * Debug file location (log to STDOUT by default) * @@ -126,6 +133,15 @@ class Configuration */ protected $tempFolderPath; + /** + * Indicates if SSL verification should be enabled or disabled. + * + * This is useful if the host uses a self-signed SSL certificate. + * + * @var boolean True if the certificate should be validated, false otherwise. + */ + protected $sslVerification = true; + /** * Constructor */ @@ -133,7 +149,7 @@ class Configuration { $this->tempFolderPath = sys_get_temp_dir(); } - + /** * Sets API key * @@ -147,7 +163,7 @@ class Configuration $this->apiKeys[$apiKeyIdentifier] = $key; return $this; } - + /** * Gets API key * @@ -159,7 +175,7 @@ class Configuration { return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; } - + /** * Sets the prefix for API key (e.g. Bearer) * @@ -173,7 +189,7 @@ class Configuration $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; return $this; } - + /** * Gets API key prefix * @@ -185,7 +201,30 @@ class Configuration { return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; } - + + /** + * Sets the access token for OAuth + * + * @param string $accessToken Token for OAuth + * + * @return Configuration + */ + public function setAccessToken($accessToken) + { + $this->$accessToken = $accessToken; + return $this; + } + + /** + * Gets the access token for OAuth + * + * @return string Access token for OAuth + */ + public function getAccessToken() + { + return $this->accessToken; + } + /** * Sets the username for HTTP basic authentication * @@ -198,7 +237,7 @@ class Configuration $this->username = $username; return $this; } - + /** * Gets the username for HTTP basic authentication * @@ -208,7 +247,7 @@ class Configuration { return $this->username; } - + /** * Sets the password for HTTP basic authentication * @@ -221,7 +260,7 @@ class Configuration $this->password = $password; return $this; } - + /** * Gets the password for HTTP basic authentication * @@ -231,7 +270,7 @@ class Configuration { return $this->password; } - + /** * Adds a default header * @@ -245,11 +284,11 @@ class Configuration if (!is_string($headerName)) { throw new \InvalidArgumentException('Header name must be a string.'); } - + $this->defaultHeaders[$headerName] = $headerValue; return $this; } - + /** * Gets the default header * @@ -259,7 +298,7 @@ class Configuration { return $this->defaultHeaders; } - + /** * Deletes a default header * @@ -271,7 +310,7 @@ class Configuration { unset($this->defaultHeaders[$headerName]); } - + /** * Sets the host * @@ -284,7 +323,7 @@ class Configuration $this->host = $host; return $this; } - + /** * Gets the host * @@ -294,7 +333,7 @@ class Configuration { return $this->host; } - + /** * Sets the user agent of the api client * @@ -307,11 +346,11 @@ class Configuration if (!is_string($userAgent)) { throw new \InvalidArgumentException('User-agent must be a string.'); } - + $this->userAgent = $userAgent; return $this; } - + /** * Gets the user agent of the api client * @@ -321,7 +360,7 @@ class Configuration { return $this->userAgent; } - + /** * Sets the HTTP timeout value * @@ -334,11 +373,11 @@ class Configuration if (!is_numeric($seconds) || $seconds < 0) { throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); } - + $this->curlTimeout = $seconds; return $this; } - + /** * Gets the HTTP timeout value * @@ -348,10 +387,10 @@ class Configuration { return $this->curlTimeout; } - + /** * Sets debug flag - * + * * @param bool $debug Debug flag * * @return Configuration @@ -361,7 +400,7 @@ class Configuration $this->debug = $debug; return $this; } - + /** * Gets the debug flag * @@ -371,7 +410,7 @@ class Configuration { return $this->debug; } - + /** * Sets the debug file * @@ -384,7 +423,7 @@ class Configuration $this->debugFile = $debugFile; return $this; } - + /** * Gets the debug file * @@ -394,7 +433,7 @@ class Configuration { return $this->debugFile; } - + /** * Sets the temp folder path * @@ -407,7 +446,7 @@ class Configuration $this->tempFolderPath = $tempFolderPath; return $this; } - + /** * Gets the temp folder path * @@ -417,7 +456,30 @@ class Configuration { return $this->tempFolderPath; } - + + /** + * Sets if SSL verification should be enabled or disabled + * + * @param boolean $sslVerification True if the certificate should be validated, false otherwise + * + * @return Configuration + */ + public function setSSLVerification($sslVerification) + { + $this->sslVerification = $sslVerification; + return $this; + } + + /** + * Gets if SSL verification should be enabled or disabled + * + * @return boolean True if the certificate should be validated, false otherwise + */ + public function getSSLVerification() + { + return $this->sslVerification; + } + /** * Gets the default configuration instance * @@ -428,10 +490,10 @@ class Configuration if (self::$_defaultConfiguration == null) { self::$_defaultConfiguration = new Configuration(); } - + return self::$_defaultConfiguration; } - + /** * Sets the detault configuration instance * @@ -443,7 +505,7 @@ class Configuration { self::$_defaultConfiguration = $config; } - + /** * Gets the essential information for debugging * @@ -457,8 +519,8 @@ class Configuration $report .= " Swagger Spec Version: 1.0.0\n"; $report .= " SDK Package Version: 1.0.0\n"; $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n"; - + return $report; } - + } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 0d281b9d1fa..efdc1c896ab 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -193,7 +193,7 @@ class ObjectSerializer $deserialized = $values; } elseif ($class === '\DateTime') { $deserialized = new \DateTime($data); - } elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) { + } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { settype($data, $class); $deserialized = $data; } elseif ($class === '\SplFileObject') { diff --git a/samples/client/petstore/python/.coverage b/samples/client/petstore/python/.coverage index d58a8fe9c63..03f8b2a2d03 100644 Binary files a/samples/client/petstore/python/.coverage and b/samples/client/petstore/python/.coverage differ diff --git a/samples/client/petstore/python/dev-requirements.txt.log b/samples/client/petstore/python/dev-requirements.txt.log index 9394a724030..0d8dcbb5831 100644 --- a/samples/client/petstore/python/dev-requirements.txt.log +++ b/samples/client/petstore/python/dev-requirements.txt.log @@ -13,3 +13,10 @@ Collecting pluggy<0.4.0,>=0.3.0 (from tox->-r dev-requirements.txt (line 2)) Using cached pluggy-0.3.0-py2.py3-none-any.whl Installing collected packages: nose, virtualenv, py, pluggy, tox, coverage, randomize Successfully installed coverage-3.7.1 nose-1.3.7 pluggy-0.3.0 py-1.4.30 randomize-0.13 tox-2.1.1 virtualenv-13.1.2 +Requirement already satisfied (use --upgrade to upgrade): nose in ./.venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in ./.venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in ./.venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in ./.venv/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Requirement already satisfied (use --upgrade to upgrade): virtualenv>=1.11.2 in ./.venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): py>=1.4.17 in ./.venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): pluggy<0.4.0,>=0.3.0 in ./.venv/lib/python2.7/site-packages (from tox->-r dev-requirements.txt (line 2)) 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 ad053a7d72d..d68d34e6774 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -409,7 +409,7 @@ class PetApi(object): select_header_content_type([]) # Authentication setting - auth_settings = ['api_key', 'petstore_auth'] + auth_settings = ['api_key'] response = self.api_client.call_api(resource_path, method, path_params, diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index 3e00acbe252..ecbecf7e9f9 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -72,6 +72,10 @@ class Configuration(object): # Password for HTTP basic authentication self.password = "" + # access token for OAuth + self.access_token = "" + + # Logging Settings self.logger = {} self.logger["package_logger"] = logging.getLogger("swagger_client") @@ -220,6 +224,7 @@ class Configuration(object): 'key': 'api_key', 'value': self.get_api_key_with_prefix('api_key') }, + } def to_debug_report(self): diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 61640d687ac..c13e99f29fc 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -14,8 +14,8 @@ require 'petstore/models/order' # APIs require 'petstore/api/user_api' -require 'petstore/api/pet_api' require 'petstore/api/store_api' +require 'petstore/api/pet_api' module Petstore class << self diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 4b956aeadcc..887f86dd45c 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -117,7 +117,7 @@ module Petstore # query parameters query_params = {} - query_params[:'status'] = opts[:'status'] if opts[:'status'] + query_params[:'status'] = @api_client.build_collection_param(opts[:'status'], :multi) if opts[:'status'] # header parameters header_params = {} @@ -166,7 +166,7 @@ module Petstore # query parameters query_params = {} - query_params[:'tags'] = opts[:'tags'] if opts[:'tags'] + query_params[:'tags'] = @api_client.build_collection_param(opts[:'tags'], :multi) if opts[:'tags'] # header parameters header_params = {} @@ -237,7 +237,7 @@ module Petstore post_body = nil - auth_names = ['api_key', 'petstore_auth'] + auth_names = ['api_key'] result = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 4f747bcd6a1..92a61bac4a6 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -189,9 +189,15 @@ module Petstore # http form if header_params['Content-Type'] == 'application/x-www-form-urlencoded' || header_params['Content-Type'] == 'multipart/form-data' - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) + data = {} + form_params.each do |key, value| + case value + when File, Array, nil + # let typhoeus handle File, Array and nil parameters + data[key] = value + else + data[key] = value.to_s + end end elsif body data = body.is_a?(String) ? body : body.to_json @@ -269,5 +275,25 @@ module Petstore obj end end + + # Build parameter value according to the given collection format. + # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi + def build_collection_param(param, collection_format) + case collection_format + when :csv + param.join(',') + when :ssv + param.join(' ') + when :tsv + param.join("\t") + when :pipes + param.join('|') + when :multi + # return the array directly as typhoeus will handle it as expected + param + else + fail "unknown collection format: #{collection_format.inspect}" + end + end end end diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 04479b53db0..4f7bd1c1b80 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -44,6 +44,9 @@ module Petstore # @return [String] attr_accessor :password + # Defines the access token (Bearer) used with OAuth2. + attr_accessor :access_token + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response # details will be logged with `logger.debug` (see the `logger` attribute). # Default to false. @@ -160,6 +163,13 @@ module Petstore # Returns Auth Settings hash for api client. def auth_settings { + 'petstore_auth' => + { + type: 'oauth2', + in: 'header', + key: 'Authorization', + value: "Bearer #{access_token}" + }, 'api_key' => { type: 'api_key', diff --git a/samples/client/petstore/ruby/lib/petstore/models/base_object.rb b/samples/client/petstore/ruby/lib/petstore/models/base_object.rb index 4a9a781ae64..af0ec63e79f 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/base_object.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/base_object.rb @@ -42,6 +42,17 @@ module Petstore else false end + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end else # model _model = Petstore.const_get(type).new _model.build_from_hash(value) @@ -63,11 +74,7 @@ module Petstore self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? - if value.is_a?(Array) - hash[param] = value.compact.map{ |v| _to_hash(v) } - else - hash[param] = _to_hash(value) - end + hash[param] = _to_hash(value) end hash end @@ -75,7 +82,13 @@ module Petstore # Method to output non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value def _to_hash(value) - if value.respond_to? :to_hash + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash value.to_hash else value diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index cd9016c9a0b..eeb27300bf3 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -116,4 +116,33 @@ describe Petstore::ApiClient do end end + describe "#build_collection_param" do + let(:param) { ['aa', 'bb', 'cc'] } + let(:api_client) { Petstore::ApiClient.new } + + it "works for csv" do + api_client.build_collection_param(param, :csv).should == 'aa,bb,cc' + end + + it "works for ssv" do + api_client.build_collection_param(param, :ssv).should == 'aa bb cc' + end + + it "works for tsv" do + api_client.build_collection_param(param, :tsv).should == "aa\tbb\tcc" + end + + it "works for pipes" do + api_client.build_collection_param(param, :pipes).should == 'aa|bb|cc' + end + + it "works for multi" do + api_client.build_collection_param(param, :multi).should == ['aa', 'bb', 'cc'] + end + + it "fails for invalid collection format" do + proc { api_client.build_collection_param(param, :INVALID) }.should raise_error + end + end + end diff --git a/samples/client/petstore/ruby/spec/base_object_spec.rb b/samples/client/petstore/ruby/spec/base_object_spec.rb new file mode 100644 index 00000000000..313d47f5d54 --- /dev/null +++ b/samples/client/petstore/ruby/spec/base_object_spec.rb @@ -0,0 +1,81 @@ +require 'spec_helper' + +class ArrayMapObject < Petstore::BaseObject + attr_accessor :int_arr, :pet_arr, :int_map, :pet_map, :int_arr_map, :pet_arr_map + + def self.attribute_map + { + :int_arr => :int_arr, + :pet_arr => :pet_arr, + :int_map => :int_map, + :pet_map => :pet_map, + :int_arr_map => :int_arr_map, + :pet_arr_map => :pet_arr_map + } + end + + def self.swagger_types + { + :int_arr => :'Array', + :pet_arr => :'Array', + :int_map => :'Hash', + :pet_map => :'Hash', + :int_arr_map => :'Hash>', + :pet_arr_map => :'Hash>' + } + end +end + + +describe Petstore::BaseObject do + describe 'array and map properties' do + let(:obj) { ArrayMapObject.new } + + let(:data) do + {int_arr: [123, 456], + pet_arr: [{name: 'Kitty'}], + int_map: {'int' => 123}, + pet_map: {'pet' => {name: 'Kitty'}}, + int_arr_map: {'int_arr' => [123, 456]}, + pet_arr_map: {'pet_arr' => [{name: 'Kitty'}]} + } + end + + it 'works for #build_from_hash' do + obj.build_from_hash(data) + + obj.int_arr.should == [123, 456] + + obj.pet_arr.should be_a(Array) + obj.pet_arr.size.should == 1 + pet = obj.pet_arr.first + pet.should be_a(Petstore::Pet) + pet.name.should == 'Kitty' + + obj.int_map.should be_a(Hash) + obj.int_map.should == {'int' => 123} + + obj.pet_map.should be_a(Hash) + pet = obj.pet_map['pet'] + pet.should be_a(Petstore::Pet) + pet.name.should == 'Kitty' + + obj.int_arr_map.should be_a(Hash) + arr = obj.int_arr_map['int_arr'] + arr.should == [123, 456] + + obj.pet_arr_map.should be_a(Hash) + arr = obj.pet_arr_map['pet_arr'] + arr.should be_a(Array) + arr.size.should == 1 + pet = arr.first + pet.should be_a(Petstore::Pet) + pet.name.should == 'Kitty' + end + + it 'works for #to_hash' do + obj.build_from_hash(data) + obj.to_hash.should == data + end + end +end \ No newline at end of file diff --git a/samples/client/petstore/scala/src/test/scala/UserApiTest.scala b/samples/client/petstore/scala/src/test/scala/UserApiTest.scala index ea0fda03d9a..77614a5dbbb 100644 --- a/samples/client/petstore/scala/src/test/scala/UserApiTest.scala +++ b/samples/client/petstore/scala/src/test/scala/UserApiTest.scala @@ -11,21 +11,41 @@ import scala.collection.JavaConverters._ import scala.beans.BeanProperty @RunWith(classOf[JUnitRunner]) -class UserApiTest extends FlatSpec with Matchers { +class UserApiTest extends FlatSpec with Matchers with BeforeAndAfterAll { behavior of "UserApi" val api = new UserApi api.apiInvoker.defaultHeaders += "api_key" -> "special-key" + // preparation before running a test + override def beforeAll() { + val user = User( + 11222, + "scala-test-username", + "scala-test-first", + "scala-test-last", + "scala_test@fail.com", + "SCALATEST", + "408-867-5309", + 1) + + api.createUser(user) + } + + // cleanup after running a test + override def afterAll() { + api.deleteUser("scala-test-username") + } + it should "fetch a user" in { - api.getUserByName("user1") match { + api.getUserByName("scala-test-username") match { case Some(user) => { - user.id should be(1) - user.username should be("user1") - user.password should be("XXXXXXXXXXX") - user.email should be("email1@test.com") - user.firstName should be("first name 1") - user.lastName should be("last name 1") - user.phone should be("123-456-7890") + user.id should be(11222) + user.username should be("scala-test-username") + user.password should be("SCALATEST") + user.email should be("scala_test@fail.com") + user.firstName should be("scala-test-first") + user.lastName should be("scala-test-last") + user.phone should be("408-867-5309") user.userStatus should be(1) } case None => @@ -33,7 +53,7 @@ class UserApiTest extends FlatSpec with Matchers { } it should "authenticate a user" in { - api.loginUser("user1", "XXXXXXXXXXX") match { + api.loginUser("scala-test-username", "SCALATEST") match { case Some(status) => status.startsWith("logged in user session") match { case true => // success! case _ => fail("didn't get expected message " + status) @@ -46,28 +66,6 @@ class UserApiTest extends FlatSpec with Matchers { api.logoutUser } - it should "create a user" in { - val user = User( - 1002, - "johnny", - "Johnny", - "Rocket", - "johnny@fail.com", - "XXXXXXXXXXX", - "408-867-5309", - 1) - - api.createUser(user) - - api.getUserByName("johnny") match { - case Some(user) => { - user.id should be(1002) - user.username should be("johnny") - } - case None => - } - } - it should "create 2 users" in { val userArray = (for (i <- (1 to 2)) yield { User( @@ -149,4 +147,4 @@ class UserApiTest extends FlatSpec with Matchers { case None => } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift/Cartfile b/samples/client/petstore/swift/Cartfile index fbd9346e468..745e00376a8 100644 --- a/samples/client/petstore/swift/Cartfile +++ b/samples/client/petstore/swift/Cartfile @@ -1,2 +1,2 @@ -github "Alamofire/Alamofire" >= 2.0.0 +github "Alamofire/Alamofire" >= 3.0.0 github "mxcl/PromiseKit" >=1.5.3 diff --git a/samples/client/petstore/swift/PetstoreClient.podspec b/samples/client/petstore/swift/PetstoreClient.podspec index 473b130c40c..3caf12083de 100644 --- a/samples/client/petstore/swift/PetstoreClient.podspec +++ b/samples/client/petstore/swift/PetstoreClient.podspec @@ -7,5 +7,5 @@ Pod::Spec.new do |s| s.license = 'Apache License, Version 2.0' s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' s.dependency 'PromiseKit', '~> 2.1' - s.dependency 'Alamofire', '~> 2.0.0' + s.dependency 'Alamofire', '~> 3.0.0' end diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift index 73c923e6486..96eead0d8dd 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift @@ -7,8 +7,9 @@ import Foundation public class PetstoreClientAPI { - static let basePath = "http://petstore.swagger.io/v2" - static var credential: NSURLCredential? + public static var basePath = "http://petstore.swagger.io/v2" + public static var credential: NSURLCredential? + public static var customHeaders: [String:String] = [:] static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() } @@ -41,9 +42,17 @@ public class RequestBuilder { self.URLString = URLString self.parameters = parameters self.isBody = isBody + + addHeaders(PetstoreClientAPI.customHeaders) } - public func execute(completion: (response: Response?, erorr: ErrorType?) -> Void) { } + public func addHeaders(aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + public func execute(completion: (response: Response?, error: ErrorType?) -> Void) { } public func addHeader(name name: String, value: String) -> Self { if !value.isEmpty { diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 614e70b717e..ea6c50e2549 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -71,20 +71,20 @@ extension PetstoreClientAPI { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -93,21 +93,21 @@ extension PetstoreClientAPI { string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -116,7 +116,7 @@ extension PetstoreClientAPI { string -, contentType=application/xml}] +}] - parameter status: (query) Status values that need to be considered for filter @@ -145,20 +145,20 @@ extension PetstoreClientAPI { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -167,21 +167,21 @@ extension PetstoreClientAPI { string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -190,7 +190,7 @@ extension PetstoreClientAPI { string -, contentType=application/xml}] +}] - parameter tags: (query) Tags to filter by @@ -219,23 +219,20 @@ extension PetstoreClientAPI { - API Key: - type: apiKey api_key - name: api_key - - OAuth: - - type: oauth2 - - name: petstore_auth - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -244,21 +241,21 @@ extension PetstoreClientAPI { string -, contentType=application/xml}] - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -267,7 +264,7 @@ extension PetstoreClientAPI { string -, contentType=application/xml}] +}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 92cedda725e..c3865cb3ccc 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -21,12 +21,12 @@ extension PetstoreClientAPI { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - - examples: [{example={ +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@d1e580af}] - returns: RequestBuilder<[String:Int]> */ @@ -48,36 +48,36 @@ extension PetstoreClientAPI { - POST /store/order - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-10-20T06:12:32.347+0000" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2015-11-11T12:31:12.079+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 - 2015-10-19T23:12:32.350Z + 2015-11-11T14:31:12.082Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-10-20T06:12:32.347+0000" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2015-11-11T12:31:12.079+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 - 2015-10-19T23:12:32.350Z + 2015-11-11T14:31:12.082Z string true -, contentType=application/xml}] +}] - parameter body: (body) order placed for purchasing the pet @@ -100,36 +100,36 @@ extension PetstoreClientAPI { - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-10-20T06:12:32.351+0000" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2015-11-11T12:31:12.083+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 - 2015-10-19T23:12:32.351Z + 2015-11-11T14:31:12.083Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-10-20T06:12:32.351+0000" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2015-11-11T12:31:12.083+0000", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 - 2015-10-19T23:12:32.351Z + 2015-11-11T14:31:12.083Z string true -, contentType=application/xml}] +}] - parameter orderId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 19cf534cea8..231e7f59228 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -84,8 +84,8 @@ extension PetstoreClientAPI { - GET /user/login - - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text @@ -134,7 +134,7 @@ extension PetstoreClientAPI { - GET /user/{username} - - - examples: [{example={ + - examples: [{contentType=application/json, example={ "id" : 1, "username" : "johnp", "firstName" : "John", @@ -143,7 +143,7 @@ extension PetstoreClientAPI { "password" : "-secret-", "phone" : "0123456789", "userStatus" : 0 -}, contentType=application/json}] +}}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 21791168ab2..6b4d36f9410 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -20,7 +20,7 @@ class AlamofireRequestBuilder: RequestBuilder { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) } - override func execute(completion: (response: Response?, erorr: ErrorType?) -> Void) { + override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { let managerId = NSUUID().UUIDString // Create a new manager for each request to customize its request header let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() @@ -60,7 +60,7 @@ class AlamofireRequestBuilder: RequestBuilder { case .Success(let upload, _, _): self.processRequest(upload, managerId, completion) case .Failure(let encodingError): - completion(response: nil, erorr: encodingError) + completion(response: nil, error: encodingError) } } ) @@ -70,38 +70,35 @@ class AlamofireRequestBuilder: RequestBuilder { } - private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, erorr: ErrorType?) -> Void) { + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, error: ErrorType?) -> Void) { if let credential = self.credential { request.authenticate(usingCredential: credential) } - request.responseJSON(options: .AllowFragments) { (req, res, result) in + request.responseJSON(options: .AllowFragments) { response in managerStore.removeValueForKey(managerId) - if result.isFailure { - completion(response: nil, erorr: result.error) + if response.result.isFailure { + completion(response: nil, error: response.result.error) return } if () is T { - let response = Response(response: res!, body: () as! T) - completion(response: response, erorr: nil) + completion(response: Response(response: response.response!, body: () as! T), error: nil) return } - if let json: AnyObject = result.value { + if let json: AnyObject = response.result.value { let body = Decoders.decode(clazz: T.self, source: json) - let response = Response(response: res!, body: body) - completion(response: response, erorr: nil) + completion(response: Response(response: response.response!, body: body), error: nil) return } else if "" is T { // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release // https://github.com/swagger-api/swagger-parser/pull/34 - let response = Response(response: res!, body: "" as! T) - completion(response: response, erorr: nil) + completion(response: Response(response: response.response!, body: "" as! T), error: nil) return } - completion(response: nil, erorr: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) } } @@ -113,4 +110,3 @@ class AlamofireRequestBuilder: RequestBuilder { return httpHeaders } } - diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift index 7ac67ca1b4a..8266d08a1b2 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift @@ -118,6 +118,10 @@ class Decoders { fatalError("formatter failed to parse \(sourceString)") } + // Decoder for [User] + Decoders.addDecoder(clazz: [User].self) { (source: AnyObject) -> [User] in + return Decoders.decode(clazz: [User].self, source: source) + } // Decoder for User Decoders.addDecoder(clazz: User.self) { (source: AnyObject) -> User in let sourceDictionary = source as! [NSObject:AnyObject] @@ -134,6 +138,10 @@ class Decoders { } + // Decoder for [Category] + Decoders.addDecoder(clazz: [Category].self) { (source: AnyObject) -> [Category] in + return Decoders.decode(clazz: [Category].self, source: source) + } // Decoder for Category Decoders.addDecoder(clazz: Category.self) { (source: AnyObject) -> Category in let sourceDictionary = source as! [NSObject:AnyObject] @@ -144,6 +152,10 @@ class Decoders { } + // Decoder for [Pet] + Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in + return Decoders.decode(clazz: [Pet].self, source: source) + } // Decoder for Pet Decoders.addDecoder(clazz: Pet.self) { (source: AnyObject) -> Pet in let sourceDictionary = source as! [NSObject:AnyObject] @@ -158,6 +170,10 @@ class Decoders { } + // Decoder for [Tag] + Decoders.addDecoder(clazz: [Tag].self) { (source: AnyObject) -> [Tag] in + return Decoders.decode(clazz: [Tag].self, source: source) + } // Decoder for Tag Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in let sourceDictionary = source as! [NSObject:AnyObject] @@ -168,6 +184,10 @@ class Decoders { } + // Decoder for [Order] + Decoders.addDecoder(clazz: [Order].self) { (source: AnyObject) -> [Order] in + return Decoders.decode(clazz: [Order].self, source: source) + } // Decoder for Order Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in let sourceDictionary = source as! [NSObject:AnyObject] diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift index 1356bd1db98..f542ea676f8 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -14,6 +14,8 @@ public class Category: JSONEncodable { public var name: String? + public init() {} + // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift index 25f7745f306..f309744da99 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -25,6 +25,8 @@ public class Order: JSONEncodable { public var complete: Bool? + public init() {} + // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift index b94e5a7a6de..b1491df2516 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -25,6 +25,8 @@ public class Pet: JSONEncodable { public var status: Status? + public init() {} + // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift index b7ab8a3a0cf..edcd73a7a0c 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -14,6 +14,8 @@ public class Tag: JSONEncodable { public var name: String? + public init() {} + // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift index a7592185021..fa0ad3f5019 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -21,6 +21,8 @@ public class User: JSONEncodable { public var userStatus: Int? + public init() {} + // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?]() diff --git a/samples/client/petstore/typescript-angular/API/Client/Category.ts b/samples/client/petstore/typescript-angular/API/Client/Category.ts index 7faf87208eb..a802fe4ebdf 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Category.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Category.ts @@ -1,13 +1,13 @@ /// -module API.Client { +namespace API.Client { 'use strict'; - export class Category { + export interface Category { - id: number; + id?: number; - name: string; + name?: string; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/typescript-angular/API/Client/Order.ts b/samples/client/petstore/typescript-angular/API/Client/Order.ts index abee3a2894b..1dd84e6d0ad 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Order.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Order.ts @@ -1,32 +1,32 @@ /// -module API.Client { +namespace API.Client { 'use strict'; - export class Order { + export interface Order { - id: number; + id?: number; - petId: number; + petId?: number; - quantity: number; + quantity?: number; - shipDate: Date; + shipDate?: Date; /** * Order Status */ - status: Order.StatusEnum; + status?: Order.StatusEnum; - complete: boolean; + complete?: boolean; } - export module Order { + export namespace Order { - export enum StatusEnum { - placed = 'placed', - approved = 'approved', + export enum StatusEnum { + placed = 'placed', + approved = 'approved', delivered = 'delivered', } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/typescript-angular/API/Client/Pet.ts b/samples/client/petstore/typescript-angular/API/Client/Pet.ts index 9523bef90b0..60431f69c83 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Pet.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Pet.ts @@ -1,32 +1,32 @@ /// -module API.Client { +namespace API.Client { 'use strict'; - export class Pet { + export interface Pet { - id: number; + id?: number; - category: Category; + category?: Category; name: string; photoUrls: Array; - tags: Array; + tags?: Array; /** * pet status in the store */ - status: Pet.StatusEnum; + status?: Pet.StatusEnum; } - export module Pet { + export namespace Pet { - export enum StatusEnum { - available = 'available', - pending = 'pending', + export enum StatusEnum { + available = 'available', + pending = 'pending', sold = 'sold', } } -} \ No newline at end of file +} diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index b8eb8c3ae12..11ef0aa3d5a 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -2,26 +2,41 @@ /* tslint:disable:no-unused-variable member-ordering */ -module API.Client { +namespace API.Client { 'use strict'; export class PetApi { - private basePath = 'http://petstore.swagger.io/v2'; + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; static $inject: string[] = ['$http', '$httpParamSerializer']; - constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (any) => any) { + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { if (basePath) { this.basePath = basePath; } } - public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/pet'; + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } - var queryParameters: any = {}; - var headerParams: any = {}; - var httpRequestParams: any = { + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const path = this.basePath + '/pet'; + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let httpRequestParams: any = { method: 'PUT', url: path, json: true, @@ -33,22 +48,22 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ public addPet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/pet'; + const path = this.basePath + '/pet'; - var queryParameters: any = {}; - var headerParams: any = {}; - var httpRequestParams: any = { + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let httpRequestParams: any = { method: 'POST', url: path, json: true, @@ -60,26 +75,26 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * 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 + */ public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { - var path = this.basePath + '/pet/findByStatus'; + const path = this.basePath + '/pet/findByStatus'; - var queryParameters: any = {}; - var headerParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); if (status !== undefined) { queryParameters['status'] = status; } - var httpRequestParams: any = { + let httpRequestParams: any = { method: 'GET', url: path, json: true, @@ -90,26 +105,26 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * 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 + */ public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { - var path = this.basePath + '/pet/findByTags'; + const path = this.basePath + '/pet/findByTags'; - var queryParameters: any = {}; - var headerParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); if (tags !== undefined) { queryParameters['tags'] = tags; } - var httpRequestParams: any = { + let httpRequestParams: any = { method: 'GET', url: path, json: true, @@ -120,29 +135,27 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * 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 + */ public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { - var path = this.basePath + '/pet/{petId}'; + const path = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); - path = path.replace('{' + 'petId' + '}', String(petId)); - - var queryParameters: any = {}; - var headerParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling getPetById'); } - - var httpRequestParams: any = { + let httpRequestParams: any = { method: 'GET', url: path, json: true, @@ -153,37 +166,37 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * 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 + */ public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/pet/{petId}'; + const path = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); - path = path.replace('{' + 'petId' + '}', String(petId)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; formParams['name'] = name; - + formParams['status'] = status; - - var httpRequestParams: any = { + + let httpRequestParams: any = { method: 'POST', url: path, json: false, @@ -195,31 +208,30 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/pet/{petId}'; + const path = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); - path = path.replace('{' + 'petId' + '}', String(petId)); - - var queryParameters: any = {}; - var headerParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling deletePet'); } - headerParams['api_key'] = apiKey; - var httpRequestParams: any = { + let httpRequestParams: any = { method: 'DELETE', url: path, json: true, @@ -230,37 +242,37 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/pet/{petId}/uploadImage'; + const path = this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', String(petId)); - path = path.replace('{' + 'petId' + '}', String(petId)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling uploadFile'); } - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; formParams['additionalMetadata'] = additionalMetadata; - + formParams['file'] = file; - - var httpRequestParams: any = { + + let httpRequestParams: any = { method: 'POST', url: path, json: false, @@ -272,11 +284,7 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index 739f6039e6c..3d3c445a144 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -2,26 +2,40 @@ /* tslint:disable:no-unused-variable member-ordering */ -module API.Client { +namespace API.Client { 'use strict'; export class StoreApi { - private basePath = 'http://petstore.swagger.io/v2'; + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; static $inject: string[] = ['$http', '$httpParamSerializer']; - constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (any) => any) { + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { if (basePath) { this.basePath = basePath; } } - public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> { - var path = this.basePath + '/store/inventory'; + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } - var queryParameters: any = {}; - var headerParams: any = {}; - var httpRequestParams: any = { + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> { + const path = this.basePath + '/store/inventory'; + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let httpRequestParams: any = { method: 'GET', url: path, json: true, @@ -32,22 +46,22 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ public placeOrder (body?: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { - var path = this.basePath + '/store/order'; + const path = this.basePath + '/store/order'; - var queryParameters: any = {}; - var headerParams: any = {}; - var httpRequestParams: any = { + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let httpRequestParams: any = { method: 'POST', url: path, json: true, @@ -59,29 +73,27 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { - var path = this.basePath + '/store/order/{orderId}'; + const path = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - var queryParameters: any = {}; - var headerParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling getOrderById'); } - - var httpRequestParams: any = { + let httpRequestParams: any = { method: 'GET', url: path, json: true, @@ -92,29 +104,27 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/store/order/{orderId}'; + const path = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - var queryParameters: any = {}; - var headerParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling deleteOrder'); } - - var httpRequestParams: any = { + let httpRequestParams: any = { method: 'DELETE', url: path, json: true, @@ -125,11 +135,7 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); diff --git a/samples/client/petstore/typescript-angular/API/Client/Tag.ts b/samples/client/petstore/typescript-angular/API/Client/Tag.ts index 2ec9b456f27..1c0284cce48 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Tag.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Tag.ts @@ -1,13 +1,13 @@ /// -module API.Client { +namespace API.Client { 'use strict'; - export class Tag { + export interface Tag { - id: number; + id?: number; - name: string; + name?: string; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/typescript-angular/API/Client/User.ts b/samples/client/petstore/typescript-angular/API/Client/User.ts index ca8ac57c7a3..7c2b0b78b0c 100644 --- a/samples/client/petstore/typescript-angular/API/Client/User.ts +++ b/samples/client/petstore/typescript-angular/API/Client/User.ts @@ -1,28 +1,28 @@ /// -module API.Client { +namespace API.Client { 'use strict'; - export class User { + export interface User { - id: number; + id?: number; - username: string; + username?: string; - firstName: string; + firstName?: string; - lastName: string; + lastName?: string; - email: string; + email?: string; - password: string; + password?: string; - phone: string; + phone?: string; /** * User Status */ - userStatus: number; + userStatus?: number; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 26ebd693db9..376bdb8935a 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -2,26 +2,41 @@ /* tslint:disable:no-unused-variable member-ordering */ -module API.Client { +namespace API.Client { 'use strict'; export class UserApi { - private basePath = 'http://petstore.swagger.io/v2'; + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; static $inject: string[] = ['$http', '$httpParamSerializer']; - constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (any) => any) { + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { if (basePath) { this.basePath = basePath; } } + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ public createUser (body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/user'; + const path = this.basePath + '/user'; - var queryParameters: any = {}; - var headerParams: any = {}; - var httpRequestParams: any = { + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let httpRequestParams: any = { method: 'POST', url: path, json: true, @@ -33,22 +48,22 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Creates list of users with given input array + * + * @param body List of user object + */ public createUsersWithArrayInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/user/createWithArray'; + const path = this.basePath + '/user/createWithArray'; - var queryParameters: any = {}; - var headerParams: any = {}; - var httpRequestParams: any = { + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let httpRequestParams: any = { method: 'POST', url: path, json: true, @@ -60,22 +75,22 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Creates list of users with given input array + * + * @param body List of user object + */ public createUsersWithListInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/user/createWithList'; + const path = this.basePath + '/user/createWithList'; - var queryParameters: any = {}; - var headerParams: any = {}; - var httpRequestParams: any = { + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let httpRequestParams: any = { method: 'POST', url: path, json: true, @@ -87,21 +102,22 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { - var path = this.basePath + '/user/login'; + const path = this.basePath + '/user/login'; - var queryParameters: any = {}; - var headerParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); if (username !== undefined) { queryParameters['username'] = username; } @@ -110,7 +126,7 @@ module API.Client { queryParameters['password'] = password; } - var httpRequestParams: any = { + let httpRequestParams: any = { method: 'GET', url: path, json: true, @@ -121,22 +137,21 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Logs out current logged in user session + * + */ public logoutUser (extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/user/logout'; + const path = this.basePath + '/user/logout'; - var queryParameters: any = {}; - var headerParams: any = {}; - var httpRequestParams: any = { + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let httpRequestParams: any = { method: 'GET', url: path, json: true, @@ -147,29 +162,27 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { - var path = this.basePath + '/user/{username}'; + const path = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); - path = path.replace('{' + 'username' + '}', String(username)); - - var queryParameters: any = {}; - var headerParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling getUserByName'); } - - var httpRequestParams: any = { + let httpRequestParams: any = { method: 'GET', url: path, json: true, @@ -180,29 +193,28 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ public updateUser (username: string, body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/user/{username}'; + const path = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); - path = path.replace('{' + 'username' + '}', String(username)); - - var queryParameters: any = {}; - var headerParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling updateUser'); } - - var httpRequestParams: any = { + let httpRequestParams: any = { method: 'PUT', url: path, json: true, @@ -214,29 +226,27 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); } - + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/user/{username}'; + const path = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); - path = path.replace('{' + 'username' + '}', String(username)); - - var queryParameters: any = {}; - var headerParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling deleteUser'); } - - var httpRequestParams: any = { + let httpRequestParams: any = { method: 'DELETE', url: path, json: true, @@ -247,11 +257,7 @@ module API.Client { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { - if (extraHttpRequestParams.hasOwnProperty(k)) { - httpRequestParams[k] = extraHttpRequestParams[k]; - } - } + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); diff --git a/samples/client/petstore/typescript-angular/tsconfig.json b/samples/client/petstore/typescript-angular/tsconfig.json index c389d5011ff..9bf11bd4cee 100644 --- a/samples/client/petstore/typescript-angular/tsconfig.json +++ b/samples/client/petstore/typescript-angular/tsconfig.json @@ -1,18 +1,19 @@ { - "compilerOptions": { - "noImplicitAny": true, - "out": "client.js" - }, - "files": [ - "API/Client/Category.ts", - "API/Client/Pet.ts", - "API/Client/StoreApi.ts", - "API/Client/User.ts", - "API/Client/api.d.ts", - "API/Client/Order.ts", - "API/Client/PetApi.ts", - "API/Client/Tag.ts", - "API/Client/UserApi.ts", - "typings/tsd.d.ts" - ] + "compilerOptions": { + "noImplicitAny": true, + "suppressImplicitAnyIndexErrors": true, + "out": "client.js" + }, + "files": [ + "API/Client/Category.ts", + "API/Client/Pet.ts", + "API/Client/StoreApi.ts", + "API/Client/User.ts", + "API/Client/api.d.ts", + "API/Client/Order.ts", + "API/Client/PetApi.ts", + "API/Client/Tag.ts", + "API/Client/UserApi.ts", + "typings/tsd.d.ts" + ] } diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index 148782a4000..ab5f05b46cb 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -39,7 +39,7 @@ export class Pet { status: Pet.StatusEnum; } -export module Pet { +export namespace Pet { export enum StatusEnum { available = 'available', pending = 'pending', @@ -63,7 +63,7 @@ export class Order { complete: boolean; } -export module Order { +export namespace Order { export enum StatusEnum { placed = 'placed', approved = 'approved', @@ -118,7 +118,11 @@ class VoidAuth implements Authentication { } export class UserApi { - private basePath = 'http://petstore.swagger.io/v2'; + protected basePath = 'http://petstore.swagger.io/v2'; + protected defaultHeaders : any = {}; + + + public authentications = { 'default': new VoidAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), @@ -141,20 +145,31 @@ export class UserApi { set apiKey(key: string) { this.authentications.api_key.apiKey = key; } - - public createUser (body?: User) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/user'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, @@ -187,20 +202,23 @@ export class UserApi { return deferred.promise; } - - public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/createWithArray'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/user/createWithArray'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, @@ -233,20 +251,23 @@ export class UserApi { return deferred.promise; } - - public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/createWithList'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/user/createWithList'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, @@ -279,13 +300,17 @@ export class UserApi { return deferred.promise; } - + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { - var path = this.url + this.basePath + '/user/login'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + const path = this.url + this.basePath + '/user/login'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; if (username !== undefined) { @@ -296,11 +321,11 @@ export class UserApi { queryParameters['password'] = password; } - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, @@ -332,20 +357,22 @@ export class UserApi { return deferred.promise; } - - public logoutUser () : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/logout'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + /** + * Logs out current logged in user session + * + */ + public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/user/logout'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, @@ -377,15 +404,17 @@ export class UserApi { return deferred.promise; } - + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { - var path = this.url + this.basePath + '/user/{username}'; - - path = path.replace('{' + 'username' + '}', String(username)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + const path = this.url + this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; // verify required parameter 'username' is set @@ -393,11 +422,11 @@ export class UserApi { throw new Error('Missing required parameter username when calling getUserByName'); } - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, @@ -429,15 +458,18 @@ export class UserApi { return deferred.promise; } - - public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/{username}'; - - path = path.replace('{' + 'username' + '}', String(username)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; // verify required parameter 'username' is set @@ -445,11 +477,11 @@ export class UserApi { throw new Error('Missing required parameter username when calling updateUser'); } - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'PUT', qs: queryParameters, headers: headerParams, @@ -482,15 +514,17 @@ export class UserApi { return deferred.promise; } - - public deleteUser (username: string) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/{username}'; - - path = path.replace('{' + 'username' + '}', String(username)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + public deleteUser (username: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; // verify required parameter 'username' is set @@ -498,11 +532,11 @@ export class UserApi { throw new Error('Missing required parameter username when calling deleteUser'); } - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, @@ -536,7 +570,11 @@ export class UserApi { } } export class PetApi { - private basePath = 'http://petstore.swagger.io/v2'; + protected basePath = 'http://petstore.swagger.io/v2'; + protected defaultHeaders : any = {}; + + + public authentications = { 'default': new VoidAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), @@ -559,20 +597,31 @@ export class PetApi { set apiKey(key: string) { this.authentications.api_key.apiKey = key; } - - public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/pet'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'PUT', qs: queryParameters, headers: headerParams, @@ -607,20 +656,23 @@ export class PetApi { return deferred.promise; } - - public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/pet'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, @@ -655,24 +707,27 @@ export class PetApi { return deferred.promise; } - + /** + * 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 + */ public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { - var path = this.url + this.basePath + '/pet/findByStatus'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + const path = this.url + this.basePath + '/pet/findByStatus'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; if (status !== undefined) { queryParameters['status'] = status; } - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, @@ -706,24 +761,27 @@ export class PetApi { return deferred.promise; } - + /** + * 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 + */ public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { - var path = this.url + this.basePath + '/pet/findByTags'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + const path = this.url + this.basePath + '/pet/findByTags'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; if (tags !== undefined) { queryParameters['tags'] = tags; } - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, @@ -757,15 +815,17 @@ export class PetApi { return deferred.promise; } - + /** + * 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 + */ public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - path = path.replace('{' + 'petId' + '}', String(petId)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + const path = this.url + this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; // verify required parameter 'petId' is set @@ -773,11 +833,11 @@ export class PetApi { throw new Error('Missing required parameter petId when calling getPetById'); } - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, @@ -787,8 +847,6 @@ export class PetApi { this.authentications.api_key.applyToRequest(requestOptions); - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -813,15 +871,19 @@ export class PetApi { return deferred.promise; } - - public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - path = path.replace('{' + 'petId' + '}', String(petId)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + /** + * 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 + */ + public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; // verify required parameter 'petId' is set @@ -829,7 +891,7 @@ export class PetApi { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } - var useFormData = false; + let useFormData = false; if (name !== undefined) { formParams['name'] = name; @@ -839,9 +901,9 @@ export class PetApi { formParams['status'] = status; } - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, @@ -875,15 +937,18 @@ export class PetApi { return deferred.promise; } - - public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - path = path.replace('{' + 'petId' + '}', String(petId)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; // verify required parameter 'petId' is set @@ -893,11 +958,11 @@ export class PetApi { headerParams['api_key'] = apiKey; - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, @@ -931,15 +996,19 @@ export class PetApi { return deferred.promise; } - - public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}/uploadImage'; - - path = path.replace('{' + 'petId' + '}', String(petId)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', String(petId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; // verify required parameter 'petId' is set @@ -947,7 +1016,7 @@ export class PetApi { throw new Error('Missing required parameter petId when calling uploadFile'); } - var useFormData = false; + let useFormData = false; if (additionalMetadata !== undefined) { formParams['additionalMetadata'] = additionalMetadata; @@ -958,9 +1027,9 @@ export class PetApi { } useFormData = true; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, @@ -996,7 +1065,11 @@ export class PetApi { } } export class StoreApi { - private basePath = 'http://petstore.swagger.io/v2'; + protected basePath = 'http://petstore.swagger.io/v2'; + protected defaultHeaders : any = {}; + + + public authentications = { 'default': new VoidAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), @@ -1019,20 +1092,30 @@ export class StoreApi { set apiKey(key: string) { this.authentications.api_key.apiKey = key; } - + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { - var path = this.url + this.basePath + '/store/inventory'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + const path = this.url + this.basePath + '/store/inventory'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, @@ -1066,20 +1149,23 @@ export class StoreApi { return deferred.promise; } - + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order'; - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + const path = this.url + this.basePath + '/store/order'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'POST', qs: queryParameters, headers: headerParams, @@ -1112,15 +1198,17 @@ export class StoreApi { return deferred.promise; } - + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + */ public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; - - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + const path = this.url + this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; // verify required parameter 'orderId' is set @@ -1128,11 +1216,11 @@ export class StoreApi { throw new Error('Missing required parameter orderId when calling getOrderById'); } - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'GET', qs: queryParameters, headers: headerParams, @@ -1164,15 +1252,17 @@ export class StoreApi { return deferred.promise; } - - public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; - - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const path = this.url + this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; // verify required parameter 'orderId' is set @@ -1180,11 +1270,11 @@ export class StoreApi { throw new Error('Missing required parameter orderId when calling deleteOrder'); } - var useFormData = false; + let useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: 'DELETE', qs: queryParameters, headers: headerParams, diff --git a/samples/client/petstore/typescript-node/client.ts b/samples/client/petstore/typescript-node/client.ts index 111c76f03c7..506f33f014e 100644 --- a/samples/client/petstore/typescript-node/client.ts +++ b/samples/client/petstore/typescript-node/client.ts @@ -1,7 +1,7 @@ import api = require('./api'); import fs = require('fs'); -var petApi = new api.PetApi('http://petstore.swagger.io'); +var petApi = new api.PetApi('http://petstore.swagger.io/'); petApi.apiKey = 'special-key'; var pet = new api.Pet(); @@ -13,39 +13,39 @@ var exitCode = 0; // Test various API calls to the petstore petApi.addPet(pet) -.then((res) => { - var newPet = (res.response).body; - petId = (res.response).body.id; - console.log(`Created pet with ID ${petId}`); - newPet.status = api.Pet.StatusEnum.available; - return petApi.updatePet(newPet); -}) -.then((res) => { - console.log('Updated pet using POST body'); - return petApi.updatePetWithForm(petId, undefined, "pending"); -}) -.then((res) => { - console.log('Updated pet using POST form'); - return petApi.uploadFile(petId, undefined, fs.createReadStream('sample.png')); -}) -.then((res) => { - console.log('Uploaded image'); - return petApi.getPetById(petId); -}) -.then((res) => { - console.log('Got pet by ID: ' + JSON.stringify(res.body)); - if (res.body.status != api.Pet.StatusEnum.pending) { - throw new Error("Unexpected pet status"); - } -}) -.catch((err:any) => { - console.error(err); - exitCode = 1; -}) -.finally(() => { - return petApi.deletePet(petId); -}) -.then((res) => { - console.log('Deleted pet'); - process.exit(exitCode); -}); + .then((res) => { + var newPet = res.body; + petId = newPet.id; + console.log(`Created pet with ID ${petId}`); + newPet.status = api.Pet.StatusEnum.available; + return petApi.updatePet(newPet); + }) + .then((res) => { + console.log('Updated pet using POST body'); + return petApi.updatePetWithForm(petId, undefined, "pending"); + }) + .then((res) => { + console.log('Updated pet using POST form'); + return petApi.uploadFile(petId, undefined, fs.createReadStream('sample.png')); + }) + .then((res) => { + console.log('Uploaded image'); + return petApi.getPetById(petId); + }) + .then((res) => { + console.log('Got pet by ID: ' + JSON.stringify(res.body)); + if (res.body.status != api.Pet.StatusEnum.pending) { + throw new Error("Unexpected pet status"); + } + }) + .catch((err: any) => { + console.error(err); + exitCode = 1; + }) + .finally(() => { + return petApi.deletePet(petId); + }) + .then((res) => { + console.log('Deleted pet'); + process.exit(exitCode); + }); diff --git a/samples/client/petstore/typescript-node/tsconfig.json b/samples/client/petstore/typescript-node/tsconfig.json index 572228f6356..7c4f5847040 100644 --- a/samples/client/petstore/typescript-node/tsconfig.json +++ b/samples/client/petstore/typescript-node/tsconfig.json @@ -2,6 +2,7 @@ "compilerOptions": { "module": "commonjs", "noImplicitAny": true, + "suppressImplicitAnyIndexErrors": true, "target": "ES5" }, "files": [ diff --git a/samples/dynamic-html/docs/assets/css/style.css b/samples/dynamic-html/docs/assets/css/style.css index f14f6bdb62c..b596c11a535 100644 --- a/samples/dynamic-html/docs/assets/css/style.css +++ b/samples/dynamic-html/docs/assets/css/style.css @@ -100,6 +100,10 @@ float: left; } +.param-enum { + margin-left: 20px; +} + .section-header { border-bottom: 2px; font-weight: bold; diff --git a/samples/dynamic-html/docs/models/Category.html b/samples/dynamic-html/docs/models/Category.html index 15c6820eead..99ec473bcc7 100644 --- a/samples/dynamic-html/docs/models/Category.html +++ b/samples/dynamic-html/docs/models/Category.html @@ -3,13 +3,15 @@
  • id : Long -
    +
    +
  • name : String -
    +
    +
diff --git a/samples/dynamic-html/docs/models/Order.html b/samples/dynamic-html/docs/models/Order.html index 82278a470c2..a45f7d6cd65 100644 --- a/samples/dynamic-html/docs/models/Order.html +++ b/samples/dynamic-html/docs/models/Order.html @@ -3,37 +3,55 @@
  • id : Long -
    +
    +
  • petId : Long -
    +
    +
  • quantity : Integer -
    +
    +
  • shipDate : Date -
    +
    +
  • status : String -
    Order Status +
    Order Status + +
    +
    Enum: + +
    placed
    + +
    approved
    + +
    delivered
    + + +
    +
  • complete : Boolean -
    +
    +
diff --git a/samples/dynamic-html/docs/models/Pet.html b/samples/dynamic-html/docs/models/Pet.html index 17468477704..2578f97e660 100644 --- a/samples/dynamic-html/docs/models/Pet.html +++ b/samples/dynamic-html/docs/models/Pet.html @@ -3,37 +3,55 @@
  • id : Long -
    +
    +
  • category : Category -
    +
    +
  • name : String -
    +
    +
  • photoUrls : List -
    +
    +
  • tags : List -
    +
    +
  • status : String -
    pet status in the store +
    pet status in the store + +
    +
    Enum: + +
    available
    + +
    pending
    + +
    sold
    + + +
    +
diff --git a/samples/dynamic-html/docs/models/Tag.html b/samples/dynamic-html/docs/models/Tag.html index e84b50d73d6..bf1ef9eadaf 100644 --- a/samples/dynamic-html/docs/models/Tag.html +++ b/samples/dynamic-html/docs/models/Tag.html @@ -3,13 +3,15 @@
  • id : Long -
    +
    +
  • name : String -
    +
    +
diff --git a/samples/dynamic-html/docs/models/User.html b/samples/dynamic-html/docs/models/User.html index c71cf6649d7..d742aa7cfde 100644 --- a/samples/dynamic-html/docs/models/User.html +++ b/samples/dynamic-html/docs/models/User.html @@ -3,49 +3,57 @@
  • id : Long -
    +
    +
  • username : String -
    +
    +
  • firstName : String -
    +
    +
  • lastName : String -
    +
    +
  • email : String -
    +
    +
  • password : String -
    +
    +
  • phone : String -
    +
    +
  • userStatus : Integer -
    User Status +
    User Status +
diff --git a/samples/html/index.html b/samples/html/index.html index 67d651d9307..cae7e02c9e0 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -1,685 +1,11 @@ - + + + - - API Reference - - -

Swagger Petstore

-
This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters for
- -
Contact Info: apiteam@swagger.io
-
Version: 1.0.0
-
Apache 2.0
-
http://www.apache.org/licenses/LICENSE-2.0.html
-

Access

-
Customize this message as you see fit!
-

Methods

- - - -
-
put: /pet
-
Pet
-
updatePet Update an existing pet
-
- -

Parameters

-
-
body (optional)
- -
Body Parameter — Pet object that needs to be added to the store
- -
-

Return type

- -
- - -
-
- -
-
post: /pet
-
Pet
-
addPet Add a new pet to the store
-
- -

Parameters

-
-
body (optional)
- -
Body Parameter — Pet object that needs to be added to the store
- -
-

Return type

- -
- - -
-
- -
-
get: /pet/findByStatus
-
Pet
-
findPetsByStatus Finds Pets by status
-
Multiple status values can be provided with comma seperated strings
- -

Parameters

-
-
status (optional)
- -
Query Parameter — Status values that need to be considered for filter default: available
- -
-

Return type

- - - - -

Example data

-
Content-Type: application/json
-
[ {
-  "photoUrls" : [ "aeiou" ],
-  "name" : "doggie",
-  "id" : 123456789,
-  "category" : {
-    "name" : "aeiou",
-    "id" : 123456789
-  },
-  "tags" : [ {
-    "name" : "aeiou",
-    "id" : 123456789
-  } ],
-  "status" : "aeiou"
-} ]
- -

Example data

-
Content-Type: application/xml
-
<Pet>
-  <id>123456</id>
-  <name>doggie</name>
-  <photoUrls>string</photoUrls>
-  <status>string</status>
-</Pet>
- -
-
- -
-
get: /pet/findByTags
-
Pet
-
findPetsByTags Finds Pets by tags
-
Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
- -

Parameters

-
-
tags (optional)
- -
Query Parameter — Tags to filter by
- -
-

Return type

- - - - -

Example data

-
Content-Type: application/json
-
[ {
-  "photoUrls" : [ "aeiou" ],
-  "name" : "doggie",
-  "id" : 123456789,
-  "category" : {
-    "name" : "aeiou",
-    "id" : 123456789
-  },
-  "tags" : [ {
-    "name" : "aeiou",
-    "id" : 123456789
-  } ],
-  "status" : "aeiou"
-} ]
- -

Example data

-
Content-Type: application/xml
-
<Pet>
-  <id>123456</id>
-  <name>doggie</name>
-  <photoUrls>string</photoUrls>
-  <status>string</status>
-</Pet>
- -
-
- -
-
get: /pet/{petId}
-
Pet
-
getPetById Find pet by ID
-
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
- -

Parameters

-
-
petId (required)
- -
Path Parameter — ID of pet that needs to be fetched
- -
-

Return type

- - - - -

Example data

-
Content-Type: application/json
-
{
-  "photoUrls" : [ "aeiou" ],
-  "name" : "doggie",
-  "id" : 123456789,
-  "category" : {
-    "name" : "aeiou",
-    "id" : 123456789
-  },
-  "tags" : [ {
-    "name" : "aeiou",
-    "id" : 123456789
-  } ],
-  "status" : "aeiou"
-}
- -

Example data

-
Content-Type: application/xml
-
<Pet>
-  <id>123456</id>
-  <name>doggie</name>
-  <photoUrls>string</photoUrls>
-  <status>string</status>
-</Pet>
- -
-
- -
-
post: /pet/{petId}
-
Pet
-
updatePetWithForm Updates a pet in the store with form data
-
- -

Parameters

-
-
petId (required)
- -
Path Parameter — ID of pet that needs to be updated
-
name (optional)
- -
Form Parameter — Updated name of the pet
-
status (optional)
- -
Form Parameter — Updated status of the pet
- -
-

Return type

- -
- - -
-
- -
-
delete: /pet/{petId}
-
Pet
-
deletePet Deletes a pet
-
- -

Parameters

-
-
apiKey (optional)
- -
Header Parameter
-
petId (required)
- -
Path Parameter — Pet id to delete
- -
-

Return type

- -
- - -
-
- -
-
post: /pet/{petId}/uploadImage
-
Pet
-
uploadFile uploads an image
-
- -

Parameters

-
-
petId (required)
- -
Path Parameter — ID of pet to update
-
additionalMetadata (optional)
- -
Form Parameter — Additional data to pass to server
-
file (optional)
- -
Form Parameter — file to upload
- -
-

Return type

- -
- - -
-
- -
-
get: /store/inventory
-
Store
-
getInventory Returns pet inventories by status
-
Returns a map of status codes to quantities
- -

Parameters

-
- -
-

Return type

- - - - -

Example data

-
Content-Type: application/json
-
{
-  "key" : 123
-}
- -

Example data

-
Content-Type: application/xml
-
not implemented io.swagger.models.properties.MapProperty@3e
- -
-
- -
-
post: /store/order
-
Store
-
placeOrder Place an order for a pet
-
- -

Parameters

-
-
body (optional)
- -
Body Parameter — order placed for purchasing the pet
- -
-

Return type

- - - - -

Example data

-
Content-Type: application/json
-
{
-  "petId" : 123456789,
-  "quantity" : 123,
-  "id" : 123456789,
-  "shipDate" : "2015-06-09T07:23:55.625+0000",
-  "complete" : true,
-  "status" : "aeiou"
-}
- -

Example data

-
Content-Type: application/xml
-
<Order>
-  <id>123456</id>
-  <petId>123456</petId>
-  <quantity>0</quantity>
-  <shipDate>2015-06-09T00:23:55.631Z</shipDate>
-  <status>string</status>
-  <complete>true</complete>
-</Order>
- -
-
- -
-
get: /store/order/{orderId}
-
Store
-
getOrderById Find purchase order by ID
-
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
- -

Parameters

-
-
orderId (required)
- -
Path Parameter — ID of pet that needs to be fetched
- -
-

Return type

- - - - -

Example data

-
Content-Type: application/json
-
{
-  "petId" : 123456789,
-  "quantity" : 123,
-  "id" : 123456789,
-  "shipDate" : "2015-06-09T07:23:55.632+0000",
-  "complete" : true,
-  "status" : "aeiou"
-}
- -

Example data

-
Content-Type: application/xml
-
<Order>
-  <id>123456</id>
-  <petId>123456</petId>
-  <quantity>0</quantity>
-  <shipDate>2015-06-09T00:23:55.633Z</shipDate>
-  <status>string</status>
-  <complete>true</complete>
-</Order>
- -
-
- -
-
delete: /store/order/{orderId}
-
Store
-
deleteOrder Delete purchase order by ID
-
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
- -

Parameters

-
-
orderId (required)
- -
Path Parameter — ID of the order that needs to be deleted
- -
-

Return type

- -
- - -
-
- -
-
post: /user
-
User
-
createUser Create user
-
This can only be done by the logged in user.
- -

Parameters

-
-
body (optional)
- -
Body Parameter — Created user object
- -
-

Return type

- -
- - -
-
- -
-
post: /user/createWithArray
-
User
-
createUsersWithArrayInput Creates list of users with given input array
-
- -

Parameters

-
-
body (optional)
- -
Body Parameter — List of user object
- -
-

Return type

- -
- - -
-
- -
-
post: /user/createWithList
-
User
-
createUsersWithListInput Creates list of users with given input array
-
- -

Parameters

-
-
body (optional)
- -
Body Parameter — List of user object
- -
-

Return type

- -
- - -
-
- -
-
get: /user/login
-
User
-
loginUser Logs user into the system
-
- -

Parameters

-
-
username (optional)
- -
Query Parameter — The user name for login
-
password (optional)
- -
Query Parameter — The password for login in clear text
- -
-

Return type

- - - - -

Example data

-
Content-Type: application/json
-
"aeiou"
- -

Example data

-
Content-Type: application/xml
-
string
- -
-
- -
-
get: /user/logout
-
User
-
logoutUser Logs out current logged in user session
-
- -

Parameters

-
- -
-

Return type

- -
- - -
-
- -
-
get: /user/{username}
-
User
-
getUserByName Get user by user name
-
- -

Parameters

-
-
username (required)
- -
Path Parameter — The name that needs to be fetched. Use user1 for testing.
- -
-

Return type

- - - - -

Example data

-
Content-Type: application/json
-
{
-  "id" : 1,
-  "username" : "johnp",
-  "firstName" : "John",
-  "lastName" : "Public",
-  "email" : "johnp@swagger.io",
-  "password" : "-secret-",
-  "phone" : "0123456789",
-  "userStatus" : 0
-}
- -
-
- -
-
put: /user/{username}
-
User
-
updateUser Updated user
-
This can only be done by the logged in user.
- -

Parameters

-
-
username (required)
- -
Path Parameter — name that need to be deleted
-
body (optional)
- -
Body Parameter — Updated user object
- -
-

Return type

- -
- - -
-
- -
-
delete: /user/{username}
-
User
-
deleteUser Delete user
-
This can only be done by the logged in user.
- -

Parameters

-
-
username (required)
- -
Path Parameter — The name that needs to be deleted
- -
-

Return type

- -
- - -
-
- - - -

Models

- - -
-

User

-
-
id
Long
-
username
String
-
firstName
String
-
lastName
String
-
email
String
-
password
String
-
phone
String
-
userStatus
Integer User Status
- -
-
- - - -
-

Category

-
-
id
Long
-
name
String
- -
-
- - - -
-

Pet

-
-
id
Long
-
category
Category
-
name
String
-
photoUrls
array[String]
-
tags
array[Tag]
-
status
String pet status in the store
- -
-
- - - -
-

Tag

-
-
id
Long
-
name
String
- -
-
- - - -
-

Order

-
-
id
Long
-
petId
Long
-
quantity
Integer
-
shipDate
Date
-
status
String Order Status
-
complete
Boolean
- -
-
- - - + + + +

Swagger Petstore

+
This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters
+ +
Contact Info: apiteam@swagger.io
+
Version: 1.0.0
+
Apache 2.0
+
http://www.apache.org/licenses/LICENSE-2.0.html
+

Access

+ + +

Methods

+ [ Jump to Models ] + + +

Table of Contents

+
+ +
    + + + +
  1. put /pet
  2. + +
  3. post /pet
  4. + +
  5. get /pet/findByStatus
  6. + +
  7. get /pet/findByTags
  8. + +
  9. get /pet/{petId}
  10. + +
  11. post /pet/{petId}
  12. + +
  13. delete /pet/{petId}
  14. + +
  15. post /pet/{petId}/uploadImage
  16. + +
  17. get /store/inventory
  18. + +
  19. post /store/order
  20. + +
  21. get /store/order/{orderId}
  22. + +
  23. delete /store/order/{orderId}
  24. + +
  25. post /user
  26. + +
  27. post /user/createWithArray
  28. + +
  29. post /user/createWithList
  30. + +
  31. get /user/login
  32. + +
  33. get /user/logout
  34. + +
  35. get /user/{username}
  36. + +
  37. put /user/{username}
  38. + +
  39. delete /user/{username}
  40. + + + +
+ + + + + + +
+
+ Up +
put /pet
+
Update an existing pet (updatePet)
+ +
+ + + + +

Consumes

+ This API call consumes the following media types via the Content-Type request header: +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + + +

Request body

+
+
body (optional)
+ +
Body Parameter — Pet object that needs to be added to the store
+
+ + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

400

+ Invalid ID supplied + + +

404

+ Pet not found + + +

405

+ Validation exception + + +
+
+ +
+
+ Up +
post /pet
+
Add a new pet to the store (addPet)
+ +
+ + + + +

Consumes

+ This API call consumes the following media types via the Content-Type request header: +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + + +

Request body

+
+
body (optional)
+ +
Body Parameter — Pet object that needs to be added to the store
+
+ + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

405

+ Invalid input + + +
+
+ +
+
+ Up +
get /pet/findByStatus
+
Finds Pets by status (findPetsByStatus)
+ +
Multiple status values can be provided with comma seperated strings
+ + + + + + + + + + +

Query parameters

+
+
status (optional)
+ +
Query Parameter — Status values that need to be considered for filter default: available
+
+ + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

200

+ successful operation + + +

400

+ Invalid status value + + +
+
+ +
+
+ Up +
get /pet/findByTags
+
Finds Pets by tags (findPetsByTags)
+ +
Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
+ + + + + + + + + + +

Query parameters

+
+
tags (optional)
+ +
Query Parameter — Tags to filter by
+
+ + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

200

+ successful operation + + +

400

+ Invalid tag value + + +
+
+ +
+
+ Up +
get /pet/{petId}
+
Find pet by ID (getPetById)
+ +
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
+ + +

Path parameters

+
+
petId (required)
+ +
Path Parameter — ID of pet that needs to be fetched
+
+ + + + + + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

200

+ successful operation + + +

400

+ Invalid ID supplied + + +

404

+ Pet not found + + +
+
+ +
+
+ Up +
post /pet/{petId}
+
Updates a pet in the store with form data (updatePetWithForm)
+ +
+ + +

Path parameters

+
+
petId (required)
+ +
Path Parameter — ID of pet that needs to be updated
+
+ + + +

Consumes

+ This API call consumes the following media types via the Content-Type request header: +
    + +
  • application/x-www-form-urlencoded
  • + +
+ + + + + + + + + +

Form parameters

+
+
name (optional)
+ +
Form Parameter — Updated name of the pet
status (optional)
+ +
Form Parameter — Updated status of the pet
+
+ + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

405

+ Invalid input + + +
+
+ +
+
+ Up +
delete /pet/{petId}
+
Deletes a pet (deletePet)
+ +
+ + +

Path parameters

+
+
petId (required)
+ +
Path Parameter — Pet id to delete
+
+ + + + + + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

400

+ Invalid pet value + + +
+
+ +
+
+ Up +
post /pet/{petId}/uploadImage
+
uploads an image (uploadFile)
+ +
+ + +

Path parameters

+
+
petId (required)
+ +
Path Parameter — ID of pet to update
+
+ + + +

Consumes

+ This API call consumes the following media types via the Content-Type request header: +
    + +
  • multipart/form-data
  • + +
+ + + + + + + + + +

Form parameters

+
+
additionalMetadata (optional)
+ +
Form Parameter — Additional data to pass to server
file (optional)
+ +
Form Parameter — file to upload
+
+ + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

0

+ successful operation + + +
+
+ +
+
+ Up +
get /store/inventory
+
Returns pet inventories by status (getInventory)
+ +
Returns a map of status codes to quantities
+ + + + + + + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

200

+ successful operation + + +
+
+ +
+
+ Up +
post /store/order
+
Place an order for a pet (placeOrder)
+ +
+ + + + + + +

Request body

+
+
body (optional)
+ +
Body Parameter — order placed for purchasing the pet
+
+ + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

200

+ successful operation + + +

400

+ Invalid Order + + +
+
+ +
+
+ Up +
get /store/order/{orderId}
+
Find purchase order by ID (getOrderById)
+ +
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
+ + +

Path parameters

+
+
orderId (required)
+ +
Path Parameter — ID of pet that needs to be fetched
+
+ + + + + + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

200

+ successful operation + + +

400

+ Invalid ID supplied + + +

404

+ Order not found + + +
+
+ +
+
+ Up +
delete /store/order/{orderId}
+
Delete purchase order by ID (deleteOrder)
+ +
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
+ + +

Path parameters

+
+
orderId (required)
+ +
Path Parameter — ID of the order that needs to be deleted
+
+ + + + + + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

400

+ Invalid ID supplied + + +

404

+ Order not found + + +
+
+ +
+
+ Up +
post /user
+
Create user (createUser)
+ +
This can only be done by the logged in user.
+ + + + + + +

Request body

+
+
body (optional)
+ +
Body Parameter — Created user object
+
+ + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

0

+ successful operation + + +
+
+ +
+
+ Up +
post /user/createWithArray
+
Creates list of users with given input array (createUsersWithArrayInput)
+ +
+ + + + + + +

Request body

+
+
body (optional)
+ +
Body Parameter — List of user object
+
+ + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

0

+ successful operation + + +
+
+ +
+
+ Up +
post /user/createWithList
+
Creates list of users with given input array (createUsersWithListInput)
+ +
+ + + + + + +

Request body

+
+
body (optional)
+ +
Body Parameter — List of user object
+
+ + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

0

+ successful operation + + +
+
+ +
+
+ Up +
get /user/login
+
Logs user into the system (loginUser)
+ +
+ + + + + + + + + + +

Query parameters

+
+
username (optional)
+ +
Query Parameter — The user name for login
password (optional)
+ +
Query Parameter — The password for login in clear text
+
+ + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

200

+ successful operation + + +

400

+ Invalid username/password supplied + + +
+
+ +
+
+ Up +
get /user/logout
+
Logs out current logged in user session (logoutUser)
+ +
+ + + + + + + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

0

+ successful operation + + +
+
+ +
+
+ Up +
get /user/{username}
+
Get user by user name (getUserByName)
+ +
+ + +

Path parameters

+
+
username (required)
+ +
Path Parameter — The name that needs to be fetched. Use user1 for testing.
+
+ + + + + + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

200

+ successful operation + +

Example data

+
Content-Type: application/json
+
{id=1, username=johnp, firstName=John, lastName=Public, email=johnp@swagger.io, password=-secret-, phone=0123456789, userStatus=0}
+ + +

400

+ Invalid username supplied + + +

404

+ User not found + + +
+
+ +
+
+ Up +
put /user/{username}
+
Updated user (updateUser)
+ +
This can only be done by the logged in user.
+ + +

Path parameters

+
+
username (required)
+ +
Path Parameter — name that need to be deleted
+
+ + + + + +

Request body

+
+
body (optional)
+ +
Body Parameter — Updated user object
+
+ + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

400

+ Invalid user supplied + + +

404

+ User not found + + +
+
+ +
+
+ Up +
delete /user/{username}
+
Delete user (deleteUser)
+ +
This can only be done by the logged in user.
+ + +

Path parameters

+
+
username (required)
+ +
Path Parameter — The name that needs to be deleted
+
+ + + + + + + + + + + + + + + + + +

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. +
    + +
  • application/json
  • + +
  • application/xml
  • + +
+ + +

Responses

+ +

400

+ Invalid username supplied + + +

404

+ User not found + + +
+
+ + + + + + +

Models

+ [ Jump to Methods ] + +

Table of Contents

+
    + + +
  1. User
  2. + + + +
  3. Category
  4. + + + +
  5. Pet
  6. + + + +
  7. Tag
  8. + + + +
  9. Order
  10. + + +
+ + + +
+

User Up

+
+
id
Long
+ +
username
String
+ +
firstName
String
+ +
lastName
String
+ +
email
String
+ +
password
String
+ +
phone
String
+ +
userStatus
Integer User Status
+ + +
+
+ + + +
+

Category Up

+
+
id
Long
+ +
name
String
+ + +
+
+ + + +
+

Pet Up

+
+
id
Long
+ +
category
Category
+ +
name
String
+ +
photoUrls
array[String]
+ +
tags
array[Tag]
+ +
status
String pet status in the store
+ +
Enum:
+
available
pending
sold
+ + +
+
+ + + +
+

Tag Up

+
+
id
Long
+ +
name
String
+ + +
+
+ + + +
+

Order Up

+
+
id
Long
+ +
petId
Long
+ +
quantity
Integer
+ +
shipDate
Date
+ +
status
String Order Status
+ +
Enum:
+
placed
approved
delivered
+ +
complete
Boolean
+ + +
+
+ + - \ No newline at end of file + diff --git a/samples/server/petstore/flaskConnexion/README.md b/samples/server/petstore/flaskConnexion/README.md new file mode 100644 index 00000000000..d85f471ba40 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/README.md @@ -0,0 +1,27 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled JAX-RS server. + +This example uses the [connexion](https://github.com/zalando/connexion) library on top of Flask. + +To run the server, please execute the following: + +``` +python3 app.py +``` + +and open your browser to here: + +``` +http://localhost:8080/ui +``` + +Your swagger definition lives here: + +``` +http://localhost:8080/swagger.json +``` + diff --git a/samples/server/petstore/flaskConnexion/app.py b/samples/server/petstore/flaskConnexion/app.py new file mode 100644 index 00000000000..ae021b58df9 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/app.py @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 + +import connexion + +if __name__ == '__main__': + app = connexion.App(__name__, 8080, + specification_dir='./swagger/') + app.add_api('swagger.yaml', arguments={'title': 'This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters'}) + app.run() diff --git a/samples/server/petstore/flaskConnexion/controllers/default_controller.py b/samples/server/petstore/flaskConnexion/controllers/default_controller.py new file mode 100644 index 00000000000..8d771afed91 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/controllers/default_controller.py @@ -0,0 +1,60 @@ + +def create_user(body) -> str: + return 'do some magic!' + +def create_users_with_array_input(body) -> str: + return 'do some magic!' + +def create_users_with_list_input(body) -> str: + return 'do some magic!' + +def login_user(username, password) -> str: + return 'do some magic!' + +def logout_user() -> str: + return 'do some magic!' + +def get_user_by_name(username) -> str: + return 'do some magic!' + +def update_user(username, body) -> str: + return 'do some magic!' + +def delete_user(username) -> str: + return 'do some magic!' + +def update_pet(body) -> str: + return 'do some magic!' + +def add_pet(body) -> str: + return 'do some magic!' + +def find_pets_by_status(status) -> str: + return 'do some magic!' + +def find_pets_by_tags(tags) -> str: + return 'do some magic!' + +def get_pet_by_id(petId) -> str: + return 'do some magic!' + +def update_pet_with_form(petId, name, status) -> str: + return 'do some magic!' + +def delete_pet(petId, apiKey) -> str: + return 'do some magic!' + +def upload_file(petId, additionalMetadata, file) -> str: + return 'do some magic!' + +def get_inventory() -> str: + return 'do some magic!' + +def place_order(body) -> str: + return 'do some magic!' + +def get_order_by_id(orderId) -> str: + return 'do some magic!' + +def delete_order(orderId) -> str: + return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml new file mode 100644 index 00000000000..047d1652a87 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml @@ -0,0 +1,727 @@ +--- +swagger: "2.0" +info: + description: "This is a sample server Petstore server. You can find out more about\ + \ Swagger at http://swagger.io or on irc.freenode.net,\ + \ #swagger. For this sample, you can use the api key \"special-key\" to test\ + \ the authorization filters" + version: "1.0.0" + title: "Swagger Petstore" + termsOfService: "http://swagger.io/terms/" + contact: + email: "apiteam@swagger.io" + license: + name: "Apache 2.0" + url: "http://www.apache.org/licenses/LICENSE-2.0.html" +host: "petstore.swagger.io" +basePath: "/v2" +schemes: +- "http" +paths: + /pet: + post: + tags: + - "pet" + summary: "Add a new pet to the store" + description: "" + operationId: "controllers.default_controller.add_pet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: false + schema: + $ref: "#/definitions/Pet" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-operationId: "add_pet" + x-tags: + - tag: "pet" + put: + tags: + - "pet" + summary: "Update an existing pet" + description: "" + operationId: "controllers.default_controller.update_pet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: false + schema: + $ref: "#/definitions/Pet" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + 405: + description: "Validation exception" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-operationId: "update_pet" + x-tags: + - tag: "pet" + /pet/findByStatus: + get: + tags: + - "pet" + summary: "Finds Pets by status" + description: "Multiple status values can be provided with comma seperated strings" + operationId: "controllers.default_controller.find_pets_by_status" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "status" + in: "query" + description: "Status values that need to be considered for filter" + required: false + type: "array" + items: + type: "string" + collectionFormat: "multi" + default: "available" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid status value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-operationId: "find_pets_by_status" + x-tags: + - tag: "pet" + /pet/findByTags: + get: + tags: + - "pet" + summary: "Finds Pets by tags" + description: "Muliple tags can be provided with comma seperated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: "controllers.default_controller.find_pets_by_tags" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "tags" + in: "query" + description: "Tags to filter by" + required: false + type: "array" + items: + type: "string" + collectionFormat: "multi" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid tag value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-operationId: "find_pets_by_tags" + x-tags: + - tag: "pet" + /pet/{petId}: + get: + tags: + - "pet" + summary: "Find pet by ID" + description: "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate\ + \ API error conditions" + operationId: "controllers.default_controller.get_pet_by_id" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "integer" + format: "int64" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Pet" + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + security: + - api_key: [] + - petstore_auth: + - "write:pets" + - "read:pets" + x-operationId: "get_pet_by_id" + x-tags: + - tag: "pet" + post: + tags: + - "pet" + summary: "Updates a pet in the store with form data" + description: "" + operationId: "controllers.default_controller.update_pet_with_form" + consumes: + - "application/x-www-form-urlencoded" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be updated" + required: true + type: "string" + - name: "name" + in: "formData" + description: "Updated name of the pet" + required: false + type: "string" + - name: "status" + in: "formData" + description: "Updated status of the pet" + required: false + type: "string" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-operationId: "update_pet_with_form" + x-tags: + - tag: "pet" + delete: + tags: + - "pet" + summary: "Deletes a pet" + description: "" + operationId: "controllers.default_controller.delete_pet" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "api_key" + in: "header" + description: "" + required: false + type: "string" + - name: "petId" + in: "path" + description: "Pet id to delete" + required: true + type: "integer" + format: "int64" + responses: + 400: + description: "Invalid pet value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-operationId: "delete_pet" + x-tags: + - tag: "pet" + /pet/{petId}/uploadImage: + post: + tags: + - "pet" + summary: "uploads an image" + description: "" + operationId: "controllers.default_controller.upload_file" + consumes: + - "multipart/form-data" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to update" + required: true + type: "integer" + format: "int64" + - name: "additionalMetadata" + in: "formData" + description: "Additional data to pass to server" + required: false + type: "string" + - name: "file" + in: "formData" + description: "file to upload" + required: false + type: "file" + responses: + default: + description: "successful operation" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-operationId: "upload_file" + x-tags: + - tag: "pet" + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "controllers.default_controller.get_inventory" + produces: + - "application/json" + - "application/xml" + parameters: [] + responses: + 200: + description: "successful operation" + schema: + type: "object" + additionalProperties: + type: "integer" + format: "int32" + security: + - api_key: [] + x-operationId: "get_inventory" + x-tags: + - tag: "store" + /store/order: + post: + tags: + - "store" + summary: "Place an order for a pet" + description: "" + operationId: "controllers.default_controller.place_order" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "order placed for purchasing the pet" + required: false + schema: + $ref: "#/definitions/Order" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid Order" + x-operationId: "place_order" + x-tags: + - tag: "store" + /store/order/{orderId}: + get: + tags: + - "store" + summary: "Find purchase order by ID" + description: "For valid response try integer IDs with value <= 5 or > 10. Other\ + \ values will generated exceptions" + operationId: "controllers.default_controller.get_order_by_id" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "orderId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "string" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + x-operationId: "get_order_by_id" + x-tags: + - tag: "store" + delete: + tags: + - "store" + summary: "Delete purchase order by ID" + description: "For valid response try integer IDs with value < 1000. Anything\ + \ above 1000 or nonintegers will generate API errors" + operationId: "controllers.default_controller.delete_order" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "orderId" + in: "path" + description: "ID of the order that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + x-operationId: "delete_order" + x-tags: + - tag: "store" + /user: + post: + tags: + - "user" + summary: "Create user" + description: "This can only be done by the logged in user." + operationId: "controllers.default_controller.create_user" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Created user object" + required: false + schema: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-operationId: "create_user" + x-tags: + - tag: "user" + /user/createWithArray: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "controllers.default_controller.create_users_with_array_input" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: false + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-operationId: "create_users_with_array_input" + x-tags: + - tag: "user" + /user/createWithList: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "controllers.default_controller.create_users_with_list_input" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: false + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-operationId: "create_users_with_list_input" + x-tags: + - tag: "user" + /user/login: + get: + tags: + - "user" + summary: "Logs user into the system" + description: "" + operationId: "controllers.default_controller.login_user" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "query" + description: "The user name for login" + required: false + type: "string" + - name: "password" + in: "query" + description: "The password for login in clear text" + required: false + type: "string" + responses: + 200: + description: "successful operation" + schema: + type: "string" + 400: + description: "Invalid username/password supplied" + x-operationId: "login_user" + x-tags: + - tag: "user" + /user/logout: + get: + tags: + - "user" + summary: "Logs out current logged in user session" + description: "" + operationId: "controllers.default_controller.logout_user" + produces: + - "application/json" + - "application/xml" + parameters: [] + responses: + default: + description: "successful operation" + x-operationId: "logout_user" + x-tags: + - tag: "user" + /user/{username}: + get: + tags: + - "user" + summary: "Get user by user name" + description: "" + operationId: "controllers.default_controller.get_user_by_name" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be fetched. Use user1 for testing. " + required: true + type: "string" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/User" + examples: + application/json: + id: 1 + username: "johnp" + firstName: "John" + lastName: "Public" + email: "johnp@swagger.io" + password: "-secret-" + phone: "0123456789" + userStatus: 0 + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + x-operationId: "get_user_by_name" + x-tags: + - tag: "user" + put: + tags: + - "user" + summary: "Updated user" + description: "This can only be done by the logged in user." + operationId: "controllers.default_controller.update_user" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "name that need to be deleted" + required: true + type: "string" + - in: "body" + name: "body" + description: "Updated user object" + required: false + schema: + $ref: "#/definitions/User" + responses: + 400: + description: "Invalid user supplied" + 404: + description: "User not found" + x-operationId: "update_user" + x-tags: + - tag: "user" + delete: + tags: + - "user" + summary: "Delete user" + description: "This can only be done by the logged in user." + operationId: "controllers.default_controller.delete_user" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + x-operationId: "delete_user" + x-tags: + - tag: "user" +securityDefinitions: + api_key: + type: "apiKey" + name: "api_key" + in: "header" + petstore_auth: + type: "oauth2" + authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" + flow: "implicit" + scopes: + write:pets: "modify pets in your account" + read:pets: "read your pets" +definitions: + User: + properties: + id: + type: "integer" + format: "int64" + username: + type: "string" + firstName: + type: "string" + lastName: + type: "string" + email: + type: "string" + password: + type: "string" + phone: + type: "string" + userStatus: + type: "integer" + format: "int32" + description: "User Status" + xml: + name: "User" + Category: + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Category" + Pet: + required: + - "name" + - "photoUrls" + properties: + id: + type: "integer" + format: "int64" + category: + $ref: "#/definitions/Category" + name: + type: "string" + example: "doggie" + photoUrls: + type: "array" + xml: + name: "photoUrl" + wrapped: true + items: + type: "string" + tags: + type: "array" + xml: + name: "tag" + wrapped: true + items: + $ref: "#/definitions/Tag" + status: + type: "string" + description: "pet status in the store" + enum: + - "available" + - "pending" + - "sold" + xml: + name: "Pet" + Tag: + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Tag" + Order: + properties: + id: + type: "integer" + format: "int64" + petId: + type: "integer" + format: "int64" + quantity: + type: "integer" + format: "int32" + shipDate: + type: "string" + format: "date-time" + status: + type: "string" + description: "Order Status" + enum: + - "placed" + - "approved" + - "delivered" + complete: + type: "boolean" + xml: + name: "Order" diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java index ad8ae3aff94..765ae959367 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java index 3c45b7e282f..9559bd394aa 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class ApiOriginFilter implements javax.servlet.Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java index 1bddb4087ae..2460847cf6a 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java index 37f7328aaf7..58dc8bcd1ad 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java index 260523279cd..e8db743f900 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java @@ -22,13 +22,12 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.*; -@Path("/v2/pet") +@Path("/pet") -@io.swagger.annotations.Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@io.swagger.annotations.Api(description = "the pet API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class PetApi { - private final PetApiService delegate = PetApiServiceFactory.getPetApi(); @PUT @@ -40,7 +39,7 @@ public class PetApi { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @@ -48,7 +47,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) - public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { return delegate.updatePet(body); } @@ -61,11 +60,11 @@ public class PetApi { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) - public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { return delegate.addPet(body); } @@ -78,7 +77,7 @@ public class PetApi { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @@ -97,7 +96,7 @@ public class PetApi { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @@ -113,7 +112,7 @@ public class PetApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { @io.swagger.annotations.Authorization(value = "api_key") - }) + }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), @@ -121,7 +120,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) - public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("petId") Long petId) + public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("petId") Long petId) throws NotFoundException { return delegate.getPetById(petId); } @@ -134,13 +133,13 @@ public class PetApi { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) - public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathParam("petId") String petId, - @ApiParam(value = "Updated name of the pet" )@FormParam("name") String name, - @ApiParam(value = "Updated status of the pet" )@FormParam("status") String status) + public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") String petId, + @ApiParam(value = "Updated name of the pet")@FormParam("name") String name, + @ApiParam(value = "Updated status of the pet")@FormParam("status") String status) throws NotFoundException { return delegate.updatePetWithForm(petId,name,status); } @@ -153,12 +152,12 @@ public class PetApi { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) - public Response deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathParam("petId") Long petId, - @ApiParam(value = "" )@HeaderParam("api_key") String apiKey) + public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId, + @ApiParam(value = "" )@HeaderParam("api_key") String apiKey) throws NotFoundException { return delegate.deletePet(petId,apiKey); } @@ -171,12 +170,12 @@ public class PetApi { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) - }) + }, tags={ "pet" }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathParam("petId") Long petId, - @ApiParam(value = "Additional data to pass to server" )@FormParam("additionalMetadata") String additionalMetadata, + public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId, + @ApiParam(value = "Additional data to pass to server")@FormParam("additionalMetadata") String additionalMetadata, @FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) throws NotFoundException { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java index 8171555b0d0..b7e1ead74cc 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public abstract class PetApiService { public abstract Response updatePet(Pet body) diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java index 63fac7c2b34..7c9b500470a 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java @@ -22,13 +22,12 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.*; -@Path("/v2/store") +@Path("/store") -@io.swagger.annotations.Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@io.swagger.annotations.Api(description = "the store API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class StoreApi { - private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); @GET @@ -37,7 +36,7 @@ public class StoreApi { @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @io.swagger.annotations.Authorization(value = "api_key") - }) + }, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) @@ -49,13 +48,13 @@ public class StoreApi { @Path("/order") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) throws NotFoundException { return delegate.placeOrder(body); } @@ -63,7 +62,7 @@ public class StoreApi { @Path("/order/{orderId}") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), @@ -71,7 +70,7 @@ public class StoreApi { @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("orderId") String orderId) + public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") String orderId) throws NotFoundException { return delegate.getOrderById(orderId); } @@ -79,13 +78,13 @@ public class StoreApi { @Path("/order/{orderId}") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store" }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Void.class) }) - public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathParam("orderId") String orderId) + public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId) throws NotFoundException { return delegate.deleteOrder(orderId); } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java index dc8274ce739..721117cf3b3 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public abstract class StoreApiService { public abstract Response getInventory() diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java index cade9a3b2f1..718fbbe9a9a 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java @@ -22,24 +22,23 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.*; -@Path("/v2/user") +@Path("/user") -@io.swagger.annotations.Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@io.swagger.annotations.Api(description = "the user API") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class UserApi { - private final UserApiService delegate = UserApiServiceFactory.getUserApi(); @POST @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUser(@ApiParam(value = "Created user object" ) User body) + public Response createUser(@ApiParam(value = "Created user object" ) User body) throws NotFoundException { return delegate.createUser(body); } @@ -47,11 +46,11 @@ public class UserApi { @Path("/createWithArray") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { return delegate.createUsersWithArrayInput(body); } @@ -59,11 +58,11 @@ public class UserApi { @Path("/createWithList") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { return delegate.createUsersWithListInput(body); } @@ -71,7 +70,7 @@ public class UserApi { @Path("/login") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), @@ -86,7 +85,7 @@ public class UserApi { @Path("/logout") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @@ -98,7 +97,7 @@ public class UserApi { @Path("/{username}") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), @@ -106,7 +105,7 @@ public class UserApi { @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) - public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true ) @PathParam("username") String username) + public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathParam("username") String username) throws NotFoundException { return delegate.getUserByName(username); } @@ -114,14 +113,14 @@ public class UserApi { @Path("/{username}") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) }) - public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathParam("username") String username, - @ApiParam(value = "Updated user object" ) User body) + public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username, + @ApiParam(value = "Updated user object" ) User body) throws NotFoundException { return delegate.updateUser(username,body); } @@ -129,13 +128,13 @@ public class UserApi { @Path("/{username}") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user" }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) }) - public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathParam("username") String username) + public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username) throws NotFoundException { return delegate.deleteUser(username); } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java index 175aa32757a..aebc957e25c 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public abstract class UserApiService { public abstract Response createUser(User body) diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java index 9aed596a768..0acf355555c 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java index 8a5c22a38ac..07b422a67f5 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class Order { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java index f3e1cfa17f2..af735dcc3b2 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java index fe723eea4d8..1102fa408bf 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java index ea890100a74..d170b2c7df0 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-26T17:58:55.634+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class User { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java index c3a7cbf8bf7..1096ef30806 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java @@ -3,7 +3,7 @@ package io.swagger.api.factories; import io.swagger.api.PetApiService; import io.swagger.api.impl.PetApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class PetApiServiceFactory { private final static PetApiService service = new PetApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java index 9eb7af458dd..2fb1234323a 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java @@ -3,7 +3,7 @@ package io.swagger.api.factories; import io.swagger.api.StoreApiService; import io.swagger.api.impl.StoreApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class StoreApiServiceFactory { private final static StoreApiService service = new StoreApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java index 2f381c6b459..4c654779ed9 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java @@ -3,7 +3,7 @@ package io.swagger.api.factories; import io.swagger.api.UserApiService; import io.swagger.api.impl.UserApiServiceImpl; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class UserApiServiceFactory { private final static UserApiService service = new UserApiServiceImpl(); diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index c7ee88aaf63..5137ffe7912 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class PetApiServiceImpl extends PetApiService { @Override diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 7dbf5e75dd2..4d9011b4943 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class StoreApiServiceImpl extends StoreApiService { @Override diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index cdbc9afed19..991849edc17 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T22:18:00.553-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-11-05T22:31:25.130-08:00") public class UserApiServiceImpl extends UserApiService { @Override diff --git a/samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml b/samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml index 80df1cd180d..bde33eae91a 100644 --- a/samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml +++ b/samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml @@ -34,14 +34,14 @@ swagger.api.basepath - http://localhost:8080 + http://petstore.swagger.io/v2 2 jersey - /* + /v2/* ApiOriginFilter diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiClient.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiClient.java deleted file mode 100644 index 9af0c10b543..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiClient.java +++ /dev/null @@ -1,553 +0,0 @@ -package io.swagger.client; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.LoggingFilter; -import com.sun.jersey.api.client.WebResource.Builder; - -import com.sun.jersey.multipart.FormDataMultiPart; -import com.sun.jersey.multipart.file.FileDataBodyPart; - -import javax.ws.rs.core.Response.Status.Family; -import javax.ws.rs.core.MediaType; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Map.Entry; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; -import java.util.Date; -import java.util.TimeZone; - -import java.net.URLEncoder; - -import java.io.IOException; -import java.io.File; -import java.io.UnsupportedEncodingException; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.text.ParseException; - -import io.swagger.client.auth.Authentication; -import io.swagger.client.auth.HttpBasicAuth; -import io.swagger.client.auth.ApiKeyAuth; -import io.swagger.client.auth.OAuth; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class ApiClient { - private Map hostMap = new HashMap(); - private Map defaultHeaderMap = new HashMap(); - private boolean debugging = false; - private String basePath = "http://petstore.swagger.io/v2"; - private JSON json = new JSON(); - - private Map authentications; - - private DateFormat dateFormat; - - public ApiClient() { - // Use ISO 8601 format for date and datetime. - // See https://en.wikipedia.org/wiki/ISO_8601 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - - // Use UTC as the default time zone. - this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - - // Set default User-Agent. - setUserAgent("Java-Swagger"); - - // Setup authentications (key: authentication name, value: authentication). - authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - authentications.put("petstore_auth", new OAuth()); - // Prevent the authentications from being modified. - authentications = Collections.unmodifiableMap(authentications); - } - - public String getBasePath() { - return basePath; - } - - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - - /** - * Get authentications (key: authentication name, value: authentication). - */ - public Map getAuthentications() { - return authentications; - } - - /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ - public Authentication getAuthentication(String authName) { - return authentications.get(authName); - } - - /** - * Helper method to set username for the first HTTP basic authentication. - */ - public void setUsername(String username) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set password for the first HTTP basic authentication. - */ - public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** - * Helper method to set API key value for the first API key authentication. - */ - public void setApiKey(String apiKey) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Helper method to set API key prefix for the first API key authentication. - */ - public void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : authentications.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** - * Set the User-Agent header's value (by adding to the default header map). - */ - public ApiClient setUserAgent(String userAgent) { - addDefaultHeader("User-Agent", userAgent); - return this; - } - - /** - * Add a default header. - * - * @param key The header's key - * @param value The header's value - */ - public ApiClient addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - return this; - } - - /** - * Check that whether debugging is enabled for this API client. - */ - public boolean isDebugging() { - return debugging; - } - - /** - * Enable/disable debugging for this API client. - * - * @param debugging To enable (true) or disable (false) debugging - */ - public ApiClient setDebugging(boolean debugging) { - this.debugging = debugging; - return this; - } - - /** - * Get the date format used to parse/format date parameters. - */ - public DateFormat getDateFormat() { - return dateFormat; - } - - /** - * Set the date format used to parse/format date parameters. - */ - public ApiClient getDateFormat(DateFormat dateFormat) { - this.dateFormat = dateFormat; - return this; - } - - /** - * Parse the given string into Date object. - */ - public Date parseDate(String str) { - try { - return dateFormat.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } - - /** - * Format the given parameter object into string. - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDate((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for(Object o : (Collection)param) { - if(b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /* - Format to {@code Pair} objects. - */ - public List parameterToPairs(String collectionFormat, String name, Object value){ - List params = new ArrayList(); - - // preconditions - if (name == null || name.isEmpty() || value == null) return params; - - Collection valueCollection = null; - if (value instanceof Collection) { - valueCollection = (Collection) value; - } else { - params.add(new Pair(name, parameterToString(value))); - return params; - } - - if (valueCollection.isEmpty()){ - return params; - } - - // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - - // create the params based on the collection format - if (collectionFormat.equals("multi")) { - for (Object item : valueCollection) { - params.add(new Pair(name, parameterToString(item))); - } - - return params; - } - - String delimiter = ","; - - if (collectionFormat.equals("csv")) { - delimiter = ","; - } else if (collectionFormat.equals("ssv")) { - delimiter = " "; - } else if (collectionFormat.equals("tsv")) { - delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { - delimiter = "|"; - } - - StringBuilder sb = new StringBuilder() ; - for (Object item : valueCollection) { - sb.append(delimiter); - sb.append(parameterToString(item)); - } - - params.add(new Pair(name, sb.substring(1))); - - return params; - } - - /** - * Select the Accept header's value from the given accepts array: - * if JSON exists in the given array, use it; - * otherwise use all of them (joining into a string) - * - * @param accepts The accepts array to select from - * @return The Accept header to use. If the given array is empty, - * null will be returned (not to set the Accept header explicitly). - */ - public String selectHeaderAccept(String[] accepts) { - if (accepts.length == 0) return null; - if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; - return StringUtil.join(accepts, ","); - } - - /** - * Select the Content-Type header's value from the given array: - * if JSON exists in the given array, use it; - * otherwise use the first one of the array. - * - * @param contentTypes The Content-Type array to select from - * @return The Content-Type header to use. If the given array is empty, - * JSON will be used. - */ - public String selectHeaderContentType(String[] contentTypes) { - if (contentTypes.length == 0) return "application/json"; - if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; - return contentTypes[0]; - } - - /** - * Escape the given string to be used as URL query value. - */ - public String escapeString(String str) { - try { - return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } catch (UnsupportedEncodingException e) { - return str; - } - } - - /** - * Serialize the given Java object into string according the given - * Content-Type (only JSON is supported for now). - */ - public String serialize(Object obj, String contentType) throws ApiException { - if (contentType.startsWith("application/json")) { - return json.serialize(obj); - } else { - throw new ApiException(400, "can not serialize object into Content-Type: " + contentType); - } - } - - /** - * Deserialize response body to Java object according to the Content-Type. - */ - public T deserialize(ClientResponse response, TypeRef returnType) throws ApiException { - String contentType = null; - List contentTypes = response.getHeaders().get("Content-Type"); - if (contentTypes != null && !contentTypes.isEmpty()) - contentType = contentTypes.get(0); - if (contentType == null) - throw new ApiException(500, "missing Content-Type in response"); - - String body; - if (response.hasEntity()) - body = (String) response.getEntity(String.class); - else - body = ""; - - if (contentType.startsWith("application/json")) { - return json.deserialize(body, returnType); - } else { - throw new ApiException(500, "can not deserialize Content-Type: " + contentType); - } - } - - /** - * Invoke API by sending HTTP request with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param formParams The form parameters - * @param accept The request's Accept header - * @param contentType The request's Content-Type header - * @param authNames The authentications to apply - * @param returnType The return type into which to deserialize the response - * @return The response body in type of string - */ - public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { - updateParamsForAuth(authNames, queryParams, headerParams); - - Client client = getClient(); - - StringBuilder b = new StringBuilder(); - b.append("?"); - if (queryParams != null){ - for (Pair queryParam : queryParams){ - if (!queryParam.getName().isEmpty()) { - b.append(escapeString(queryParam.getName())); - b.append("="); - b.append(escapeString(queryParam.getValue())); - b.append("&"); - } - } - } - - String querystring = b.substring(0, b.length() - 1); - - Builder builder; - if (accept == null) - builder = client.resource(basePath + path + querystring).getRequestBuilder(); - else - builder = client.resource(basePath + path + querystring).accept(accept); - - for (String key : headerParams.keySet()) { - builder = builder.header(key, headerParams.get(key)); - } - for (String key : defaultHeaderMap.keySet()) { - if (!headerParams.containsKey(key)) { - builder = builder.header(key, defaultHeaderMap.get(key)); - } - } - - String encodedFormParams = null; - if (contentType.startsWith("multipart/form-data")) { - FormDataMultiPart mp = new FormDataMultiPart(); - for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof File) { - File file = (File) param.getValue(); - mp.field(param.getKey(), file.getName()); - mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE)); - } else { - mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE); - } - } - body = mp; - } else if (contentType.startsWith("application/x-www-form-urlencoded")) { - encodedFormParams = this.getXWWWFormUrlencodedParams(formParams); - } - - ClientResponse response = null; - - if ("GET".equals(method)) { - response = (ClientResponse) builder.get(ClientResponse.class); - } else if ("POST".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).post(ClientResponse.class, encodedFormParams); - } else if (body == null) { - response = builder.post(ClientResponse.class, null); - } else if (body instanceof FormDataMultiPart) { - response = builder.type(contentType).post(ClientResponse.class, body); - } else { - response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType)); - } - } else if ("PUT".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); - } else if(body == null) { - response = builder.put(ClientResponse.class, serialize(body, contentType)); - } else { - response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType)); - } - } else if ("DELETE".equals(method)) { - if (encodedFormParams != null) { - response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams); - } else if(body == null) { - response = builder.delete(ClientResponse.class); - } else { - response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType)); - } - } else { - throw new ApiException(500, "unknown method type " + method); - } - - if (response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { - return null; - } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { - if (returnType == null) - return null; - else - return deserialize(response, returnType); - } else { - String message = "error"; - String respBody = null; - if (response.hasEntity()) { - try { - respBody = String.valueOf(response.getEntity(String.class)); - message = respBody; - } catch (RuntimeException e) { - // e.printStackTrace(); - } - } - throw new ApiException( - response.getStatusInfo().getStatusCode(), - message, - response.getHeaders(), - respBody); - } - } - - /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ - private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { - for (String authName : authNames) { - Authentication auth = authentications.get(authName); - if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); - auth.applyToParams(queryParams, headerParams); - } - } - - /** - * Encode the given form parameters as request body. - */ - private String getXWWWFormUrlencodedParams(Map formParams) { - StringBuilder formParamBuilder = new StringBuilder(); - - for (Entry param : formParams.entrySet()) { - String keyStr = param.getKey(); - String valueStr = parameterToString(param.getValue()); - try { - formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8")) - .append("=") - .append(URLEncoder.encode(valueStr, "utf8")); - formParamBuilder.append("&"); - } catch (UnsupportedEncodingException e) { - // move on to next - } - } - - String encodedFormParams = formParamBuilder.toString(); - if (encodedFormParams.endsWith("&")) { - encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1); - } - - return encodedFormParams; - } - - /** - * Get an existing client or create a new client to handle HTTP request. - */ - private Client getClient() { - if(!hostMap.containsKey(basePath)) { - Client client = Client.create(); - if (debugging) - client.addFilter(new LoggingFilter()); - hostMap.put(basePath, client); - } - return hostMap.get(basePath); - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiException.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiException.java deleted file mode 100644 index 605f8c3769d..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/ApiException.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.swagger.client; - -import java.util.Map; -import java.util.List; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class ApiException extends Exception { - private int code = 0; - private String message = null; - private Map> responseHeaders = null; - private String responseBody = null; - - public ApiException() {} - - public ApiException(int code, String message) { - this.code = code; - this.message = message; - } - - public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this.code = code; - this.message = message; - this.responseHeaders = responseHeaders; - this.responseBody = responseBody; - } - - public int getCode() { - return code; - } - - public String getMessage() { - return message; - } - - /** - * Get the HTTP response headers. - */ - public Map> getResponseHeaders() { - return responseHeaders; - } - - /** - * Get the HTTP response body. - */ - public String getResponseBody() { - return responseBody; - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Configuration.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Configuration.java deleted file mode 100644 index 524006fd7bd..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Configuration.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.swagger.client; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class Configuration { - private static ApiClient defaultApiClient = new ApiClient(); - - /** - * Get the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static ApiClient getDefaultApiClient() { - return defaultApiClient; - } - - /** - * Set the default API client, which would be used when creating API - * instances without providing an API client. - */ - public static void setDefaultApiClient(ApiClient apiClient) { - defaultApiClient = apiClient; - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/JSON.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/JSON.java deleted file mode 100644 index 3514e41778e..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/JSON.java +++ /dev/null @@ -1,52 +0,0 @@ -package io.swagger.client; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.datatype.joda.*; - -import java.io.IOException; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class JSON { - private ObjectMapper mapper; - - public JSON() { - mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.registerModule(new JodaModule()); - } - - /** - * Serialize the given Java object into JSON string. - */ - public String serialize(Object obj) throws ApiException { - try { - if (obj != null) - return mapper.writeValueAsString(obj); - else - return null; - } catch (Exception e) { - throw new ApiException(400, e.getMessage()); - } - } - - /** - * Deserialize the given JSON string to Java object. - * - * @param body The JSON string - * @param returnType The type to deserialize inot - * @return The deserialized Java object - */ - public T deserialize(String body, TypeRef returnType) throws ApiException { - JavaType javaType = mapper.constructType(returnType.getType()); - try { - return mapper.readValue(body, javaType); - } catch (IOException e) { - if (returnType.getType().equals(String.class)) - return (T) body; - else - throw new ApiException(500, e.getMessage(), null, body); - } - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Pair.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Pair.java deleted file mode 100644 index e7dd3350637..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/Pair.java +++ /dev/null @@ -1,39 +0,0 @@ -package io.swagger.client; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class Pair { - private String name = ""; - private String value = ""; - - public Pair (String name, String value) { - setName(name); - setValue(value); - } - - private void setName(String name) { - if (!isValidString(name)) return; - - this.name = name; - } - - private void setValue(String value) { - if (!isValidString(value)) return; - - this.value = value; - } - - public String getName() { - return this.name; - } - - public String getValue() { - return this.value; - } - - private boolean isValidString(String arg) { - if (arg == null) return false; - if (arg.trim().isEmpty()) return false; - - return true; - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/TypeRef.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/TypeRef.java deleted file mode 100644 index 15eb3ea05ba..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/TypeRef.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.swagger.client; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class TypeRef { - private final Type type; - - public TypeRef() { - this.type = getGenericType(getClass()); - } - - private static Type getGenericType(Class klass) { - Type superclass = klass.getGenericSuperclass(); - if (superclass instanceof Class) { - throw new RuntimeException("No type parameter provided"); - } - ParameterizedType parameterized = (ParameterizedType) superclass; - return parameterized.getActualTypeArguments()[0]; - } - - public Type getType() { - return type; - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/PetApi.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/PetApi.java deleted file mode 100644 index 5b71f7c199c..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/PetApi.java +++ /dev/null @@ -1,407 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.TypeRef; - -import io.swagger.client.model.*; - -import java.util.*; - -import io.swagger.client.model.Pet; -import java.io.File; - -import java.io.File; -import java.util.Map; -import java.util.HashMap; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - * @return void - */ - public void updatePet (Pet body) throws ApiException { - Object postBody = body; - - - // create path and map variables - String path = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - "application/json", "application/xml" - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { "petstore_auth" }; - - apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - * @return void - */ - public void addPet (Pet body) throws ApiException { - Object postBody = body; - - - // create path and map variables - String path = "/pet".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - "application/json", "application/xml" - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { "petstore_auth" }; - - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - - /** - * 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 - */ - public List findPetsByStatus (List status) throws ApiException { - Object postBody = null; - - - // create path and map variables - String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { "petstore_auth" }; - - TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - } - - /** - * 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 - */ - public List findPetsByTags (List tags) throws ApiException { - Object postBody = null; - - - // create path and map variables - String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { "petstore_auth" }; - - TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - } - - /** - * 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 - */ - public Pet getPetById (Long petId) throws ApiException { - Object postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); - } - - - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { "api_key", "petstore_auth" }; - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - } - - /** - * 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 - */ - public void updatePetWithForm (String petId, String name, String status) throws ApiException { - Object postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); - } - - - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - if (name != null) - formParams.put("name", name); - if (status != null) - formParams.put("status", status); - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - "application/x-www-form-urlencoded" - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { "petstore_auth" }; - - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - * @return void - */ - public void deletePet (Long petId, String apiKey) throws ApiException { - Object postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); - } - - - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - if (apiKey != null) - headerParams.put("api_key", apiClient.parameterToString(apiKey)); - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { "petstore_auth" }; - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - - /** - * 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 - */ - public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { - Object postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); - } - - - // create path and map variables - String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - if (additionalMetadata != null) - formParams.put("additionalMetadata", additionalMetadata); - if (file != null) - formParams.put("file", file); - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - "multipart/form-data" - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { "petstore_auth" }; - - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/StoreApi.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/StoreApi.java deleted file mode 100644 index 7c0430b5f71..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/StoreApi.java +++ /dev/null @@ -1,215 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.TypeRef; - -import io.swagger.client.model.*; - -import java.util.*; - -import java.util.Map; -import io.swagger.client.model.Order; - -import java.io.File; -import java.util.Map; -import java.util.HashMap; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map - */ - public Map getInventory () throws ApiException { - Object postBody = null; - - - // create path and map variables - String path = "/store/inventory".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { "api_key" }; - - TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - * @return Order - */ - public Order placeOrder (Order body) throws ApiException { - Object postBody = body; - - - // create path and map variables - String path = "/store/order".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { }; - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - } - - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * @param orderId ID of pet that needs to be fetched - * @return Order - */ - public Order getOrderById (String orderId) throws ApiException { - Object postBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); - } - - - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { }; - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - } - - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * @param orderId ID of the order that needs to be deleted - * @return void - */ - public void deleteOrder (String orderId) throws ApiException { - Object postBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); - } - - - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { }; - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/UserApi.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/UserApi.java deleted file mode 100644 index a11ac7d16ed..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/api/UserApi.java +++ /dev/null @@ -1,386 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.TypeRef; - -import io.swagger.client.model.*; - -import java.util.*; - -import io.swagger.client.model.User; -import java.util.*; - -import java.io.File; -import java.util.Map; -import java.util.HashMap; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - * @return void - */ - public void createUser (User body) throws ApiException { - Object postBody = body; - - - // create path and map variables - String path = "/user".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { }; - - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - - /** - * Creates list of users with given input array - * - * @param body List of user object - * @return void - */ - public void createUsersWithArrayInput (List body) throws ApiException { - Object postBody = body; - - - // create path and map variables - String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { }; - - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - - /** - * Creates list of users with given input array - * - * @param body List of user object - * @return void - */ - public void createUsersWithListInput (List body) throws ApiException { - Object postBody = body; - - - // create path and map variables - String path = "/user/createWithList".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { }; - - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - * @return String - */ - public String loginUser (String username, String password) throws ApiException { - Object postBody = null; - - - // create path and map variables - String path = "/user/login".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - queryParams.addAll(apiClient.parameterToPairs("", "username", username)); - - queryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { }; - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - } - - /** - * Logs out current logged in user session - * - * @return void - */ - public void logoutUser () throws ApiException { - Object postBody = null; - - - // create path and map variables - String path = "/user/logout".replaceAll("\\{format\\}","json"); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { }; - - apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - * @return User - */ - public User getUserByName (String username) throws ApiException { - Object postBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); - } - - - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { }; - - TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); - - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - * @return void - */ - public void updateUser (String username, User body) throws ApiException { - Object postBody = body; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); - } - - - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { }; - - apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - * @return void - */ - public void deleteUser (String username) throws ApiException { - Object postBody = null; - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); - } - - - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - String[] authNames = new String[] { }; - - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); - - } - -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/ApiKeyAuth.java deleted file mode 100644 index 41094d08440..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/ApiKeyAuth.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import java.util.Map; -import java.util.List; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class ApiKeyAuth implements Authentication { - private final String location; - private final String paramName; - - private String apiKey; - private String apiKeyPrefix; - - public ApiKeyAuth(String location, String paramName) { - this.location = location; - this.paramName = paramName; - } - - public String getLocation() { - return location; - } - - public String getParamName() { - return paramName; - } - - public String getApiKey() { - return apiKey; - } - - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } - - public String getApiKeyPrefix() { - return apiKeyPrefix; - } - - public void setApiKeyPrefix(String apiKeyPrefix) { - this.apiKeyPrefix = apiKeyPrefix; - } - - @Override - public void applyToParams(List queryParams, Map headerParams) { - String value; - if (apiKeyPrefix != null) { - value = apiKeyPrefix + " " + apiKey; - } else { - value = apiKey; - } - if (location == "query") { - queryParams.add(new Pair(paramName, value)); - } else if (location == "header") { - headerParams.put(paramName, value); - } - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/Authentication.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/Authentication.java deleted file mode 100644 index 5585eecdf1e..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/Authentication.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import java.util.Map; -import java.util.List; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public interface Authentication { - /** Apply authentication settings to header and query params. */ - void applyToParams(List queryParams, Map headerParams); -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/HttpBasicAuth.java deleted file mode 100644 index 740d8993862..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/HttpBasicAuth.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import java.util.Map; -import java.util.List; - -import java.io.UnsupportedEncodingException; -import javax.xml.bind.DatatypeConverter; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class HttpBasicAuth implements Authentication { - private String username; - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public void applyToParams(List queryParams, Map headerParams) { - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - try { - headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/OAuth.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/OAuth.java deleted file mode 100644 index b592d67848f..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/auth/OAuth.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.swagger.client.auth; - -import io.swagger.client.Pair; - -import java.util.Map; -import java.util.List; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-23T11:08:48.917-07:00") -public class OAuth implements Authentication { - @Override - public void applyToParams(List queryParams, Map headerParams) { - // TODO: support oauth - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/test/integration/ResourceListingTestIT.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/test/integration/ResourceListingTestIT.java deleted file mode 100644 index f2b6ffffa68..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/test/integration/ResourceListingTestIT.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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. - */ - -package io.swagger.test.integration; - -import io.swagger.client.ApiClient; -import io.swagger.client.Pair; -import io.swagger.client.TypeRef; -import io.swagger.models.Operation; -import io.swagger.models.Response; -import io.swagger.models.Swagger; -import io.swagger.models.parameters.Parameter; -import io.swagger.models.properties.IntegerProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; -import io.swagger.util.Json; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static org.testng.Assert.*; - -public class ResourceListingTestIT { - ApiClient client = new ApiClient(); - Swagger swagger = null; - - @BeforeClass - public void setup() throws Exception { - TypeRef ref = new TypeRef(){}; - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String str = client.invokeAPI("/swagger.json", "GET", queryParams, null, headerParams, formParams, "application/json", "", new String[0], ref); - swagger = Json.mapper().readValue(str, Swagger.class); - assertNotNull(swagger); - } - - @Test - public void verifyFileInput() throws Exception { - Operation op = swagger.getPath("/pet/{petId}/uploadImage").getPost(); - List parameters = op.getParameters(); - Parameter petId = parameters.get(0); - assertEquals(petId.getName(), "petId"); - assertEquals(petId.getIn(), "path"); - - Parameter additionalMetadata = parameters.get(1); - assertEquals(additionalMetadata.getName(), "additionalMetadata"); - assertEquals(additionalMetadata.getIn(), "formData"); - - Parameter file = parameters.get(2); - assertEquals(file.getName(), "file"); - assertEquals(file.getIn(), "formData"); - } - - @Test - public void verifyMapResponse() throws Exception { - Operation op = swagger.getPath("/store/inventory").getGet(); - Response response = op.getResponses().get("200"); - - Property property = response.getSchema(); - assertTrue(property instanceof MapProperty); - - MapProperty mp = (MapProperty) property; - assertTrue(mp.getAdditionalProperties() instanceof IntegerProperty); - } -} \ No newline at end of file diff --git a/samples/server/petstore/nodejs/README.md b/samples/server/petstore/nodejs/README.md new file mode 100644 index 00000000000..edeea0005c0 --- /dev/null +++ b/samples/server/petstore/nodejs/README.md @@ -0,0 +1,24 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate a server stub. This is an example of building a node.js server. + +This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: + +[README](https://github.com/swagger-api/swagger-codegen/README.md) + +### Running the server +To run the server, follow these simple steps: + +``` +npm install +node . +``` + +To view the Swagger UI interface: + +``` +open http://localhost:8080/docs +``` + +This project leverages the mega-awesome [swagger-tools](https://github.com/apigee-127/swagger-tools) middleware which does most all the work. \ No newline at end of file diff --git a/samples/server/petstore/nodejs/api/swagger.json b/samples/server/petstore/nodejs/api/swagger.json deleted file mode 100644 index 4c0ad6ea42f..00000000000 --- a/samples/server/petstore/nodejs/api/swagger.json +++ /dev/null @@ -1,867 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "title": "Swagger Petstore", - "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", - "version": "1.0.0" - }, - "produces": ["application/json"], - "host": "localhost:8080", - "basePath": "/v2", - "paths": { - - "/user/createWithList": { - - "post": { - "summary": "Creates list of users with given input array", - "description":"", - "x-swagger-router-controller": "User", - "tags": ["User"], - "operationId": "createUsersWithListInput", - "parameters": [ - { - "in" : "body", - "name" : "body", - "description" : "List of user object", - "required" : false, - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/User" - } - } -} - - ], - "responses": { - "default": { - "description" : "successful operation" -} - - - } - } - - } , - - "/user/createWithArray": { - - "post": { - "summary": "Creates list of users with given input array", - "description":"", - "x-swagger-router-controller": "User", - "tags": ["User"], - "operationId": "createUsersWithArrayInput", - "parameters": [ - { - "in" : "body", - "name" : "body", - "description" : "List of user object", - "required" : false, - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/User" - } - } -} - - ], - "responses": { - "default": { - "description" : "successful operation" -} - - - } - } - - } , - - "/user/{username}": { - - "get": { - "summary": "Get user by user name", - "description":"", - "x-swagger-router-controller": "User", - "tags": ["User"], - "operationId": "getUserByName", - "parameters": [ - { - "name" : "username", - "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing. ", - "required" : true, - "type" : "string" -} - - ], - "responses": { - "200": { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/User" - }, - "examples" : { - "application/json" : { - "id" : 1, - "username" : "johnp", - "firstName" : "John", - "lastName" : "Public", - "email" : "johnp@swagger.io", - "password" : "-secret-", - "phone" : "0123456789", - "userStatus" : 0 - } - } -} - , - "400": { - "description" : "Invalid username supplied" -} - , - "404": { - "description" : "User not found" -} - - - } - } , - - "put": { - "summary": "Updated user", - "description":"This can only be done by the logged in user.", - "x-swagger-router-controller": "User", - "tags": ["User"], - "operationId": "updateUser", - "parameters": [ - { - "name" : "username", - "in" : "path", - "description" : "name that need to be deleted", - "required" : true, - "type" : "string" -}, - { - "in" : "body", - "name" : "body", - "description" : "Updated user object", - "required" : false, - "schema" : { - "$ref" : "#/definitions/User" - } -} - - ], - "responses": { - "400": { - "description" : "Invalid user supplied" -} - , - "404": { - "description" : "User not found" -} - - - } - } , - - "delete": { - "summary": "Delete user", - "description":"This can only be done by the logged in user.", - "x-swagger-router-controller": "User", - "tags": ["User"], - "operationId": "deleteUser", - "parameters": [ - { - "name" : "username", - "in" : "path", - "description" : "The name that needs to be deleted", - "required" : true, - "type" : "string" -} - - ], - "responses": { - "400": { - "description" : "Invalid username supplied" -} - , - "404": { - "description" : "User not found" -} - - - } - } - - } , - - "/user": { - - "post": { - "summary": "Create user", - "description":"This can only be done by the logged in user.", - "x-swagger-router-controller": "User", - "tags": ["User"], - "operationId": "createUser", - "parameters": [ - { - "in" : "body", - "name" : "body", - "description" : "Created user object", - "required" : false, - "schema" : { - "$ref" : "#/definitions/User" - } -} - - ], - "responses": { - "default": { - "description" : "successful operation" -} - - - } - } - - } , - - "/user/logout": { - - "get": { - "summary": "Logs out current logged in user session", - "description":"", - "x-swagger-router-controller": "User", - "tags": ["User"], - "operationId": "logoutUser", - "responses": { - "default": { - "description" : "successful operation" -} - - - } - } - - } , - - "/user/login": { - - "get": { - "summary": "Logs user into the system", - "description":"", - "x-swagger-router-controller": "User", - "tags": ["User"], - "operationId": "loginUser", - "parameters": [ - { - "name" : "username", - "in" : "query", - "description" : "The user name for login", - "required" : false, - "type" : "string" -}, - { - "name" : "password", - "in" : "query", - "description" : "The password for login in clear text", - "required" : false, - "type" : "string" -} - - ], - "responses": { - "200": { - "description" : "successful operation", - "schema" : { - "type" : "string" - } -} - , - "400": { - "description" : "Invalid username/password supplied" -} - - - } - } - - } , - - - "/pet": { - - "put": { - "summary": "Update an existing pet", - "description":"", - "x-swagger-router-controller": "Pet", - "tags": ["Pet"], - "operationId": "updatePet", - "parameters": [ - { - "in" : "body", - "name" : "body", - "description" : "Pet object that needs to be added to the store", - "required" : false, - "schema" : { - "$ref" : "#/definitions/Pet" - } -} - - ], - "responses": { - "400": { - "description" : "Invalid ID supplied" -} - , - "404": { - "description" : "Pet not found" -} - , - "405": { - "description" : "Validation exception" -} - - - } - } , - - "post": { - "summary": "Add a new pet to the store", - "description":"", - "x-swagger-router-controller": "Pet", - "tags": ["Pet"], - "operationId": "addPet", - "parameters": [ - { - "in" : "body", - "name" : "body", - "description" : "Pet object that needs to be added to the store", - "required" : false, - "schema" : { - "$ref" : "#/definitions/Pet" - } -} - - ], - "responses": { - "405": { - "description" : "Invalid input" -} - - - } - } - - } , - - "/pet/{petId}/uploadImage": { - - "post": { - "summary": "uploads an image", - "description":"", - "x-swagger-router-controller": "Pet", - "tags": ["Pet"], - "operationId": "uploadFile", - "parameters": [ - { - "name" : "petId", - "in" : "path", - "description" : "ID of pet to update", - "required" : true, - "type" : "integer", - "format" : "int64" -}, - { - "name" : "additionalMetadata", - "in" : "formData", - "description" : "Additional data to pass to server", - "required" : false, - "type" : "string" -}, - { - "name" : "file", - "in" : "formData", - "description" : "file to upload", - "required" : false, - "type" : "file" -} - - ], - "responses": { - "default": { - "description" : "successful operation" -} - - - } - } - - } , - - "/pet/findByStatus": { - - "get": { - "summary": "Finds Pets by status", - "description":"Multiple status values can be provided with comma seperated strings", - "x-swagger-router-controller": "Pet", - "tags": ["Pet"], - "operationId": "findPetsByStatus", - "parameters": [ - { - "name" : "status", - "in" : "query", - "description" : "Status values that need to be considered for filter", - "required" : false, - "type" : "array", - "collectionFormat" : "multi", - "default" : "available" -} - - ], - "responses": { - "200": { - "description" : "successful operation", - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/Pet" - } - } -} - , - "400": { - "description" : "Invalid status value" -} - - - } - } - - } , - - "/pet/findByTags": { - - "get": { - "summary": "Finds Pets by tags", - "description":"Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", - "x-swagger-router-controller": "Pet", - "tags": ["Pet"], - "operationId": "findPetsByTags", - "parameters": [ - { - "name" : "tags", - "in" : "query", - "description" : "Tags to filter by", - "required" : false, - "type" : "array", - "collectionFormat" : "multi" -} - - ], - "responses": { - "200": { - "description" : "successful operation", - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/Pet" - } - } -} - , - "400": { - "description" : "Invalid tag value" -} - - - } - } - - } , - - "/pet/{petId}": { - - "get": { - "summary": "Find pet by ID", - "description":"Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", - "x-swagger-router-controller": "Pet", - "tags": ["Pet"], - "operationId": "getPetById", - "parameters": [ - { - "name" : "petId", - "in" : "path", - "description" : "ID of pet that needs to be fetched", - "required" : true, - "type" : "integer", - "format" : "int64" -} - - ], - "responses": { - "200": { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/Pet" - } -} - , - "400": { - "description" : "Invalid ID supplied" -} - , - "404": { - "description" : "Pet not found" -} - - - } - } , - - "post": { - "summary": "Updates a pet in the store with form data", - "description":"", - "x-swagger-router-controller": "Pet", - "tags": ["Pet"], - "operationId": "updatePetWithForm", - "parameters": [ - { - "name" : "petId", - "in" : "path", - "description" : "ID of pet that needs to be updated", - "required" : true, - "type" : "string" -}, - { - "name" : "name", - "in" : "formData", - "description" : "Updated name of the pet", - "required" : false, - "type" : "string" -}, - { - "name" : "status", - "in" : "formData", - "description" : "Updated status of the pet", - "required" : false, - "type" : "string" -} - - ], - "responses": { - "405": { - "description" : "Invalid input" -} - - - } - } , - - "delete": { - "summary": "Deletes a pet", - "description":"", - "x-swagger-router-controller": "Pet", - "tags": ["Pet"], - "operationId": "deletePet", - "parameters": [ - { - "name" : "petId", - "in" : "path", - "description" : "Pet id to delete", - "required" : true, - "type" : "integer", - "format" : "int64" -}, - { - "name" : "api_key", - "in" : "header", - "description" : "", - "required" : false, - "type" : "string" -} - - ], - "responses": { - "400": { - "description" : "Invalid pet value" -} - - - } - } - - } , - - - "/store/order/{orderId}": { - - "get": { - "summary": "Find purchase order by ID", - "description":"For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", - "x-swagger-router-controller": "Store", - "tags": ["Store"], - "operationId": "getOrderById", - "parameters": [ - { - "name" : "orderId", - "in" : "path", - "description" : "ID of pet that needs to be fetched", - "required" : true, - "type" : "string" -} - - ], - "responses": { - "200": { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/Order" - } -} - , - "400": { - "description" : "Invalid ID supplied" -} - , - "404": { - "description" : "Order not found" -} - - - } - } , - - "delete": { - "summary": "Delete purchase order by ID", - "description":"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "x-swagger-router-controller": "Store", - "tags": ["Store"], - "operationId": "deleteOrder", - "parameters": [ - { - "name" : "orderId", - "in" : "path", - "description" : "ID of the order that needs to be deleted", - "required" : true, - "type" : "string" -} - - ], - "responses": { - "400": { - "description" : "Invalid ID supplied" -} - , - "404": { - "description" : "Order not found" -} - - - } - } - - } , - - "/store/order": { - - "post": { - "summary": "Place an order for a pet", - "description":"", - "x-swagger-router-controller": "Store", - "tags": ["Store"], - "operationId": "placeOrder", - "parameters": [ - { - "in" : "body", - "name" : "body", - "description" : "order placed for purchasing the pet", - "required" : false, - "schema" : { - "$ref" : "#/definitions/Order" - } -} - - ], - "responses": { - "200": { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/Order" - } -} - , - "400": { - "description" : "Invalid Order" -} - - - } - } - - } , - - "/store/inventory": { - - "get": { - "summary": "Returns pet inventories by status", - "description":"Returns a map of status codes to quantities", - "x-swagger-router-controller": "Store", - "tags": ["Store"], - "operationId": "getInventory", - "responses": { - "200": { - "description" : "successful operation", - "schema" : { - "type" : "object", - "additionalProperties" : { - "type" : "integer", - "format" : "int32" - } - } -} - - - } - } - - } - - }, "definitions": { - "User": { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "username" : { - "type" : "string" - }, - "firstName" : { - "type" : "string" - }, - "lastName" : { - "type" : "string" - }, - "email" : { - "type" : "string" - }, - "password" : { - "type" : "string" - }, - "phone" : { - "type" : "string" - }, - "userStatus" : { - "type" : "integer", - "format" : "int32", - "description" : "User Status" - } - }, - "xml" : { - "name" : "User" - } -},"Category": { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "name" : { - "type" : "string" - } - }, - "xml" : { - "name" : "Category" - } -},"Pet": { - "required" : [ "name", "photoUrls" ], - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "category" : { - "$ref" : "#/definitions/Category" - }, - "name" : { - "type" : "string", - "example" : "doggie" - }, - "photoUrls" : { - "type" : "array", - "xml" : { - "name" : "photoUrl", - "wrapped" : true - }, - "items" : { - "type" : "string" - } - }, - "tags" : { - "type" : "array", - "xml" : { - "name" : "tag", - "wrapped" : true - }, - "items" : { - "$ref" : "#/definitions/Tag" - } - }, - "status" : { - "type" : "string", - "description" : "pet status in the store", - "enum" : [ "available", "pending", "sold" ] - } - }, - "xml" : { - "name" : "Pet" - } -},"Tag": { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "name" : { - "type" : "string" - } - }, - "xml" : { - "name" : "Tag" - } -},"Order": { - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "petId" : { - "type" : "integer", - "format" : "int64" - }, - "quantity" : { - "type" : "integer", - "format" : "int32" - }, - "shipDate" : { - "type" : "string", - "format" : "date-time" - }, - "status" : { - "type" : "string", - "description" : "Order Status", - "enum" : [ "placed", "approved", "delivered" ] - }, - "complete" : { - "type" : "boolean" - } - }, - "xml" : { - "name" : "Order" - } -} - } -} diff --git a/samples/server/petstore/nodejs/api/swagger.yaml b/samples/server/petstore/nodejs/api/swagger.yaml new file mode 100644 index 00000000000..49a3405de09 --- /dev/null +++ b/samples/server/petstore/nodejs/api/swagger.yaml @@ -0,0 +1,667 @@ +--- +swagger: "2.0" +info: + description: "This is a sample server Petstore server. You can find out more about\ + \ Swagger at http://swagger.io or on irc.freenode.net,\ + \ #swagger. For this sample, you can use the api key \"special-key\" to test\ + \ the authorization filters" + version: "1.0.0" + title: "Swagger Petstore" + termsOfService: "http://swagger.io/terms/" + contact: + email: "apiteam@swagger.io" + license: + name: "Apache 2.0" + url: "http://www.apache.org/licenses/LICENSE-2.0.html" +host: "petstore.swagger.io" +basePath: "/v2" +schemes: +- "http" +paths: + /pet: + post: + tags: + - "pet" + summary: "Add a new pet to the store" + description: "" + operationId: "addPet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: false + schema: + $ref: "#/definitions/Pet" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + put: + tags: + - "pet" + summary: "Update an existing pet" + description: "" + operationId: "updatePet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: false + schema: + $ref: "#/definitions/Pet" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + 405: + description: "Validation exception" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/findByStatus: + get: + tags: + - "pet" + summary: "Finds Pets by status" + description: "Multiple status values can be provided with comma seperated strings" + operationId: "findPetsByStatus" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "status" + in: "query" + description: "Status values that need to be considered for filter" + required: false + type: "array" + items: + type: "string" + collectionFormat: "multi" + default: "available" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid status value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/findByTags: + get: + tags: + - "pet" + summary: "Finds Pets by tags" + description: "Muliple tags can be provided with comma seperated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: "findPetsByTags" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "tags" + in: "query" + description: "Tags to filter by" + required: false + type: "array" + items: + type: "string" + collectionFormat: "multi" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid tag value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/{petId}: + get: + tags: + - "pet" + summary: "Find pet by ID" + description: "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate\ + \ API error conditions" + operationId: "getPetById" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "integer" + format: "int64" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Pet" + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + security: + - api_key: [] + - petstore_auth: + - "write:pets" + - "read:pets" + post: + tags: + - "pet" + summary: "Updates a pet in the store with form data" + description: "" + operationId: "updatePetWithForm" + consumes: + - "application/x-www-form-urlencoded" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be updated" + required: true + type: "string" + - name: "name" + in: "formData" + description: "Updated name of the pet" + required: false + type: "string" + - name: "status" + in: "formData" + description: "Updated status of the pet" + required: false + type: "string" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + delete: + tags: + - "pet" + summary: "Deletes a pet" + description: "" + operationId: "deletePet" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "api_key" + in: "header" + description: "" + required: false + type: "string" + - name: "petId" + in: "path" + description: "Pet id to delete" + required: true + type: "integer" + format: "int64" + responses: + 400: + description: "Invalid pet value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /pet/{petId}/uploadImage: + post: + tags: + - "pet" + summary: "uploads an image" + description: "" + operationId: "uploadFile" + consumes: + - "multipart/form-data" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to update" + required: true + type: "integer" + format: "int64" + - name: "additionalMetadata" + in: "formData" + description: "Additional data to pass to server" + required: false + type: "string" + - name: "file" + in: "formData" + description: "file to upload" + required: false + type: "file" + responses: + default: + description: "successful operation" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "getInventory" + produces: + - "application/json" + - "application/xml" + parameters: [] + responses: + 200: + description: "successful operation" + schema: + type: "object" + additionalProperties: + type: "integer" + format: "int32" + security: + - api_key: [] + /store/order: + post: + tags: + - "store" + summary: "Place an order for a pet" + description: "" + operationId: "placeOrder" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "order placed for purchasing the pet" + required: false + schema: + $ref: "#/definitions/Order" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid Order" + /store/order/{orderId}: + get: + tags: + - "store" + summary: "Find purchase order by ID" + description: "For valid response try integer IDs with value <= 5 or > 10. Other\ + \ values will generated exceptions" + operationId: "getOrderById" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "orderId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "string" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + delete: + tags: + - "store" + summary: "Delete purchase order by ID" + description: "For valid response try integer IDs with value < 1000. Anything\ + \ above 1000 or nonintegers will generate API errors" + operationId: "deleteOrder" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "orderId" + in: "path" + description: "ID of the order that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + /user: + post: + tags: + - "user" + summary: "Create user" + description: "This can only be done by the logged in user." + operationId: "createUser" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "Created user object" + required: false + schema: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/createWithArray: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithArrayInput" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: false + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/createWithList: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithListInput" + produces: + - "application/json" + - "application/xml" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: false + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + /user/login: + get: + tags: + - "user" + summary: "Logs user into the system" + description: "" + operationId: "loginUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "query" + description: "The user name for login" + required: false + type: "string" + - name: "password" + in: "query" + description: "The password for login in clear text" + required: false + type: "string" + responses: + 200: + description: "successful operation" + schema: + type: "string" + 400: + description: "Invalid username/password supplied" + /user/logout: + get: + tags: + - "user" + summary: "Logs out current logged in user session" + description: "" + operationId: "logoutUser" + produces: + - "application/json" + - "application/xml" + parameters: [] + responses: + default: + description: "successful operation" + /user/{username}: + get: + tags: + - "user" + summary: "Get user by user name" + description: "" + operationId: "getUserByName" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be fetched. Use user1 for testing. " + required: true + type: "string" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/User" + examples: + application/json: + id: 1 + username: "johnp" + firstName: "John" + lastName: "Public" + email: "johnp@swagger.io" + password: "-secret-" + phone: "0123456789" + userStatus: 0 + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + put: + tags: + - "user" + summary: "Updated user" + description: "This can only be done by the logged in user." + operationId: "updateUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "name that need to be deleted" + required: true + type: "string" + - in: "body" + name: "body" + description: "Updated user object" + required: false + schema: + $ref: "#/definitions/User" + responses: + 400: + description: "Invalid user supplied" + 404: + description: "User not found" + delete: + tags: + - "user" + summary: "Delete user" + description: "This can only be done by the logged in user." + operationId: "deleteUser" + produces: + - "application/json" + - "application/xml" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid username supplied" + 404: + description: "User not found" +securityDefinitions: + api_key: + type: "apiKey" + name: "api_key" + in: "header" + petstore_auth: + type: "oauth2" + authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" + flow: "implicit" + scopes: + write:pets: "modify pets in your account" + read:pets: "read your pets" +definitions: + User: + properties: + id: + type: "integer" + format: "int64" + username: + type: "string" + firstName: + type: "string" + lastName: + type: "string" + email: + type: "string" + password: + type: "string" + phone: + type: "string" + userStatus: + type: "integer" + format: "int32" + description: "User Status" + xml: + name: "User" + Category: + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Category" + Pet: + required: + - "name" + - "photoUrls" + properties: + id: + type: "integer" + format: "int64" + category: + $ref: "#/definitions/Category" + name: + type: "string" + example: "doggie" + photoUrls: + type: "array" + xml: + name: "photoUrl" + wrapped: true + items: + type: "string" + tags: + type: "array" + xml: + name: "tag" + wrapped: true + items: + $ref: "#/definitions/Tag" + status: + type: "string" + description: "pet status in the store" + enum: + - "available" + - "pending" + - "sold" + xml: + name: "Pet" + Tag: + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + xml: + name: "Tag" + Order: + properties: + id: + type: "integer" + format: "int64" + petId: + type: "integer" + format: "int64" + quantity: + type: "integer" + format: "int32" + shipDate: + type: "string" + format: "date-time" + status: + type: "string" + description: "Order Status" + enum: + - "placed" + - "approved" + - "delivered" + complete: + type: "boolean" + xml: + name: "Order" diff --git a/samples/server/petstore/nodejs/controllers/Pet.js b/samples/server/petstore/nodejs/controllers/Pet.js index a268c8fa700..d272cb8240f 100644 --- a/samples/server/petstore/nodejs/controllers/Pet.js +++ b/samples/server/petstore/nodejs/controllers/Pet.js @@ -7,118 +7,33 @@ var Pet = require('./PetService'); module.exports.updatePet = function updatePet (req, res, next) { - var body = req.swagger.params['body'].value; - - - var result = Pet.updatePet(body); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Pet.updatePet(req.swagger.params, res, next); }; module.exports.addPet = function addPet (req, res, next) { - var body = req.swagger.params['body'].value; - - - var result = Pet.addPet(body); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Pet.addPet(req.swagger.params, res, next); }; module.exports.findPetsByStatus = function findPetsByStatus (req, res, next) { - var status = req.swagger.params['status'].value; - - - var result = Pet.findPetsByStatus(status); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Pet.findPetsByStatus(req.swagger.params, res, next); }; module.exports.findPetsByTags = function findPetsByTags (req, res, next) { - var tags = req.swagger.params['tags'].value; - - - var result = Pet.findPetsByTags(tags); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Pet.findPetsByTags(req.swagger.params, res, next); }; module.exports.getPetById = function getPetById (req, res, next) { - var petId = req.swagger.params['petId'].value; - - - var result = Pet.getPetById(petId); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Pet.getPetById(req.swagger.params, res, next); }; module.exports.updatePetWithForm = function updatePetWithForm (req, res, next) { - var petId = req.swagger.params['petId'].value; - var name = req.swagger.params['name'].value; - var status = req.swagger.params['status'].value; - - - var result = Pet.updatePetWithForm(petId, name, status); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Pet.updatePetWithForm(req.swagger.params, res, next); }; module.exports.deletePet = function deletePet (req, res, next) { - var petId = req.swagger.params['petId'].value; - var apiKey = req.swagger.params['api_key'].value; - - - var result = Pet.deletePet(petId, apiKey); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Pet.deletePet(req.swagger.params, res, next); }; module.exports.uploadFile = function uploadFile (req, res, next) { - var petId = req.swagger.params['petId'].value; - var additionalMetadata = req.swagger.params['additionalMetadata'].value; - var file = req.swagger.params['file'].value; - - - var result = Pet.uploadFile(petId, additionalMetadata, file); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Pet.uploadFile(req.swagger.params, res, next); }; diff --git a/samples/server/petstore/nodejs/controllers/PetService.js b/samples/server/petstore/nodejs/controllers/PetService.js index f238fa410ac..97a1d3ede62 100644 --- a/samples/server/petstore/nodejs/controllers/PetService.js +++ b/samples/server/petstore/nodejs/controllers/PetService.js @@ -1,22 +1,36 @@ 'use strict'; -exports.updatePet = function(body) { +exports.updatePet = function(args, res, next) { + /** + * parameters expected in the args: + * body (Pet) + **/ - var examples = {}; +var examples = {}; + res.end(); } -exports.addPet = function(body) { +exports.addPet = function(args, res, next) { + /** + * parameters expected in the args: + * body (Pet) + **/ - var examples = {}; +var examples = {}; + res.end(); } -exports.findPetsByStatus = function(status) { +exports.findPetsByStatus = function(args, res, next) { + /** + * parameters expected in the args: + * status (List) + **/ - var examples = {}; +var examples = {}; examples['application/json'] = [ { "tags" : [ { @@ -35,13 +49,23 @@ exports.findPetsByStatus = function(status) { - if(Object.keys(examples).length > 0) - return examples[Object.keys(examples)[0]]; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + } -exports.findPetsByTags = function(tags) { +exports.findPetsByTags = function(args, res, next) { + /** + * parameters expected in the args: + * tags (List) + **/ - var examples = {}; +var examples = {}; examples['application/json'] = [ { "tags" : [ { @@ -60,13 +84,23 @@ exports.findPetsByTags = function(tags) { - if(Object.keys(examples).length > 0) - return examples[Object.keys(examples)[0]]; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + } -exports.getPetById = function(petId) { +exports.getPetById = function(args, res, next) { + /** + * parameters expected in the args: + * petId (Long) + **/ - var examples = {}; +var examples = {}; examples['application/json'] = { "tags" : [ { @@ -85,28 +119,54 @@ exports.getPetById = function(petId) { - if(Object.keys(examples).length > 0) - return examples[Object.keys(examples)[0]]; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + } -exports.updatePetWithForm = function(petId, name, status) { +exports.updatePetWithForm = function(args, res, next) { + /** + * parameters expected in the args: + * petId (String) + * name (String) + * status (String) + **/ - var examples = {}; +var examples = {}; + res.end(); } -exports.deletePet = function(petId, apiKey) { +exports.deletePet = function(args, res, next) { + /** + * parameters expected in the args: + * petId (Long) + * apiKey (String) + **/ - var examples = {}; +var examples = {}; + res.end(); } -exports.uploadFile = function(petId, additionalMetadata, file) { +exports.uploadFile = function(args, res, next) { + /** + * parameters expected in the args: + * petId (Long) + * additionalMetadata (String) + * file (file) + **/ - var examples = {}; +var examples = {}; + res.end(); } diff --git a/samples/server/petstore/nodejs/controllers/Store.js b/samples/server/petstore/nodejs/controllers/Store.js index 7059f9afa61..8a07dc76ed3 100644 --- a/samples/server/petstore/nodejs/controllers/Store.js +++ b/samples/server/petstore/nodejs/controllers/Store.js @@ -7,56 +7,17 @@ var Store = require('./StoreService'); module.exports.getInventory = function getInventory (req, res, next) { - - - var result = Store.getInventory(); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Store.getInventory(req.swagger.params, res, next); }; module.exports.placeOrder = function placeOrder (req, res, next) { - var body = req.swagger.params['body'].value; - - - var result = Store.placeOrder(body); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Store.placeOrder(req.swagger.params, res, next); }; module.exports.getOrderById = function getOrderById (req, res, next) { - var orderId = req.swagger.params['orderId'].value; - - - var result = Store.getOrderById(orderId); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Store.getOrderById(req.swagger.params, res, next); }; module.exports.deleteOrder = function deleteOrder (req, res, next) { - var orderId = req.swagger.params['orderId'].value; - - - var result = Store.deleteOrder(orderId); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + Store.deleteOrder(req.swagger.params, res, next); }; diff --git a/samples/server/petstore/nodejs/controllers/StoreService.js b/samples/server/petstore/nodejs/controllers/StoreService.js index e00a6aee9b9..3bb37b6c01f 100644 --- a/samples/server/petstore/nodejs/controllers/StoreService.js +++ b/samples/server/petstore/nodejs/controllers/StoreService.js @@ -1,8 +1,11 @@ 'use strict'; -exports.getInventory = function() { +exports.getInventory = function(args, res, next) { + /** + * parameters expected in the args: + **/ - var examples = {}; +var examples = {}; examples['application/json'] = { "key" : 123 @@ -10,13 +13,23 @@ exports.getInventory = function() { - if(Object.keys(examples).length > 0) - return examples[Object.keys(examples)[0]]; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + } -exports.placeOrder = function(body) { +exports.placeOrder = function(args, res, next) { + /** + * parameters expected in the args: + * body (Order) + **/ - var examples = {}; +var examples = {}; examples['application/json'] = { "id" : 123456789, @@ -24,18 +37,28 @@ exports.placeOrder = function(body) { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-10-20T06:12:23.907+0000" + "shipDate" : "2015-11-18T02:43:54.540+0000" }; - if(Object.keys(examples).length > 0) - return examples[Object.keys(examples)[0]]; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + } -exports.getOrderById = function(orderId) { +exports.getOrderById = function(args, res, next) { + /** + * parameters expected in the args: + * orderId (String) + **/ - var examples = {}; +var examples = {}; examples['application/json'] = { "id" : 123456789, @@ -43,19 +66,30 @@ exports.getOrderById = function(orderId) { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-10-20T06:12:23.911+0000" + "shipDate" : "2015-11-18T02:43:54.544+0000" }; - if(Object.keys(examples).length > 0) - return examples[Object.keys(examples)[0]]; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + } -exports.deleteOrder = function(orderId) { +exports.deleteOrder = function(args, res, next) { + /** + * parameters expected in the args: + * orderId (String) + **/ - var examples = {}; +var examples = {}; + res.end(); } diff --git a/samples/server/petstore/nodejs/controllers/User.js b/samples/server/petstore/nodejs/controllers/User.js index d89f34c9c3f..d2ce361da52 100644 --- a/samples/server/petstore/nodejs/controllers/User.js +++ b/samples/server/petstore/nodejs/controllers/User.js @@ -7,114 +7,33 @@ var User = require('./UserService'); module.exports.createUser = function createUser (req, res, next) { - var body = req.swagger.params['body'].value; - - - var result = User.createUser(body); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + User.createUser(req.swagger.params, res, next); }; module.exports.createUsersWithArrayInput = function createUsersWithArrayInput (req, res, next) { - var body = req.swagger.params['body'].value; - - - var result = User.createUsersWithArrayInput(body); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + User.createUsersWithArrayInput(req.swagger.params, res, next); }; module.exports.createUsersWithListInput = function createUsersWithListInput (req, res, next) { - var body = req.swagger.params['body'].value; - - - var result = User.createUsersWithListInput(body); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + User.createUsersWithListInput(req.swagger.params, res, next); }; module.exports.loginUser = function loginUser (req, res, next) { - var username = req.swagger.params['username'].value; - var password = req.swagger.params['password'].value; - - - var result = User.loginUser(username, password); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + User.loginUser(req.swagger.params, res, next); }; module.exports.logoutUser = function logoutUser (req, res, next) { - - - var result = User.logoutUser(); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + User.logoutUser(req.swagger.params, res, next); }; module.exports.getUserByName = function getUserByName (req, res, next) { - var username = req.swagger.params['username'].value; - - - var result = User.getUserByName(username); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + User.getUserByName(req.swagger.params, res, next); }; module.exports.updateUser = function updateUser (req, res, next) { - var username = req.swagger.params['username'].value; - var body = req.swagger.params['body'].value; - - - var result = User.updateUser(username, body); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + User.updateUser(req.swagger.params, res, next); }; module.exports.deleteUser = function deleteUser (req, res, next) { - var username = req.swagger.params['username'].value; - - - var result = User.deleteUser(username); - - if(typeof result !== 'undefined') { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(result || {}, null, 2)); - } - else - res.end(); + User.deleteUser(req.swagger.params, res, next); }; diff --git a/samples/server/petstore/nodejs/controllers/UserService.js b/samples/server/petstore/nodejs/controllers/UserService.js index 30aab42ada9..71f34f35bfb 100644 --- a/samples/server/petstore/nodejs/controllers/UserService.js +++ b/samples/server/petstore/nodejs/controllers/UserService.js @@ -1,48 +1,82 @@ 'use strict'; -exports.createUser = function(body) { +exports.createUser = function(args, res, next) { + /** + * parameters expected in the args: + * body (User) + **/ - var examples = {}; +var examples = {}; + res.end(); } -exports.createUsersWithArrayInput = function(body) { +exports.createUsersWithArrayInput = function(args, res, next) { + /** + * parameters expected in the args: + * body (List) + **/ - var examples = {}; +var examples = {}; + res.end(); } -exports.createUsersWithListInput = function(body) { +exports.createUsersWithListInput = function(args, res, next) { + /** + * parameters expected in the args: + * body (List) + **/ - var examples = {}; +var examples = {}; + res.end(); } -exports.loginUser = function(username, password) { +exports.loginUser = function(args, res, next) { + /** + * parameters expected in the args: + * username (String) + * password (String) + **/ - var examples = {}; +var examples = {}; examples['application/json'] = "aeiou"; - if(Object.keys(examples).length > 0) - return examples[Object.keys(examples)[0]]; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + } -exports.logoutUser = function() { +exports.logoutUser = function(args, res, next) { + /** + * parameters expected in the args: + **/ - var examples = {}; +var examples = {}; + res.end(); } -exports.getUserByName = function(username) { +exports.getUserByName = function(args, res, next) { + /** + * parameters expected in the args: + * username (String) + **/ - var examples = {}; +var examples = {}; examples['application/json'] = { "id" : 1, @@ -57,21 +91,38 @@ exports.getUserByName = function(username) { - if(Object.keys(examples).length > 0) - return examples[Object.keys(examples)[0]]; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + } -exports.updateUser = function(username, body) { +exports.updateUser = function(args, res, next) { + /** + * parameters expected in the args: + * username (String) + * body (User) + **/ - var examples = {}; +var examples = {}; + res.end(); } -exports.deleteUser = function(username) { +exports.deleteUser = function(args, res, next) { + /** + * parameters expected in the args: + * username (String) + **/ - var examples = {}; +var examples = {}; + res.end(); } diff --git a/samples/server/petstore/nodejs/index.js b/samples/server/petstore/nodejs/index.js index c922cc7c1e7..aaa873a128a 100644 --- a/samples/server/petstore/nodejs/index.js +++ b/samples/server/petstore/nodejs/index.js @@ -3,7 +3,8 @@ var app = require('connect')(); var http = require('http'); var swaggerTools = require('swagger-tools'); - +var jsyaml = require('js-yaml'); +var fs = require('fs'); var serverPort = 8080; // swaggerRouter configuration @@ -14,7 +15,8 @@ var options = { }; // The Swagger document (require it, build it programmatically, fetch it from a URL, ...) -var swaggerDoc = require('./api/swagger.json'); +var spec = fs.readFileSync('./api/swagger.yaml', 'utf8'); +var swaggerDoc = jsyaml.safeLoad(spec); // Initialize the Swagger middleware swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) { diff --git a/samples/server/petstore/nodejs/package.json b/samples/server/petstore/nodejs/package.json index 35390feefda..8befd2669d2 100644 --- a/samples/server/petstore/nodejs/package.json +++ b/samples/server/petstore/nodejs/package.json @@ -10,6 +10,7 @@ "private": true, "dependencies": { "connect": "^3.2.0", - "swagger-tools": "0.8.*" + "js-yaml": "^3.3.0", + "swagger-tools": "0.9.*" } }