diff --git a/README.md b/README.md index ec693d92483..664b8e20ef1 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additi - [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) @@ -66,7 +67,7 @@ You need the following installed and available in your $PATH: #### 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 @@ -99,6 +100,15 @@ cd swagger-codegen -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: @@ -115,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 @@ -355,7 +365,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: ``` @@ -476,7 +486,7 @@ Note! The templates are included in the library generated. If you want to modi ## Online generators -One can also generate API client or sever using the online generators (https://generator.swagger.io) +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: ``` 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/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/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index 2e53ab42797..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,7 +38,10 @@ 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"; 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 7fa3d1883b6..3c8758fc15b 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 @@ -87,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; @@ -109,6 +110,11 @@ public class DefaultCodegen { 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())); + } } // override with any special post-processing @@ -245,6 +251,10 @@ public class DefaultCodegen { this.sortParamsByRequiredFlag = sortParamsByRequiredFlag; } + public void setEnsureUniqueParams(Boolean ensureUniqueParams) { + this.ensureUniqueParams = ensureUniqueParams; + } + /** * Return the file name of the Api * @@ -433,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)); } /** @@ -1245,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); @@ -1283,7 +1310,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) { @@ -1418,6 +1445,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; @@ -1710,6 +1740,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); 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 38089e7eeed..5fa165f0788 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 @@ -262,6 +262,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"); 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 312f087f83c..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; @@ -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 35b876aabaf..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 @@ -60,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(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "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() { 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 e033b9f3cf3..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; @@ -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 1e218e5ca00..a7972253188 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 @@ -80,9 +80,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.put("object", "Object"); cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case), default: IO.Swagger")); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "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 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 96f74907449..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 @@ -79,9 +79,11 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege typeMapping.put("object", "Object"); cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case), default: IO.Swagger")); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "C# package version, default: 1.0.0")); - cliOptions.add(new CliOption(CLIENT_PACKAGE, "C# client package name (convention: Camel.Case), default: IO.Swagger.Client")); + 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 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 353174df056..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 @@ -75,9 +75,9 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "flash package name (convention:" + - " package.name), default: io.swagger")); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "flash package version, " + - "default: 1.0.0")); + " 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")); 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 34b4e0e77d6..4e6f1b9910a 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 @@ -37,6 +37,7 @@ 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"; @@ -83,6 +84,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)); @@ -90,13 +93,18 @@ 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(FULL_JAVA_UTIL, "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)); + 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 @@ -196,6 +204,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { 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")); 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 fd83e38896a..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,23 +1,12 @@ 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.CodegenResponse; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.*; import io.swagger.models.Operation; -import io.swagger.models.properties.Property; -import io.swagger.models.properties.StringProperty; +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"; @@ -118,6 +107,36 @@ 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"); @@ -195,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"; 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 a3e1463d857..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 @@ -120,13 +120,17 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { instantiationTypes.put("map", "NSMutableDictionary"); cliOptions.clear(); - cliOptions.add(new CliOption(CLASS_PREFIX, "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`), default: `SWG`")); - cliOptions.add(new CliOption(POD_NAME, "cocoapods package name (convention: CameCase), default: `SwaggerClient`")); - cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "cocoapods package version, default: `1.0.0`")); - cliOptions.add(new CliOption(AUTHOR_NAME, "Name to use in the podspec file, default: `Swagger`")); - cliOptions.add(new CliOption(AUTHOR_EMAIL, "Email to use in the podspec file, default: `apiteam@swagger.io`")); - cliOptions.add(new CliOption(GIT_REPO_URL, "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() { 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 ee2fa0ddbf3..3213f0b9716 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; @@ -70,8 +71,11 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "object"); cliOptions.clear(); - cliOptions.add(new CliOption(MODULE_NAME, "perl module name (convention: CamelCase), default: SwaggerClient")); - cliOptions.add(new CliOption(MODULE_VERSION, "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)); + } 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 cc852371573..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 @@ -91,7 +91,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "object"); typeMapping.put("DateTime", "\\DateTime"); - cliOptions.add(new CliOption(VARIABLE_NAMING_CONVENTION, "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(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.")); 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 2722a93b3c9..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 @@ -63,9 +63,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig "return", "def", "for", "lambda", "try")); cliOptions.clear(); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case)," + - " default: swagger_client")); - cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "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 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 12dcedd36ae..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,6 +13,7 @@ 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; @@ -70,10 +72,19 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("file", "File"); // remove modelPackage and apiPackage added by default - cliOptions.clear(); - cliOptions.add(new CliOption(GEM_NAME, "gem name (convention: underscore_case), default: swagger_client")); - cliOptions.add(new CliOption(MODULE_NAME, "top module name (convention: CamelCase, usually corresponding to gem name), default: SwaggerClient")); - cliOptions.add(new CliOption(GEM_VERSION, "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 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 3da348ad530..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; @@ -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 81106955d84..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; @@ -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/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/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/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/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/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/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/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index f6dd2933331..883a635472d 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -319,8 +319,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: 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/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/perl/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache index 02f9ff2221f..89e5650759a 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache @@ -324,7 +324,7 @@ 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 { diff --git a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache index 0a097dda7bd..d0b8b2c0e68 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache @@ -17,8 +17,12 @@ our $http_user_agent = 'Perl-Swagger'; # authenticaiton setting our $api_key = {}; our $api_key_prefix = {}; -our $username; -our $password; +# username and password for HTTP basic authentication +our $username = ''; +our $password = ''; + +# access token for OAuth +our $access_token = ''; 1; 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/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/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/dart/DartClientOptionsTest.java index b4ac84be47f..b002fd99978 100644 --- 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 @@ -25,10 +25,6 @@ public class DartClientOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(DartClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(DartClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(DartClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; clientCodegen.setBrowserClient(Boolean.valueOf(DartClientOptionsProvider.BROWSER_CLIENT_VALUE)); 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 index 6b24bc6f251..ce905315ae3 100644 --- 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 @@ -25,10 +25,6 @@ public class NodeJSServerOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(NodeJSServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(NodeJSServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(NodeJSServerOptionsProvider.SORT_PARAMS_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 index 6cd8e83467b..e26968500d7 100644 --- 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 @@ -10,6 +10,7 @@ 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() { @@ -22,6 +23,7 @@ public class AkkaScalaClientOptionsProvider implements OptionsProvider { 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(); } 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 index 12752d7b636..c677e5caa7b 100644 --- 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 @@ -13,6 +13,7 @@ public class AndroidClientOptionsProvider implements OptionsProvider { 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"; @@ -29,6 +30,7 @@ public class AndroidClientOptionsProvider implements OptionsProvider { 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) 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 index 3a5daca3ba2..be21a20efe4 100644 --- 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 @@ -10,6 +10,7 @@ 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() { @@ -22,6 +23,7 @@ public class AsyncScalaClientOptionsProvider implements OptionsProvider { 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(); } 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 index d7309b7baec..442465dfcf9 100644 --- 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 @@ -20,6 +20,7 @@ public class CSharpClientOptionsProvider implements OptionsProvider { 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(); } 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 index 07689da66da..72066f54053 100644 --- 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 @@ -8,9 +8,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class DartClientOptionsProvider implements OptionsProvider { - public static final String MODEL_PACKAGE_VALUE = "packagedart"; - public static final String API_PACKAGE_VALUE = "apiPackageDart"; 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"; @@ -25,9 +24,8 @@ public class DartClientOptionsProvider implements OptionsProvider { @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) + 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) 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 index 26d4c893236..8ea7ee31452 100644 --- 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 @@ -20,6 +20,7 @@ public class JavaOptionsProvider implements OptionsProvider { 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() { @@ -27,6 +28,7 @@ public class JavaOptionsProvider implements OptionsProvider { 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) 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 index 09500bd65ea..3d49fcb8d01 100644 --- 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 @@ -7,9 +7,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class NodeJSServerOptionsProvider 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() { @@ -19,9 +18,8 @@ public class NodeJSServerOptionsProvider implements OptionsProvider { @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) + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); } 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 index 5bf55f4d160..5ffe04bff2b 100644 --- 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 @@ -1,5 +1,7 @@ package io.swagger.codegen.options; +import io.swagger.codegen.CodegenConstants; + import io.swagger.codegen.languages.PerlClientCodegen; import com.google.common.collect.ImmutableMap; @@ -20,6 +22,8 @@ public class PerlClientOptionsProvider implements OptionsProvider { 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(); } 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 index fd1fbabbe5d..dcd7a06438f 100644 --- 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 @@ -11,6 +11,7 @@ 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"; @@ -30,6 +31,7 @@ public class PhpClientOptionsProvider implements OptionsProvider { 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) 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 index 1d89933a746..ec62e3f2b7c 100644 --- 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 @@ -20,6 +20,7 @@ public class PythonClientOptionsProvider implements OptionsProvider { 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(); } 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 index 1deb7a99afc..05f9f1f068c 100644 --- 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 @@ -7,9 +7,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class Qt5CPPOptionsProvider 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() { @@ -19,9 +18,8 @@ public class Qt5CPPOptionsProvider implements OptionsProvider { @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) + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); } 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 index 94f15cc1def..d80341f0200 100644 --- 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 @@ -1,5 +1,6 @@ package io.swagger.codegen.options; +import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.languages.RubyClientCodegen; import com.google.common.collect.ImmutableMap; @@ -10,6 +11,8 @@ 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() { @@ -22,6 +25,8 @@ public class RubyClientOptionsProvider implements OptionsProvider { 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(); } 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 index 5d9b80b2670..867482f145b 100644 --- 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 @@ -10,6 +10,7 @@ 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() { @@ -22,6 +23,7 @@ public class ScalaClientOptionsProvider implements OptionsProvider { 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(); } 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 index 0e237f1b1e9..a0fef2f4858 100644 --- 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 @@ -10,6 +10,7 @@ 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() { @@ -22,6 +23,7 @@ public class ScalatraServerOptionsProvider implements OptionsProvider { 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(); } 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 index 35d290ada7a..ae6596923d2 100644 --- 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 @@ -7,9 +7,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class SilexServerOptionsProvider 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() { @@ -19,9 +18,8 @@ public class SilexServerOptionsProvider implements OptionsProvider { @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) + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); } 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 index fcef6a436cf..5e198a0e91a 100644 --- 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 @@ -7,9 +7,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class StaticDocOptionsProvider 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() { @@ -19,9 +18,8 @@ public class StaticDocOptionsProvider implements OptionsProvider { @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) + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); } 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 index d0067b60117..f236ff40dc0 100644 --- 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 @@ -7,9 +7,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class StaticHtmlOptionsProvider 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() { @@ -19,9 +18,8 @@ public class StaticHtmlOptionsProvider implements OptionsProvider { @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) + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); } 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 index 81b8059b9e9..e97860e83ab 100644 --- 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 @@ -7,9 +7,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class SwaggerOptionsProvider 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() { @@ -19,9 +18,8 @@ public class SwaggerOptionsProvider implements OptionsProvider { @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) + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); } 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 index f611dc9c88c..ff5daa86797 100644 --- 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 @@ -7,9 +7,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class SwaggerYamlOptionsProvider 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() { @@ -19,9 +18,8 @@ public class SwaggerYamlOptionsProvider implements OptionsProvider { @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) + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); } 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 index c5600d4f590..507d3b62829 100644 --- 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 @@ -8,9 +8,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class SwiftOptionsProvider 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 PROJECT_NAME_VALUE = "Swagger"; public static final String RESPONSE_AS_VALUE = "test"; public static final String UNWRAP_REQUIRED_VALUE = "true"; @@ -35,9 +34,8 @@ public class SwiftOptionsProvider implements OptionsProvider { @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) + 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) 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 index 796aabc6b31..ff8659627f4 100644 --- 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 @@ -7,9 +7,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class TizenClientOptionsProvider 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() { @@ -19,9 +18,8 @@ public class TizenClientOptionsProvider implements OptionsProvider { @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) + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); } 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 index 24ce25b4578..d7d4e5392fc 100644 --- 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 @@ -7,9 +7,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class TypeScriptAngularClientOptionsProvider 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() { @@ -19,9 +18,8 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { @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) + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); } 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 index 5da5c01c991..e1c0259222e 100644 --- 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 @@ -7,9 +7,8 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class TypeScriptNodeClientOptionsProvider 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() { @@ -19,9 +18,8 @@ public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { @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) + return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); } 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 index c7bb169de21..389721d3841 100644 --- 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 @@ -25,10 +25,6 @@ public class Qt5CPPOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(Qt5CPPOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(Qt5CPPOptionsProvider.API_PACKAGE_VALUE); - times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(Qt5CPPOptionsProvider.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 index 54635f02799..11681230289 100644 --- 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 @@ -25,10 +25,6 @@ public class SilexServerOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(SilexServerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(SilexServerOptionsProvider.API_PACKAGE_VALUE); - times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SilexServerOptionsProvider.SORT_PARAMS_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 index 5ae4064c4ec..bc2da143efb 100644 --- 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 @@ -25,10 +25,6 @@ public class StaticDocOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(StaticDocOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(StaticDocOptionsProvider.API_PACKAGE_VALUE); - times = 1; 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 index c09ada506f0..befe62e32c4 100644 --- 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 @@ -25,10 +25,6 @@ public class StaticHtmlOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(StaticHtmlOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(StaticHtmlOptionsProvider.API_PACKAGE_VALUE); - times = 1; 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 index 85368a44486..f2f461f2b70 100644 --- 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 @@ -25,10 +25,6 @@ public class SwaggerOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(SwaggerOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(SwaggerOptionsProvider.API_PACKAGE_VALUE); - times = 1; 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 index 5ea5a7c346b..a1478a8ba05 100644 --- 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 @@ -25,10 +25,6 @@ public class SwaggerYamlOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(SwaggerYamlOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(SwaggerYamlOptionsProvider.API_PACKAGE_VALUE); - times = 1; 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 index f76f1500f8b..7d3504f67de 100644 --- 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 @@ -25,10 +25,6 @@ public class SwiftOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(SwiftOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(SwiftOptionsProvider.API_PACKAGE_VALUE); - times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SwiftOptionsProvider.SORT_PARAMS_VALUE)); times = 1; clientCodegen.setProjectName(SwiftOptionsProvider.PROJECT_NAME_VALUE); 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 index 670c32017de..83ebb8be15e 100644 --- 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 @@ -25,10 +25,6 @@ public class TizenClientOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(TizenClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(TizenClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; 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 index d8e6589f17a..3fdf817dc58 100644 --- 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 @@ -25,10 +25,6 @@ public class TypeScriptAngularClientOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(TypeScriptAngularClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(TypeScriptAngularClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; 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 index 7d94f21f048..2374011b1b9 100644 --- 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 @@ -25,10 +25,6 @@ public class TypeScriptNodeClientOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(TypeScriptNodeClientOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(TypeScriptNodeClientOptionsProvider.API_PACKAGE_VALUE); - times = 1; clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptNodeClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; }}; 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 fd095e6c198..bc7f4a8cc68 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,16 +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"); @@ -53,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) { @@ -90,7 +113,7 @@ public class Generator { codegenConfig.setOutputDir(outputFolder); - Json.prettyPrint(clientOpts); + LOGGER.debug(Json.pretty(clientOpts)); clientOptInput.setConfig(codegenConfig); @@ -105,6 +128,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 31262a24a9a..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,7 +1,11 @@ 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; @@ -37,6 +41,9 @@ import io.swagger.generator.exception.ApiException; import io.swagger.generator.model.GeneratorInput; 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; @@ -47,8 +54,13 @@ 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; + +import javax.annotation.Nullable; public class OnlineGeneratorOptionsTest { private static final String OPTIONS_PROVIDER = "optionsProvider"; @@ -69,12 +81,12 @@ public class OnlineGeneratorOptionsTest { {new StaticDocOptionsProvider()}, {new StaticHtmlOptionsProvider()}, {new SwaggerOptionsProvider()}, {new SwaggerYamlOptionsProvider()}, {new SwiftOptionsProvider()}, {new TizenClientOptionsProvider()}, - {new TypeScriptAngularClientOptionsProvider()}, {new TypeScriptNodeClientOptionsProvider()}, + {new TypeScriptAngularClientOptionsProvider()}, {new TypeScriptNodeClientOptionsProvider()} }; } @Test(dataProvider = OPTIONS_PROVIDER) - public void optionsTest(OptionsProvider provider) throws ApiException, IOException { + public void generateOptionsTest(OptionsProvider provider) throws ApiException, IOException { final GeneratorInput input = new GeneratorInput(); final HashMap options = convertOptions(provider); @@ -137,4 +149,53 @@ public 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 new file mode 100644 index 00000000000..93277a6a2f9 --- /dev/null +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/online/OnlineJavaClientOptionsTest.java @@ -0,0 +1,26 @@ +package io.swagger.generator.online; + +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 { + + @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/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 0416f985360..049c1ef74d8 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 @@ -320,12 +320,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: 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/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll index 3541160c3b9..c292bea9bad 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 1a9c96751ba..f63c1d21fe3 100644 Binary files a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb and b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb differ diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll index 3541160c3b9..c292bea9bad 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 1a9c96751ba..f63c1d21fe3 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/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 34e29bdc521..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-30T16:36:47.681+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/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/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/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/perl/lib/WWW/SwaggerClient/ApiClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm index 028b983808a..8b51bd3c97b 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm @@ -328,7 +328,7 @@ sub update_params_for_auth { } elsif ($auth eq 'petstore_auth') { - # TODO support oauth + $header_params->{'Authorization'} = 'Bearer ' . $WWW::SwaggerClient::Configuration::access_token; } else { diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm index aaa387236d9..6a4afe254e0 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm @@ -17,8 +17,12 @@ our $http_user_agent = 'Perl-Swagger'; # authenticaiton setting our $api_key = {}; our $api_key_prefix = {}; -our $username; -our $password; +# username and password for HTTP basic authentication +our $username = ''; +our $password = ''; + +# access token for OAuth +our $access_token = ''; 1; diff --git a/samples/client/petstore/perl/t/02_store_api.t b/samples/client/petstore/perl/t/02_store_api.t index c731273271d..dfee5c46839 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 => 42; +use Test::More tests => 41; use Test::Exception; use lib 'lib'; @@ -22,7 +22,8 @@ is $store_api->{api_client}->{base_url}, 'http://petstore.swagger.io/v2', 'get t 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 = < 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/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/typescript-angular/API/Client/Category.ts b/samples/client/petstore/typescript-angular/API/Client/Category.ts index 532d9bb0856..ad34870b31a 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Category.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Category.ts @@ -3,22 +3,11 @@ namespace API.Client { 'use strict'; - - - export interface Category { - - id: number; - - name: string; - } - - - } diff --git a/samples/client/petstore/typescript-angular/API/Client/Order.ts b/samples/client/petstore/typescript-angular/API/Client/Order.ts index 11a0fafe293..dfffcd3d828 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Order.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Order.ts @@ -3,65 +3,30 @@ namespace API.Client { 'use strict'; - - - export interface Order { - - id: number; - - petId: number; - - quantity: number; - - shipDate: Date; - - /** * Order Status */ - status: Order.StatusEnum; - - complete: boolean; - } - export namespace Order { - - - - - - - - - - export enum StatusEnum { placed = 'placed', approved = 'approved', delivered = 'delivered', } - - - - } - - - } diff --git a/samples/client/petstore/typescript-angular/API/Client/Pet.ts b/samples/client/petstore/typescript-angular/API/Client/Pet.ts index acbb6bcb6c2..fa86c457fcf 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Pet.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Pet.ts @@ -3,65 +3,30 @@ namespace API.Client { 'use strict'; - - - export interface Pet { - - id: number; - - category: Category; - - name: string; - - photoUrls: Array; - - tags: Array; - - /** * pet status in the store */ - status: Pet.StatusEnum; - } - export namespace Pet { - - - - - - - - - - - - export enum StatusEnum { available = 'available', pending = 'pending', sold = 'sold', } - - } - - - } diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 6e7dd50c6aa..7c89b754914 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -2,11 +2,9 @@ /* tslint:disable:no-unused-variable member-ordering */ - namespace API.Client { 'use strict'; - export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders : any = {}; @@ -29,20 +27,11 @@ namespace API.Client { } - 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, @@ -61,20 +50,11 @@ namespace API.Client { return this.$http(httpRequestParams); } - public addPet (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: 'POST', url: path, @@ -93,25 +73,15 @@ namespace API.Client { return this.$http(httpRequestParams); } - public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { const path = this.basePath + '/pet/findByStatus'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - if (status !== undefined) { queryParameters['status'] = status; } - - - - let httpRequestParams: any = { method: 'GET', url: path, @@ -129,25 +99,15 @@ namespace API.Client { return this.$http(httpRequestParams); } - public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { const path = this.basePath + '/pet/findByTags'; let queryParameters: any = {}; let headerParams: any = this.extendObj({}, this.defaultHeaders); - - - - - if (tags !== undefined) { queryParameters['tags'] = tags; } - - - - let httpRequestParams: any = { method: 'GET', url: path, @@ -165,26 +125,16 @@ namespace API.Client { return this.$http(httpRequestParams); } - public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { const path = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); 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'); } - - - - - - let httpRequestParams: any = { method: 'GET', url: path, @@ -202,42 +152,24 @@ namespace API.Client { return this.$http(httpRequestParams); } - public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = 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 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; - let httpRequestParams: any = { method: 'POST', url: path, @@ -256,31 +188,18 @@ namespace API.Client { return this.$http(httpRequestParams); } - public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); 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; - - - let httpRequestParams: any = { method: 'DELETE', url: path, @@ -298,42 +217,24 @@ namespace API.Client { return this.$http(httpRequestParams); } - public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { const path = 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 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; - let httpRequestParams: any = { method: 'POST', url: path, @@ -351,7 +252,5 @@ namespace API.Client { 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..801a86a4a04 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -2,26 +2,37 @@ /* 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 = { + + 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 +43,18 @@ 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); } 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 +66,23 @@ 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); } 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 +93,23 @@ 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); } 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 +120,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 525d5ff8ab1..d206559a0ef 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Tag.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Tag.ts @@ -3,22 +3,11 @@ namespace API.Client { 'use strict'; - - - export interface Tag { - - id: number; - - name: string; - } - - - } diff --git a/samples/client/petstore/typescript-angular/API/Client/User.ts b/samples/client/petstore/typescript-angular/API/Client/User.ts index 274b2e866e3..e60f84bb6c6 100644 --- a/samples/client/petstore/typescript-angular/API/Client/User.ts +++ b/samples/client/petstore/typescript-angular/API/Client/User.ts @@ -3,50 +3,26 @@ namespace API.Client { 'use strict'; - - - export interface User { - - id: number; - - username: string; - - firstName: string; - - lastName: string; - - email: string; - - password: string; - - phone: string; - - /** * User Status */ - userStatus: number; - } - - - } diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 26ebd693db9..4deb8bc6ebe 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -2,26 +2,37 @@ /* 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; } } - public createUser (body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - var path = this.basePath + '/user'; + 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 = { + + public createUser (body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const path = this.basePath + '/user'; + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let httpRequestParams: any = { method: 'POST', url: path, json: true, @@ -33,22 +44,18 @@ 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); } 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 +67,18 @@ 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); } 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 +90,17 @@ 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); } 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 +109,7 @@ module API.Client { queryParameters['password'] = password; } - var httpRequestParams: any = { + let httpRequestParams: any = { method: 'GET', url: path, json: true, @@ -121,22 +120,18 @@ 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); } 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 +142,23 @@ 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); } 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 +169,23 @@ 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); } 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 +197,23 @@ 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); } 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 +224,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-node/api.ts b/samples/client/petstore/typescript-node/api.ts index 7ee27e06dd1..47026929d81 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -8,181 +8,69 @@ import http = require('http'); /* tslint:disable:no-unused-variable */ - - - export class User { - - id: number; - - username: string; - - firstName: string; - - lastName: string; - - email: string; - - password: string; - - phone: string; - - /** * User Status */ - userStatus: number; - } - - - - - export class Category { - - id: number; - - name: string; - } - - - - - export class Pet { - - id: number; - - category: Category; - - name: string; - - photoUrls: Array; - - tags: Array; - - /** * pet status in the store */ - status: Pet.StatusEnum; - } - export namespace Pet { - - - - - - - - - - - - export enum StatusEnum { available = 'available', pending = 'pending', sold = 'sold', } - - } - - - - - export class Tag { - - id: number; - - name: string; - } - - - - - export class Order { - - id: number; - - petId: number; - - quantity: number; - - shipDate: Date; - - /** * Order Status */ - status: Order.StatusEnum; - - complete: boolean; - } - export namespace Order { - - - - - - - - - - export enum StatusEnum { placed = 'placed', approved = 'approved', delivered = 'delivered', } - - - - } - - - interface Authentication { /** * Apply authentication settings to header and query params. @@ -229,10 +117,6 @@ class VoidAuth implements Authentication { } } - - - - export class UserApi { protected basePath = 'http://petstore.swagger.io/v2'; protected defaultHeaders : any = {}; @@ -241,34 +125,13 @@ export class UserApi { public authentications = { 'default': new VoidAuth(), - - - - - 'petstore_auth': new OAuth(), - - - - 'api_key': new ApiKeyAuth('header', 'api_key'), - - - + 'petstore_auth': new OAuth(), } constructor(url: string, basePath?: string); - - - - - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { if (password) { - - - - - if (basePath) { this.basePath = basePath; } @@ -279,20 +142,9 @@ export class UserApi { } } - - - - - - - - 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)){ @@ -302,7 +154,6 @@ export class UserApi { return objA; } - public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user'; let queryParameters: any = {}; @@ -310,11 +161,8 @@ export class UserApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -323,12 +171,9 @@ export class UserApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -354,7 +199,6 @@ export class UserApi { return deferred.promise; } - public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/createWithArray'; let queryParameters: any = {}; @@ -362,11 +206,8 @@ export class UserApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -375,12 +216,9 @@ export class UserApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -406,7 +244,6 @@ export class UserApi { return deferred.promise; } - public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/createWithList'; let queryParameters: any = {}; @@ -414,11 +251,8 @@ export class UserApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -427,12 +261,9 @@ export class UserApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -458,7 +289,6 @@ export class UserApi { return deferred.promise; } - public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { const path = this.url + this.basePath + '/user/login'; let queryParameters: any = {}; @@ -466,21 +296,16 @@ export class UserApi { let formParams: any = {}; - if (username !== undefined) { queryParameters['username'] = username; } - if (password !== undefined) { queryParameters['password'] = password; } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); let requestOptions: request.Options = { @@ -489,10 +314,8 @@ export class UserApi { headers: headerParams, uri: path, json: true, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -518,7 +341,6 @@ export class UserApi { return deferred.promise; } - public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/logout'; let queryParameters: any = {}; @@ -526,11 +348,8 @@ export class UserApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -539,10 +358,8 @@ export class UserApi { headers: headerParams, uri: path, json: true, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -568,7 +385,6 @@ export class UserApi { return deferred.promise; } - public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { const path = this.url + this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); @@ -582,11 +398,8 @@ export class UserApi { throw new Error('Missing required parameter username when calling getUserByName'); } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); let requestOptions: request.Options = { @@ -595,10 +408,8 @@ export class UserApi { headers: headerParams, uri: path, json: true, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -624,7 +435,6 @@ export class UserApi { return deferred.promise; } - public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); @@ -638,11 +448,8 @@ export class UserApi { throw new Error('Missing required parameter username when calling updateUser'); } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -651,12 +458,9 @@ export class UserApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -682,7 +486,6 @@ export class UserApi { return deferred.promise; } - public deleteUser (username: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); @@ -696,11 +499,8 @@ export class UserApi { throw new Error('Missing required parameter username when calling deleteUser'); } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -709,10 +509,8 @@ export class UserApi { headers: headerParams, uri: path, json: true, - } - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -737,303 +535,7 @@ export class UserApi { return deferred.promise; } - } - - - - -export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - protected defaultHeaders : any = {}; - - - - public authentications = { - 'default': new VoidAuth(), - - - - - 'petstore_auth': new OAuth(), - - - - - 'api_key': new ApiKeyAuth('header', 'api_key'), - - - - } - - constructor(url: string, basePath?: string); - - - - - - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { - if (password) { - - - - - - if (basePath) { - this.basePath = basePath; - } - } else { - if (basePathOrUsername) { - this.basePath = basePathOrUsername - } - } - } - - - - - - - - - - set apiKey(key: string) { - this.authentications.api_key.apiKey = key; - } - - - - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } - - - public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { - const path = this.url + this.basePath + '/store/inventory'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - - - let useFormData = false; - - - let deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); - - let requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - - } - - - this.authentications.api_key.applyToRequest(requestOptions); - - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { - const path = this.url + this.basePath + '/store/order'; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - - - - let useFormData = false; - - - let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - let requestOptions: request.Options = { - method: 'POST', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - - body: body, - - } - - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { - 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 - if (!orderId) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - - - - let useFormData = false; - - - let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - let requestOptions: request.Options = { - method: 'GET', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - - } - - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; 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 - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - - - - let useFormData = false; - - - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); - - let requestOptions: request.Options = { - method: 'DELETE', - qs: queryParameters, - headers: headerParams, - uri: path, - json: true, - - } - - - this.authentications.default.applyToRequest(requestOptions); - - if (Object.keys(formParams).length) { - if (useFormData) { - (requestOptions).formData = formParams; - } else { - requestOptions.form = formParams; - } - } - - request(requestOptions, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - -} - - - - export class PetApi { protected basePath = 'http://petstore.swagger.io/v2'; protected defaultHeaders : any = {}; @@ -1042,34 +544,13 @@ export class PetApi { public authentications = { 'default': new VoidAuth(), - - - - - 'petstore_auth': new OAuth(), - - - - 'api_key': new ApiKeyAuth('header', 'api_key'), - - - + 'petstore_auth': new OAuth(), } constructor(url: string, basePath?: string); - - - - - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { if (password) { - - - - - if (basePath) { this.basePath = basePath; } @@ -1080,20 +561,9 @@ export class PetApi { } } - - - - - - - - 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)){ @@ -1103,7 +573,6 @@ export class PetApi { return objA; } - public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/pet'; let queryParameters: any = {}; @@ -1111,11 +580,8 @@ export class PetApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -1124,15 +590,11 @@ export class PetApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1158,7 +620,6 @@ export class PetApi { return deferred.promise; } - public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/pet'; let queryParameters: any = {}; @@ -1166,11 +627,8 @@ export class PetApi { let formParams: any = {}; - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -1179,15 +637,11 @@ export class PetApi { headers: headerParams, uri: path, json: true, - body: body, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1213,7 +667,6 @@ export class PetApi { return deferred.promise; } - public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const path = this.url + this.basePath + '/pet/findByStatus'; let queryParameters: any = {}; @@ -1221,16 +674,12 @@ export class PetApi { let formParams: any = {}; - if (status !== undefined) { queryParameters['status'] = status; } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); let requestOptions: request.Options = { @@ -1239,13 +688,10 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1271,7 +717,6 @@ export class PetApi { return deferred.promise; } - public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const path = this.url + this.basePath + '/pet/findByTags'; let queryParameters: any = {}; @@ -1279,16 +724,12 @@ export class PetApi { let formParams: any = {}; - if (tags !== undefined) { queryParameters['tags'] = tags; } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); let requestOptions: request.Options = { @@ -1297,13 +738,10 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1329,7 +767,6 @@ export class PetApi { return deferred.promise; } - public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { const path = this.url + this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); @@ -1343,11 +780,8 @@ export class PetApi { throw new Error('Missing required parameter petId when calling getPetById'); } - - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); let requestOptions: request.Options = { @@ -1356,13 +790,10 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.api_key.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1388,7 +819,6 @@ export class PetApi { return deferred.promise; } - 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)); @@ -1402,23 +832,16 @@ export class PetApi { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } - - let useFormData = false; - if (name !== undefined) { formParams['name'] = name; } - - if (status !== undefined) { formParams['status'] = status; } - - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -1427,13 +850,10 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1459,7 +879,6 @@ export class PetApi { return deferred.promise; } - public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { const path = this.url + this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); @@ -1473,14 +892,10 @@ export class PetApi { throw new Error('Missing required parameter petId when calling deletePet'); } - - headerParams['api_key'] = apiKey; - let useFormData = false; - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -1489,13 +904,10 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1521,7 +933,6 @@ export class PetApi { return deferred.promise; } - 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)); @@ -1535,25 +946,17 @@ export class PetApi { throw new Error('Missing required parameter petId when calling uploadFile'); } - - let useFormData = false; - if (additionalMetadata !== undefined) { formParams['additionalMetadata'] = additionalMetadata; } - - if (file !== undefined) { formParams['file'] = file; } - useFormData = true; - - let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); let requestOptions: request.Options = { @@ -1562,12 +965,92 @@ export class PetApi { headers: headerParams, uri: path, json: true, - } - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +} +export class StoreApi { + protected basePath = 'http://petstore.swagger.io/v2'; + protected defaultHeaders : any = {}; + + + + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + + public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { + const path = this.url + this.basePath + '/store/inventory'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.api_key.applyToRequest(requestOptions); this.authentications.default.applyToRequest(requestOptions); @@ -1594,7 +1077,148 @@ export class PetApi { return deferred.promise; } + public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { + const path = this.url + this.basePath + '/store/order'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + let requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { + 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 + if (!orderId) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + + let useFormData = false; + + let deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + let requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; 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 + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + + let useFormData = false; + + let deferred = promise.defer<{ response: http.ClientResponse; body?: any; }>(); + + let requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } } - - - diff --git a/samples/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/StringUtil.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/StringUtil.java deleted file mode 100644 index c80bc8a1647..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/StringUtil.java +++ /dev/null @@ -1,42 +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 StringUtil { - /** - * Check if the given array contains the given value (with case-insensitive comparison). - * - * @param array The array - * @param value The value to search - * @return true if the array contains the value - */ - public static boolean containsIgnoreCase(String[] array, String value) { - for (String str : array) { - if (value == null && str == null) return true; - if (value != null && value.equalsIgnoreCase(str)) return true; - } - return false; - } - - /** - * Join an array of strings with the given separator. - *

- * Note: This might be replaced by utility method from commons-lang or guava someday - * if one of those libraries is added as dependency. - *

- * - * @param array The array of strings - * @param separator The separator - * @return the resulting string - */ - public static String join(String[] array, String separator) { - int len = array.length; - if (len == 0) return ""; - - StringBuilder out = new StringBuilder(); - out.append(array[0]); - for (int i = 1; i < len; i++) { - out.append(separator).append(array[i]); - } - return out.toString(); - } -} 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/client/model/Category.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Category.java deleted file mode 100644 index 0d1945b5804..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Category.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.swagger.client.model; - - - - -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 { - - private Long id = null; - private String name = null; - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("id") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("name") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - - @Override - public String toString() { - 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"); - return sb.toString(); - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Order.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Order.java deleted file mode 100644 index 2a3892f2918..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Order.java +++ /dev/null @@ -1,114 +0,0 @@ -package io.swagger.client.model; - -import java.util.Date; - - - -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 { - - private Long id = null; - private Long petId = null; - private Integer quantity = null; - private Date shipDate = null; - public enum StatusEnum { - placed, approved, delivered, - }; - private StatusEnum status = null; - private Boolean complete = null; - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("id") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("petId") - public Long getPetId() { - return petId; - } - public void setPetId(Long petId) { - this.petId = petId; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("quantity") - public Integer getQuantity() { - return quantity; - } - public void setQuantity(Integer quantity) { - this.quantity = quantity; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("shipDate") - public Date getShipDate() { - return shipDate; - } - public void setShipDate(Date shipDate) { - this.shipDate = shipDate; - } - - - /** - * Order Status - **/ - @ApiModelProperty(value = "Order Status") - @JsonProperty("status") - public StatusEnum getStatus() { - return status; - } - public void setStatus(StatusEnum status) { - this.status = status; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("complete") - public Boolean getComplete() { - return complete; - } - public void setComplete(Boolean complete) { - this.complete = complete; - } - - - - @Override - public String toString() { - 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"); - return sb.toString(); - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Pet.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Pet.java deleted file mode 100644 index 6cb7df1fde5..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Pet.java +++ /dev/null @@ -1,116 +0,0 @@ -package io.swagger.client.model; - -import io.swagger.client.model.Category; -import io.swagger.client.model.Tag; -import java.util.*; - - - -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 { - - private Long id = null; - private Category category = null; - private String name = null; - private List photoUrls = new ArrayList(); - private List tags = new ArrayList(); - public enum StatusEnum { - available, pending, sold, - }; - private StatusEnum status = null; - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("id") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("category") - public Category getCategory() { - return category; - } - public void setCategory(Category category) { - this.category = category; - } - - - /** - **/ - @ApiModelProperty(required = true, value = "") - @JsonProperty("name") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - /** - **/ - @ApiModelProperty(required = true, value = "") - @JsonProperty("photoUrls") - public List getPhotoUrls() { - return photoUrls; - } - public void setPhotoUrls(List photoUrls) { - this.photoUrls = photoUrls; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("tags") - public List getTags() { - return tags; - } - public void setTags(List tags) { - this.tags = tags; - } - - - /** - * pet status in the store - **/ - @ApiModelProperty(value = "pet status in the store") - @JsonProperty("status") - public StatusEnum getStatus() { - return status; - } - public void setStatus(StatusEnum status) { - this.status = status; - } - - - - @Override - public String toString() { - 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"); - return sb.toString(); - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Tag.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Tag.java deleted file mode 100644 index fe212ea8ab6..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/Tag.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.swagger.client.model; - - - - -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 { - - private Long id = null; - private String name = null; - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("id") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("name") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - - @Override - public String toString() { - 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"); - return sb.toString(); - } -} diff --git a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/User.java b/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/User.java deleted file mode 100644 index 5b9230b8e01..00000000000 --- a/samples/server/petstore/jaxrs/src/test/java/io/swagger/client/model/User.java +++ /dev/null @@ -1,138 +0,0 @@ -package io.swagger.client.model; - - - - -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 { - - private Long id = null; - private String username = null; - private String firstName = null; - private String lastName = null; - private String email = null; - private String password = null; - private String phone = null; - private Integer userStatus = null; - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("id") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("username") - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("firstName") - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("lastName") - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("email") - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("password") - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("phone") - public String getPhone() { - return phone; - } - public void setPhone(String phone) { - this.phone = phone; - } - - - /** - * User Status - **/ - @ApiModelProperty(value = "User Status") - @JsonProperty("userStatus") - public Integer getUserStatus() { - return userStatus; - } - public void setUserStatus(Integer userStatus) { - this.userStatus = userStatus; - } - - - - @Override - public String toString() { - 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"); - return sb.toString(); - } -} 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