syntax, String definition) {
+ this.syntax = syntax;
+ this.definition = definition;
+ }
+
+ public abstract Boolean matches(String relativePath);
+
+ public String getDefinition() {
+ return this.definition;
+ }
+
+ protected String getPattern() {
+ if(syntax == null) return this.definition;
+
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < syntax.size(); i++) {
+ Part current = syntax.get(i);
+
+ switch(current.getToken()){
+ case MATCH_ALL:
+ case MATCH_ANY:
+ case ESCAPED_EXCLAMATION:
+ case ESCAPED_SPACE:
+ case PATH_DELIM:
+ case TEXT:
+ case DIRECTORY_MARKER:
+ sb.append(current.getValue());
+ break;
+ case NEGATE:
+ case ROOTED_MARKER:
+ case COMMENT:
+ break;
+ }
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Whether or not the rule should be negated. !foo means foo should be removed from previous matches.
+ * Example: **\/*.bak excludes all backup. Adding !/test.bak will include test.bak in the project root.
+ *
+ * NOTE: It is not possible to re-include a file if a parent directory of that file is excluded.
+ */
+ public Boolean getNegated() {
+ return this.syntax != null && this.syntax.size() > 0 && this.syntax.get(0).getToken() == IgnoreLineParser.Token.NEGATE;
+ }
+
+ public Operation evaluate(String relativePath) {
+ if (Boolean.TRUE.equals(matches(relativePath))) {
+ if(Boolean.TRUE.equals(this.getNegated())) {
+ return this.getIncludeOperation();
+ }
+ return this.getExcludeOperation();
+ }
+ return Operation.NOOP;
+ }
+
+ protected Operation getIncludeOperation(){ return Operation.INCLUDE; }
+ protected Operation getExcludeOperation(){ return Operation.EXCLUDE; }
+
+ public static Rule create(String definition) {
+ // NOTE: Comments that start with a : (e.g. //:) are pulled from git documentation for .gitignore
+ // see: https://github.com/git/git/blob/90f7b16b3adc78d4bbabbd426fb69aa78c714f71/Documentation/gitignore.txt
+ Rule rule = null;
+ if (definition.equals(".")) {
+ return new InvalidRule(null, definition, "Pattern '.' is invalid.");
+ } else if (definition.equals("!.")) {
+ return new InvalidRule(null, definition, "Pattern '!.' is invalid.");
+ } else if (definition.startsWith("..")) {
+ return new InvalidRule(null, definition, "Pattern '..' is invalid.");
+ }
+
+ try {
+ List result = IgnoreLineParser.parse(definition);
+
+ Boolean directoryOnly = null;
+ if (result.size() == 0) {
+ return rule;
+ } else if (result.size() == 1) {
+ // single-character filename only
+ Part part = result.get(0);
+ if (IgnoreLineParser.Token.MATCH_ANY.equals(part.getToken())) {
+ rule = new RootedFileRule(result, definition);
+ } else {
+ rule = new FileRule(result, definition);
+ }
+ } else {
+ IgnoreLineParser.Token head = result.get(0).getToken();
+
+ //: An optional prefix "`!`" which negates the pattern; any
+ //: matching file excluded by a previous pattern will become
+ //: included again. It is not possible to re-include a file if a parent
+ //: directory of that file is excluded. Git doesn't list excluded
+ //: directories for performance reasons, so any patterns on contained
+ //: files have no effect, no matter where they are defined.
+ //: Put a backslash ("`\`") in front of the first "`!`" for patterns
+ //: that begin with a literal "`!`", for example, "`\!important!.txt`".
+ // see this.getNegated();
+
+ //: If the pattern ends with a slash, it is removed for the
+ //: purpose of the following description, but it would only find
+ //: a match with a directory. In other words, `foo/` will match a
+ //: directory `foo` and paths underneath it, but will not match a
+ //: regular file or a symbolic link `foo` (this is consistent
+ //: with the way how pathspec works in general in Git).
+ directoryOnly = IgnoreLineParser.Token.DIRECTORY_MARKER.equals(result.get(result.size() - 1).getToken());
+
+ if (directoryOnly) {
+ rule = new DirectoryRule(result, definition);
+ } else if (IgnoreLineParser.Token.PATH_DELIM.equals(head)) {
+ //: A leading slash matches the beginning of the pathname.
+ //: For example, "/{asterisk}.c" matches "cat-file.c" but not
+ //: "mozilla-sha1/sha1.c".
+ rule = new RootedFileRule(result, definition);
+ } else {
+ // case 1
+ //: If the pattern does not contain a slash '/', Git treats it as
+ //: a shell glob pattern and checks for a match against the
+ //: pathname relative to the location of the `.gitignore` file
+ //: (relative to the toplevel of the work tree if not from a
+ //: `.gitignore` file).
+
+ // case 2
+ //: Otherwise, Git treats the pattern as a shell glob suitable
+ //: for consumption by fnmatch(3) with the FNM_PATHNAME flag:
+ //: wildcards in the pattern will not match a / in the pathname.
+ //: For example, "Documentation/{asterisk}.html" matches
+ //: "Documentation/git.html" but not "Documentation/ppc/ppc.html"
+ //: or "tools/perf/Documentation/perf.html".
+
+
+ // case 3
+ //: Two consecutive asterisks ("`**`") in patterns matched against
+ //: full pathname may have special meaning:
+ //:
+ //: - A leading "`**`" followed by a slash means match in all
+ //: directories. For example, "`**/foo`" matches file or directory
+ //: "`foo`" anywhere, the same as pattern "`foo`". "`**/foo/bar`"
+ //: matches file or directory "`bar`" anywhere that is directly
+ //: under directory "`foo`".
+ //:
+ //: - A trailing "`/**`" matches everything inside. For example,
+ //: "`abc/**`" matches all files inside directory "`abc`", relative
+ //: to the location of the `.gitignore` file, with infinite depth.
+ //:
+ //: - A slash followed by two consecutive asterisks then a slash
+ //: matches zero or more directories. For example, "`a/**/b`"
+ //: matches "`a/b`", "`a/x/b`", "`a/x/y/b`" and so on.
+ //:
+ //: - Other consecutive asterisks are considered invalid.
+ rule = new FileRule(result, definition);
+ }
+
+ }
+ } catch (ParserException e) {
+ e.printStackTrace();
+ return new InvalidRule(null, definition, e.getMessage());
+ }
+
+ return rule;
+ }
+}
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java
index 128686b615b..386e37e3f0d 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java
@@ -77,6 +77,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
"string",
"bool?",
"double?",
+ "decimal?",
"int?",
"long?",
"float?",
@@ -112,7 +113,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
typeMapping.put("float", "float?");
typeMapping.put("long", "long?");
typeMapping.put("double", "double?");
- typeMapping.put("number", "double?");
+ typeMapping.put("number", "decimal?");
typeMapping.put("datetime", "DateTime?");
typeMapping.put("date", "DateTime?");
typeMapping.put("file", "System.IO.Stream");
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java
index 99fab6e5444..fbb2831ab8b 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java
@@ -8,10 +8,12 @@ import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.util.*;
-public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen
-{
+public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen {
/**
* Name of the sub-directory in "src/main/resource" where to find the
* Mustache template for the JAX-RS Codegen.
@@ -19,10 +21,13 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen
protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS";
protected String implFolder = "src/main/java";
protected String title = "Swagger Server";
+ static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class);
public AbstractJavaJAXRSServerCodegen()
{
super();
+ dateLibrary = "legacy";
+ apiTestTemplateFiles.clear(); // TODO: add test template
}
@Override
@@ -198,4 +203,5 @@ public abstract class AbstractJavaJAXRSServerCodegen extends JavaClientCodegen
public boolean shouldOverwrite(String filename) {
return super.shouldOverwrite(filename) && !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java");
}
+
}
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 9e30ae657c8..cc41f3ea297 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
@@ -1,62 +1,73 @@
package io.swagger.codegen.languages;
-import io.swagger.codegen.*;
-import io.swagger.models.properties.*;
-
-import java.util.*;
-import java.io.File;
-
import org.apache.commons.lang3.StringUtils;
+import java.io.File;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+
+import io.swagger.codegen.CliOption;
+import io.swagger.codegen.CodegenConfig;
+import io.swagger.codegen.CodegenConstants;
+import io.swagger.codegen.CodegenProperty;
+import io.swagger.codegen.CodegenType;
+import io.swagger.codegen.DefaultCodegen;
+import io.swagger.models.properties.ArrayProperty;
+import io.swagger.models.properties.FileProperty;
+import io.swagger.models.properties.MapProperty;
+import io.swagger.models.properties.Property;
+
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String modelPropertyNaming= "camelCase";
protected Boolean supportsES6 = true;
- public AbstractTypeScriptClientCodegen() {
- super();
- supportsInheritance = true;
- setReservedWordsLowerCase(Arrays.asList(
- // local variable names used in API methods (endpoints)
- "varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred",
- "requestOptions",
- // Typescript reserved words
- "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"));
+ public AbstractTypeScriptClientCodegen() {
+ super();
+ supportsInheritance = true;
+ setReservedWordsLowerCase(Arrays.asList(
+ // local variable names used in API methods (endpoints)
+ "varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred",
+ "requestOptions",
+ // Typescript reserved words
+ "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",
- "String",
- "boolean",
- "Boolean",
- "Double",
- "Integer",
- "Long",
- "Float",
- "Object",
+ languageSpecificPrimitives = new HashSet(Arrays.asList(
+ "string",
+ "String",
+ "boolean",
+ "Boolean",
+ "Double",
+ "Integer",
+ "Long",
+ "Float",
+ "Object",
"Array",
"Date",
"number",
"any"
- ));
- instantiationTypes.put("array", "Array");
+ ));
+ instantiationTypes.put("array", "Array");
- typeMapping = new HashMap();
- typeMapping.put("Array", "Array");
- typeMapping.put("array", "Array");
- typeMapping.put("List", "Array");
- typeMapping.put("boolean", "boolean");
- typeMapping.put("string", "string");
- typeMapping.put("int", "number");
- typeMapping.put("float", "number");
- typeMapping.put("number", "number");
- typeMapping.put("long", "number");
- typeMapping.put("short", "number");
- typeMapping.put("char", "string");
- typeMapping.put("double", "number");
- typeMapping.put("object", "any");
- typeMapping.put("integer", "number");
- typeMapping.put("Map", "any");
- typeMapping.put("DateTime", "Date");
+ typeMapping = new HashMap();
+ typeMapping.put("Array", "Array");
+ typeMapping.put("array", "Array");
+ typeMapping.put("List", "Array");
+ typeMapping.put("boolean", "boolean");
+ typeMapping.put("string", "string");
+ typeMapping.put("int", "number");
+ typeMapping.put("float", "number");
+ typeMapping.put("number", "number");
+ typeMapping.put("long", "number");
+ typeMapping.put("short", "number");
+ typeMapping.put("char", "string");
+ typeMapping.put("double", "number");
+ typeMapping.put("object", "any");
+ typeMapping.put("integer", "number");
+ typeMapping.put("Map", "any");
+ typeMapping.put("DateTime", "Date");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "string");
@@ -66,7 +77,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase"));
cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue("false"));
- }
+ }
@Override
public void processOpts() {
@@ -104,24 +115,24 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
@Override
- public String toParamName(String name) {
- // replace - with _ e.g. created-at => created_at
- name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
+ public String toParamName(String name) {
+ // replace - with _ e.g. created-at => created_at
+ name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
- // if it's all uppper case, do nothing
- if (name.matches("^[A-Z_]*$"))
- return name;
+ // if it's all uppper case, do nothing
+ if (name.matches("^[A-Z_]*$"))
+ return name;
- // camelize the variable name
- // pet_id => petId
- name = camelize(name, true);
+ // camelize the variable name
+ // pet_id => petId
+ name = camelize(name, true);
- // for reserved word or word starting with number, append _
- if (isReservedWord(name) || name.matches("^\\d.*"))
- name = escapeReservedWord(name);
+ // for reserved word or word starting with number, append _
+ if (isReservedWord(name) || name.matches("^\\d.*"))
+ name = escapeReservedWord(name);
- return name;
- }
+ return name;
+ }
@Override
public String toVarName(String name) {
@@ -130,70 +141,70 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
}
@Override
- public String toModelName(String name) {
- name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
+ public String toModelName(String name) {
+ name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
- if (!StringUtils.isEmpty(modelNamePrefix)) {
- name = modelNamePrefix + "_" + name;
+ if (!StringUtils.isEmpty(modelNamePrefix)) {
+ name = modelNamePrefix + "_" + name;
+ }
+
+ if (!StringUtils.isEmpty(modelNameSuffix)) {
+ name = name + "_" + modelNameSuffix;
+ }
+
+ // model name cannot use reserved keyword, e.g. return
+ if (isReservedWord(name)) {
+ String modelName = camelize("model_" + name);
+ LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName);
+ return modelName;
+ }
+
+ // model name starts with number
+ if (name.matches("^\\d.*")) {
+ String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize)
+ LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
+ return modelName;
+ }
+
+ // camelize the model name
+ // phone_number => PhoneNumber
+ return camelize(name);
}
- if (!StringUtils.isEmpty(modelNameSuffix)) {
- name = name + "_" + modelNameSuffix;
+ @Override
+ public String toModelFilename(String name) {
+ // should be the same as the model name
+ return toModelName(name);
+ }
+
+ @Override
+ public String getTypeDeclaration(Property p) {
+ if (p instanceof ArrayProperty) {
+ ArrayProperty ap = (ArrayProperty) p;
+ Property inner = ap.getItems();
+ return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
+ } else if (p instanceof MapProperty) {
+ MapProperty mp = (MapProperty) p;
+ Property inner = mp.getAdditionalProperties();
+ return "{ [key: string]: "+ getTypeDeclaration(inner) + "; }";
+ } else if (p instanceof FileProperty) {
+ return "any";
}
+ return super.getTypeDeclaration(p);
+ }
- // model name cannot use reserved keyword, e.g. return
- if (isReservedWord(name)) {
- String modelName = camelize("model_" + name);
- LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName);
- return modelName;
- }
-
- // model name starts with number
- if (name.matches("^\\d.*")) {
- String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize)
- LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
- return modelName;
- }
-
- // camelize the model name
- // phone_number => PhoneNumber
- return camelize(name);
- }
-
- @Override
- public String toModelFilename(String name) {
- // should be the same as the model name
- return toModelName(name);
- }
-
- @Override
- public String getTypeDeclaration(Property p) {
- if (p instanceof ArrayProperty) {
- ArrayProperty ap = (ArrayProperty) p;
- Property inner = ap.getItems();
- return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
- } else if (p instanceof MapProperty) {
- MapProperty mp = (MapProperty) p;
- Property inner = mp.getAdditionalProperties();
- return "{ [key: string]: "+ getTypeDeclaration(inner) + "; }";
- } else if (p instanceof FileProperty) {
- return "any";
- }
- return super.getTypeDeclaration(p);
- }
-
- @Override
- public String getSwaggerType(Property p) {
- String swaggerType = super.getSwaggerType(p);
- String type = null;
- if (typeMapping.containsKey(swaggerType)) {
- type = typeMapping.get(swaggerType);
- if (languageSpecificPrimitives.contains(type))
- return type;
- } else
- type = swaggerType;
- return toModelName(type);
- }
+ @Override
+ public String getSwaggerType(Property p) {
+ String swaggerType = super.getSwaggerType(p);
+ String type = null;
+ if (typeMapping.containsKey(swaggerType)) {
+ type = typeMapping.get(swaggerType);
+ if (languageSpecificPrimitives.contains(type))
+ return type;
+ } else
+ type = swaggerType;
+ return toModelName(type);
+ }
@Override
public String toOperationId(String operationId) {
@@ -217,8 +228,8 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
this.modelPropertyNaming = naming;
} else {
throw new IllegalArgumentException("Invalid model property naming '" +
- naming + "'. Must be 'original', 'camelCase', " +
- "'PascalCase' or 'snake_case'");
+ naming + "'. Must be 'original', 'camelCase', " +
+ "'PascalCase' or 'snake_case'");
}
}
@@ -232,9 +243,9 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
case camelCase: return camelize(name, true);
case PascalCase: return camelize(name);
case snake_case: return underscore(name);
- default: throw new IllegalArgumentException("Invalid model property naming '" +
- name + "'. Must be 'original', 'camelCase', " +
- "'PascalCase' or 'snake_case'");
+ default: throw new IllegalArgumentException("Invalid model property naming '" +
+ name + "'. Must be 'original', 'camelCase', " +
+ "'PascalCase' or 'snake_case'");
}
}
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 282c4d88647..d11cc6ce0a3 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
@@ -33,6 +33,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
// requestPackage and authPackage are used by the "volley" template/library
protected String requestPackage = "io.swagger.client.request";
protected String authPackage = "io.swagger.client.auth";
+ protected String gradleWrapperPackage = "gradle.wrapper";
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
@@ -89,8 +90,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
cliOptions.add(CliOption.newBoolean(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin.")
.defaultValue(Boolean.TRUE.toString()));
- supportedLibraries.put("", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1");
- supportedLibraries.put("volley", "HTTP client: Volley 1.0.19");
+ supportedLibraries.put("volley", "HTTP client: Volley 1.0.19 (default)");
+ supportedLibraries.put("httpclient", "HTTP client: Apache HttpClient 4.3.6. JSON processing: Gson 2.3.1. IMPORTANT: Android client using HttpClient is not actively maintained and will be depecreated in the next major release.");
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setEnum(supportedLibraries);
cliOptions.add(library);
@@ -382,23 +383,26 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
additionalProperties.put( "modelDocPath", modelDocPath );
if (StringUtils.isEmpty(getLibrary())) {
- modelDocTemplateFiles.put( "model_doc.mustache", ".md" );
- apiDocTemplateFiles.put( "api_doc.mustache", ".md" );
- //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md"));
- //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md"));
- supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
- addSupportingFilesForDefault();
- } else if ("volley".equals(getLibrary())) {
- modelDocTemplateFiles.put( "model_doc.mustache", ".md" );
- apiDocTemplateFiles.put( "api_doc.mustache", ".md" );
- supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
- //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md"));
- //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md"));
- addSupportingFilesForVolley();
+ setLibrary("volley"); // set volley as the default library
}
+
+ // determine which file (mustache) to add based on library
+ if ("volley".equals(getLibrary())) {
+ addSupportingFilesForVolley();
+ } else if ("httpclient".equals(getLibrary())) {
+ addSupportingFilesForHttpClient();
+ } else {
+ throw new IllegalArgumentException("Invalid 'library' option specified: '" + getLibrary() + "'. Must be 'httpclient' or 'volley' (default)");
+ }
+
}
- private void addSupportingFilesForDefault() {
+ private void addSupportingFilesForHttpClient() {
+ // documentation files
+ modelDocTemplateFiles.put( "model_doc.mustache", ".md" );
+ apiDocTemplateFiles.put( "api_doc.mustache", ".md" );
+ supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
+
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle"));
@@ -415,9 +419,25 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
(sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Pair.java"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
+
+ // gradle wrapper files
+ supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew" ));
+ supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat" ));
+ supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache",
+ gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties" ));
+ supportingFiles.add(new SupportingFile( "gradle-wrapper.jar",
+ gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar" ));
+
}
private void addSupportingFilesForVolley() {
+ // documentation files
+ modelDocTemplateFiles.put( "model_doc.mustache", ".md" );
+ apiDocTemplateFiles.put( "api_doc.mustache", ".md" );
+ supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
+
+ supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
+ supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
// supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle"));
@@ -446,6 +466,14 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi
(sourceFolder + File.separator + authPackage).replace(".", File.separator), "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/authentication.mustache",
(sourceFolder + File.separator + authPackage).replace(".", File.separator), "Authentication.java"));
+
+ // gradle wrapper files
+ supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew" ));
+ supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat" ));
+ supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache",
+ gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.properties" ));
+ supportingFiles.add(new SupportingFile( "gradle-wrapper.jar",
+ gradleWrapperPackage.replace(".", File.separator), "gradle-wrapper.jar" ));
}
public Boolean getUseAndroidMavenGradlePlugin() {
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 2fc8738f067..4265f67709c 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
@@ -137,6 +137,11 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
@Override
public void processOpts() {
super.processOpts();
+ Boolean excludeTests = false;
+
+ if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) {
+ excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString());
+ }
apiPackage = "Api";
modelPackage = "Model";
@@ -218,6 +223,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
binRelativePath += "vendor";
additionalProperties.put("binRelativePath", binRelativePath);
+ supportingFiles.add(new SupportingFile("IApiAccessor.mustache",
+ clientPackageDir, "IApiAccessor.cs"));
supportingFiles.add(new SupportingFile("Configuration.mustache",
clientPackageDir, "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache",
@@ -226,17 +233,29 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
clientPackageDir, "ApiException.cs"));
supportingFiles.add(new SupportingFile("ApiResponse.mustache",
clientPackageDir, "ApiResponse.cs"));
+ supportingFiles.add(new SupportingFile("ExceptionFactory.mustache",
+ clientPackageDir, "ExceptionFactory.cs"));
supportingFiles.add(new SupportingFile("compile.mustache", "", "build.bat"));
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "build.sh"));
+ // shell script to run the nunit test
+ supportingFiles.add(new SupportingFile("mono_nunit_test.mustache", "", "mono_nunit_test.sh"));
// copy package.config to nuget's standard location for project-level installs
supportingFiles.add(new SupportingFile("packages.config.mustache", packageFolder + File.separator, "packages.config"));
- supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config"));
+ // .travis.yml for travis-ci.org CI
+ supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml"));
+
+ if(Boolean.FALSE.equals(excludeTests)) {
+ supportingFiles.add(new SupportingFile("packages_test.config.mustache", testPackageFolder + File.separator, "packages.config"));
+ }
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
+ // apache v2 license
+ // UPDATE (20160612) no longer needed as the Apache v2 LICENSE is added globally
+ //supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE"));
if (optionalAssemblyInfoFlag) {
supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", packageFolder + File.separator + "Properties", "AssemblyInfo.cs"));
@@ -245,11 +264,9 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln"));
supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, packageName + ".csproj"));
- // TODO: Check if test project output is enabled, partially related to #2506. Should have options for:
- // 1) No test project
- // 2) No model tests
- // 3) No api tests
- supportingFiles.add(new SupportingFile("TestProject.mustache", testPackageFolder, testPackageName + ".csproj"));
+ if(Boolean.FALSE.equals(excludeTests)) {
+ supportingFiles.add(new SupportingFile("TestProject.mustache", testPackageFolder, testPackageName + ".csproj"));
+ }
}
additionalProperties.put("apiDocPath", apiDocPath);
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java
index 4e34424eab7..efcde6d8c41 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java
@@ -146,7 +146,9 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go"));
supportingFiles.add(new SupportingFile("api_client.mustache", "", "api_client.go"));
supportingFiles.add(new SupportingFile("api_response.mustache", "", "api_response.go"));
+ supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
+ supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE"));
}
@Override
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java
index 2812d2a301b..5b26662531f 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GroovyClientCodegen.java
@@ -19,6 +19,7 @@ public class GroovyClientCodegen extends JavaClientCodegen {
outputFolder = "generated-code/groovy";
modelTemplateFiles.put("model.mustache", ".groovy");
apiTemplateFiles.put(templateFileName, ".groovy");
+ apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "Groovy";
apiPackage = "io.swagger.api";
@@ -26,6 +27,7 @@ public class GroovyClientCodegen extends JavaClientCodegen {
configPackage = "io.swagger.configuration";
invokerPackage = "io.swagger.api";
artifactId = "swagger-spring-mvc-server";
+ dateLibrary = "legacy";
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java
index 324ca56e70b..08147f60f36 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java
@@ -7,10 +7,8 @@ import io.swagger.models.properties.*;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Swagger;
-import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.util.*;
-import java.io.File;
public class HaskellServantCodegen extends DefaultCodegen implements CodegenConfig {
@@ -432,7 +430,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf
case "pipes": return "(QueryList 'PipeSeparated (" + type + "))";
case "multi": return "(QueryList 'MultiParamArray (" + type + "))";
default:
- throw new NotImplementedException();
+ throw new UnsupportedOperationException();
}
}
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 bc839f07d18..c80bb0ed23f 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
@@ -30,13 +30,16 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String RETROFIT_1 = "retrofit";
public static final String RETROFIT_2 = "retrofit2";
- protected String dateLibrary = "default";
+ protected String dateLibrary = "joda";
protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-java-client";
protected String artifactVersion = "1.0.0";
protected String projectFolder = "src" + File.separator + "main";
+ protected String projectTestFolder = "src" + File.separator + "test";
protected String sourceFolder = projectFolder + File.separator + "java";
+ protected String testFolder = projectTestFolder + File.separator + "java";
+ protected String gradleWrapperPackage = "gradle.wrapper";
protected String localVariablePrefix = "";
protected boolean fullJavaUtil;
protected String javaUtilPrefix = "";
@@ -52,6 +55,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
outputFolder = "generated-code" + File.separator + "java";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
+ apiTestTemplateFiles.put("api_test.mustache", ".java");
embeddedTemplateDir = templateDir = "Java";
apiPackage = "io.swagger.client.api";
modelPackage = "io.swagger.client.model";
@@ -107,12 +111,12 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));
cliOptions.add(new CliOption("hideGenerationTimestamp", "hides the timestamp when files were generated"));
- supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2");
- supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1");
- 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_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
- supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.1). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.2)");
+ supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.19.1. JSON processing: Jackson 2.7.0");
+ supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.16.0. JSON processing: Jackson 2.7.0");
+ supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.22.2. JSON processing: Jackson 2.7.0");
+ supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.6.2");
+ supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
+ supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.2.0. JSON processing: Gson 2.6.1 (Retrofit 2.0.2). Enable the RxJava adapter using '-DuseRxJava=true'. (RxJava 1.1.3)");
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
@@ -124,6 +128,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
Map dateOptions = new HashMap();
dateOptions.put("java8", "Java 8 native");
dateOptions.put("joda", "Joda");
+ dateOptions.put("legacy", "Legacy java.util.Date");
dateLibrary.setEnum(dateOptions);
cliOptions.add(dateLibrary);
@@ -257,12 +262,22 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
writeOptional(outputFolder, new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
writeOptional(outputFolder, new SupportingFile("gradle.properties.mustache", "", "gradle.properties"));
writeOptional(outputFolder, new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
- writeOptional(outputFolder, new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
+ supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/");
if ("feign".equals(getLibrary())) {
supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java"));
+
+ //gradleWrapper files
+ supportingFiles.add( new SupportingFile( "gradlew.mustache", "", "gradlew") );
+ supportingFiles.add( new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
+ supportingFiles.add( new SupportingFile( "gradle-wrapper.properties.mustache",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
+ supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
+ // "build.sbt" is for development with SBT
+ supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
}
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
@@ -281,6 +296,14 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
// generate markdown docs
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
+
+ //gradleWrapper files
+ supportingFiles.add( new SupportingFile( "gradlew.mustache", "", "gradlew") );
+ supportingFiles.add( new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
+ supportingFiles.add( new SupportingFile( "gradle-wrapper.properties.mustache",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
+ supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
} else if ("okhttp-gson".equals(getLibrary())) {
// generate markdown docs
modelDocTemplateFiles.put("model_doc.mustache", ".md");
@@ -293,14 +316,49 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java"));
// "build.sbt" is for development with SBT
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
+
+ //gradleWrapper files
+ supportingFiles.add( new SupportingFile( "gradlew.mustache", "", "gradlew") );
+ supportingFiles.add( new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
+ supportingFiles.add( new SupportingFile( "gradle-wrapper.properties.mustache",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
+ supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
} else if (usesAnyRetrofitLibrary()) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java"));
+
+ //gradleWrapper files
+ supportingFiles.add( new SupportingFile( "gradlew.mustache", "", "gradlew") );
+ supportingFiles.add( new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
+ supportingFiles.add( new SupportingFile( "gradle-wrapper.properties.mustache",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
+ supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
+ // "build.sbt" is for development with SBT
+ supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
+
+ //generate markdown docs for retrofit2
+ if ( usesRetrofit2Library() ){
+ modelDocTemplateFiles.put("model_doc.mustache", ".md");
+ apiDocTemplateFiles.put("api_doc.mustache", ".md");
+ }
+
} else if("jersey2".equals(getLibrary())) {
// generate markdown docs
modelDocTemplateFiles.put("model_doc.mustache", ".md");
apiDocTemplateFiles.put("api_doc.mustache", ".md");
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
+
+ //gradleWrapper files
+ supportingFiles.add( new SupportingFile( "gradlew.mustache", "", "gradlew") );
+ supportingFiles.add( new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
+ supportingFiles.add( new SupportingFile( "gradle-wrapper.properties.mustache",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
+ supportingFiles.add( new SupportingFile( "gradle-wrapper.jar",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
+ // "build.sbt" is for development with SBT
+ supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
}
if(additionalProperties.containsKey(DATE_LIBRARY)) {
@@ -366,6 +424,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', '/');
}
+ @Override
+ public String apiTestFileFolder() {
+ return outputFolder + "/" + testFolder + "/" + apiPackage().replace('.', '/');
+ }
+
@Override
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', '/');
@@ -391,6 +454,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
return toModelName(name);
}
+ @Override
+ public String toApiTestFilename(String name) {
+ return toApiName(name) + "Test";
+ }
+
@Override
public String toVarName(String name) {
// sanitize name
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java
index 0cf59e5faa7..8a08bf758a3 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java
@@ -25,9 +25,11 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen {
sourceFolder = "src/gen/java";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
+ apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaInflector";
invokerPackage = "io.swagger.handler";
artifactId = "swagger-inflector-server";
+ dateLibrary = "legacy";
apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler");
modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model");
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java
index 52f3eb8d844..72f969403bf 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java
@@ -6,6 +6,8 @@ import io.swagger.models.Operation;
import java.io.File;
import java.util.*;
+import org.apache.commons.lang3.StringUtils;
+
public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
public JavaJerseyServerCodegen() {
super();
@@ -26,7 +28,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
additionalProperties.put("title", title);
- embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey1_18";
+ embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME;
for ( int i = 0; i < cliOptions.size(); i++ ) {
if ( CodegenConstants.LIBRARY.equals(cliOptions.get(i).getOpt()) ) {
@@ -36,13 +38,11 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
}
CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
- library.setDefault(DEFAULT_LIBRARY);
- Map supportedLibraries = new LinkedHashMap();
-
- supportedLibraries.put(DEFAULT_LIBRARY, "Jersey core 1.18.1");
- supportedLibraries.put("jersey2", "Jersey core 2.x");
+ supportedLibraries.put("jersey1", "Jersey core 1.x");
+ supportedLibraries.put("jersey2", "Jersey core 2.x (default)");
library.setEnum(supportedLibraries);
+ library.setDefault("jersey1");
cliOptions.add(library);
cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC));
@@ -73,16 +73,35 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
public void processOpts() {
super.processOpts();
+ // set jersey2 as default
+ if (StringUtils.isEmpty(library)) {
+ setLibrary("jersey2");
+ }
+
+ supportingFiles.clear();
+
// clear model and api doc template as this codegen
// does not support auto-generated markdown doc at the moment
modelDocTemplateFiles.remove("model_doc.mustache");
apiDocTemplateFiles.remove("api_doc.mustache");
- if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER) ) {
+ if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) {
implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER);
}
- supportingFiles.clear();
+ if (additionalProperties.containsKey("dateLibrary")) {
+ setDateLibrary(additionalProperties.get("dateLibrary").toString());
+ additionalProperties.put(dateLibrary, "true");
+ }
+
+ if ("joda".equals(dateLibrary)) {
+ supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java"));
+ supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java"));
+ } else if ( "java8".equals(dateLibrary) ) {
+ supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java"));
+ supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java"));
+ }
+
writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml"));
writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("ApiException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "ApiException.java"));
@@ -91,40 +110,8 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen {
supportingFiles.add(new SupportingFile("NotFoundException.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java"));
supportingFiles.add(new SupportingFile("jacksonJsonProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JacksonJsonProvider.java"));
writeOptional(outputFolder, new SupportingFile("bootstrap.mustache", (implFolder + '/' + apiPackage).replace(".", "/"), "Bootstrap.java"));
-
writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java"));
-
- if ( additionalProperties.containsKey("dateLibrary") ) {
- setDateLibrary(additionalProperties.get("dateLibrary").toString());
- additionalProperties.put(dateLibrary, "true");
- }
- if(DEFAULT_LIBRARY.equals(library) || library == null) {
- if(templateDir.startsWith(JAXRS_TEMPLATE_DIRECTORY_NAME)) {
- // set to the default location
- templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey1_18";
- }
- else {
- templateDir += File.separator + "jersey1_18";
- }
- }
- if("jersey2".equals(library)) {
- if(templateDir.startsWith(JAXRS_TEMPLATE_DIRECTORY_NAME)) {
- // set to the default location
- templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "jersey2";
- }
- else {
- templateDir += File.separator + "jersey2";
- }
- }
-
- if ( "joda".equals(dateLibrary) ) {
- supportingFiles.add(new SupportingFile("JodaDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaDateTimeProvider.java"));
- supportingFiles.add(new SupportingFile("JodaLocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "JodaLocalDateProvider.java"));
- } else if ( "java8".equals(dateLibrary) ) {
- supportingFiles.add(new SupportingFile("LocalDateTimeProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateTimeProvider.java"));
- supportingFiles.add(new SupportingFile("LocalDateProvider.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "LocalDateProvider.java"));
- }
}
@Override
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java
index b919430035d..4c13fd50f0b 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java
@@ -31,8 +31,10 @@ public class JavaResteasyServerCodegen extends JavaClientCodegen implements Code
apiTemplateFiles.put("apiService.mustache", ".java");
apiTemplateFiles.put("apiServiceImpl.mustache", ".java");
apiTemplateFiles.put("apiServiceFactory.mustache", ".java");
+ apiTestTemplateFiles.clear(); // TODO: add test template
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
+ dateLibrary = "legacy";
additionalProperties.put("title", title);
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 46b6083e2e4..cc1e77649e5 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
@@ -1,14 +1,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.CodegenOperation;
-import io.swagger.codegen.CodegenParameter;
-import io.swagger.codegen.CodegenProperty;
-import io.swagger.codegen.CodegenType;
-import io.swagger.codegen.DefaultCodegen;
-import io.swagger.codegen.SupportingFile;
+import io.swagger.codegen.*;
+import io.swagger.models.Model;
import io.swagger.models.properties.*;
import java.io.File;
@@ -26,10 +19,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String POD_NAME = "podName";
public static final String AUTHOR_NAME = "authorName";
public static final String AUTHOR_EMAIL = "authorEmail";
- public static final String GIT_REPO_URL = "gitRepoURL";
public static final String LICENSE = "license";
-
- public static final String BinaryDataType = "ObjcClientCodegenBinaryData";
+ public static final String GIT_REPO_URL = "gitRepoURL";
+ public static final String DEFAULT_LICENSE = "Apache License, Version 2.0";
+ public static final String CORE_DATA = "coreData";
protected Set foundationClasses = new HashSet();
protected String podName = "SwaggerClient";
@@ -37,11 +30,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String classPrefix = "SWG";
protected String authorName = "Swagger";
protected String authorEmail = "apiteam@swagger.io";
- protected String license = "MIT";
+ protected String license = DEFAULT_LICENSE;
protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen";
protected String[] specialWords = {"new", "copy"};
protected String apiDocPath = "docs/";
protected String modelDocPath = "docs/";
+ protected String modelFilesPath = "Model/";
+ protected String coreFilesPath = "Core/";
+ protected String apiFilesPath = "Api/";
+
+ protected boolean generateCoreData = false;
protected Set advancedMapingTypes = new HashSet();
@@ -70,8 +68,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
defaultIncludes.add("NSDictionary");
defaultIncludes.add("NSMutableArray");
defaultIncludes.add("NSMutableDictionary");
-
- defaultIncludes.add(BinaryDataType);
+ defaultIncludes.add("NSManagedObject");
+ defaultIncludes.add("NSData");
advancedMapingTypes.add("NSDictionary");
advancedMapingTypes.add("NSArray");
@@ -88,6 +86,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
languageSpecificPrimitives.add("NSString");
languageSpecificPrimitives.add("NSObject");
languageSpecificPrimitives.add("NSDate");
+ languageSpecificPrimitives.add("NSData");
languageSpecificPrimitives.add("NSURL");
languageSpecificPrimitives.add("bool");
languageSpecificPrimitives.add("BOOL");
@@ -109,8 +108,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("List", "NSArray");
typeMapping.put("object", "NSObject");
typeMapping.put("file", "NSURL");
- typeMapping.put("binary", BinaryDataType);
- typeMapping.put("ByteArray", BinaryDataType);
+ typeMapping.put("binary", "NSData");
+ typeMapping.put("ByteArray", "NSData");
+ typeMapping.put("byte", "NSData");
// ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm
setReservedWordsLowerCase(
@@ -143,6 +143,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
"NSObject",
"NSString",
"NSDate",
+ "NSData",
"NSURL",
"NSDictionary")
);
@@ -151,6 +152,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
instantiationTypes.put("map", "NSMutableDictionary");
cliOptions.clear();
+ cliOptions.add(new CliOption(CORE_DATA, "Should generate core data models").defaultValue("false"));
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).")
@@ -161,7 +163,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
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"));
}
@Override
@@ -191,6 +192,12 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
setPodVersion((String) additionalProperties.get(CodegenConstants.POD_VERSION));
}
+ if (additionalProperties.containsKey(CORE_DATA)) {
+ Object coreData = additionalProperties.get(CORE_DATA);
+ if(((String)coreData).equalsIgnoreCase("true")) {
+ generateCoreData = true;
+ }
+ }
if (additionalProperties.containsKey(CLASS_PREFIX)) {
setClassPrefix((String) additionalProperties.get(CLASS_PREFIX));
}
@@ -207,8 +214,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
setGitRepoURL((String) additionalProperties.get(GIT_REPO_URL));
}
- if (additionalProperties.containsKey(LICENSE)) {
- setLicense((String) additionalProperties.get(LICENSE));
+ if(generateCoreData) {
+ modelTemplateFiles.put("NSManagedObject-header.mustache", "ManagedObject.h");
+ modelTemplateFiles.put("NSManagedObject-body.mustache", "ManagedObject.m");
+ modelTemplateFiles.put("NSManagedObjectBuilder-header.mustache", "ManagedObjectBuilder.h");
+ modelTemplateFiles.put("NSManagedObjectBuilder-body.mustache", "ManagedObjectBuilder.m");
}
additionalProperties.put(POD_NAME, podName);
@@ -222,36 +232,41 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
// make api and model doc path available in mustache template
additionalProperties.put("apiDocPath", apiDocPath);
additionalProperties.put("modelDocPath", modelDocPath);
+ additionalProperties.put("useCoreData", generateCoreData);
- String swaggerFolder = podName;
+ modelPackage = podName;
+ apiPackage = podName;
- modelPackage = swaggerFolder;
- apiPackage = swaggerFolder;
-
- supportingFiles.add(new SupportingFile("Object-header.mustache", swaggerFolder, classPrefix + "Object.h"));
- supportingFiles.add(new SupportingFile("Object-body.mustache", swaggerFolder, classPrefix + "Object.m"));
- supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", swaggerFolder, classPrefix + "QueryParamCollection.h"));
- supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", swaggerFolder, classPrefix + "QueryParamCollection.m"));
- supportingFiles.add(new SupportingFile("ApiClient-header.mustache", swaggerFolder, classPrefix + "ApiClient.h"));
- supportingFiles.add(new SupportingFile("ApiClient-body.mustache", swaggerFolder, classPrefix + "ApiClient.m"));
- supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.h"));
- supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.m"));
- supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.m"));
- supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.h"));
- supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.m"));
- supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", swaggerFolder, classPrefix + "ResponseDeserializer.h"));
- supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", swaggerFolder, classPrefix + "Sanitizer.m"));
- supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", swaggerFolder, classPrefix + "Sanitizer.h"));
- supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", swaggerFolder, "JSONValueTransformer+ISO8601.m"));
- supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", swaggerFolder, "JSONValueTransformer+ISO8601.h"));
- supportingFiles.add(new SupportingFile("Configuration-body.mustache", swaggerFolder, classPrefix + "Configuration.m"));
- supportingFiles.add(new SupportingFile("Configuration-header.mustache", swaggerFolder, classPrefix + "Configuration.h"));
+ supportingFiles.add(new SupportingFile("Object-header.mustache", coreFileFolder(), classPrefix + "Object.h"));
+ supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m"));
+ supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h"));
+ supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m"));
+ supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h"));
+ supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m"));
+ supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h"));
+ supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m"));
+ supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m"));
+ supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h"));
+ supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m"));
+ supportingFiles.add(new SupportingFile("ResponseDeserializer-header.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.h"));
+ supportingFiles.add(new SupportingFile("Sanitizer-body.mustache", coreFileFolder(), classPrefix + "Sanitizer.m"));
+ supportingFiles.add(new SupportingFile("Sanitizer-header.mustache", coreFileFolder(), classPrefix + "Sanitizer.h"));
+ supportingFiles.add(new SupportingFile("Logger-body.mustache", coreFileFolder(), classPrefix + "Logger.m"));
+ supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h"));
+ supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m"));
+ supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h"));
+ supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m"));
+ supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h"));
+ supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h"));
supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
-
+ if(generateCoreData) {
+ supportingFiles.add(new SupportingFile("xccurrentversion.mustache", (modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld", ".xccurrentversion"));
+ supportingFiles.add(new SupportingFile("Model.xcdatamodel.mustache",(modelPackage() + "/" + modelFilesPath + "/").replace("/", File.separator) + classPrefix + "Model.xcdatamodeld" + File.separator + classPrefix + "Model.xcdatamodel", "contents"));
+ }
}
@Override
@@ -289,8 +304,81 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
return toModelNameWithoutReservedWordCheck(type);
}
+ public CodegenProperty coreDatafromProperty(String name, Property p) {
+ CodegenProperty property = fromProperty(name, p);
+ if(!generateCoreData) {
+ return property;
+ }
+ property.baseType = getTypeCoreDataDeclaration(p);
+ return property;
+ }
+
@Override
public String getTypeDeclaration(Property p) {
+ if (p instanceof ArrayProperty) {
+ ArrayProperty ap = (ArrayProperty) p;
+ Property inner = ap.getItems();
+ String innerTypeDeclaration = getTypeDeclaration(inner);
+ if (innerTypeDeclaration.endsWith("*")) {
+ innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
+ }
+ // In this condition, type of property p is array of primitive,
+ // return container type with pointer, e.g. `NSArray**'
+ if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
+ return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
+ }
+ // In this condition, type of property p is array of model,
+ // return container type combine inner type with pointer, e.g. `NSArray*'
+ else {
+ for (String sd : advancedMapingTypes) {
+ if(innerTypeDeclaration.startsWith(sd)) {
+ return getSwaggerType(p) + "<" + innerTypeDeclaration + "*>*";
+ }
+ }
+ return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
+ }
+ } else if (p instanceof MapProperty) {
+ MapProperty mp = (MapProperty) p;
+ Property inner = mp.getAdditionalProperties();
+
+ String innerTypeDeclaration = getTypeDeclaration(inner);
+
+ if (innerTypeDeclaration.endsWith("*")) {
+ innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
+ }
+ if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
+ return getSwaggerType(p) + "*";
+ } else {
+ for (String s : advancedMapingTypes) {
+ if(innerTypeDeclaration.startsWith(s)) {
+ return getSwaggerType(p) + "*";
+ }
+ }
+ return getSwaggerType(p) + "*";
+ }
+ } else {
+ String swaggerType = getSwaggerType(p);
+ // In this condition, type of p is objective-c primitive type, e.g. `NSSNumber',
+ // return type of p with pointer, e.g. `NSNumber*'
+ if (languageSpecificPrimitives.contains(swaggerType) &&
+ foundationClasses.contains(swaggerType)) {
+ return swaggerType + "*";
+ }
+ // In this condition, type of p is c primitive type, e.g. `bool',
+ // return type of p, e.g. `bool'
+ else if (languageSpecificPrimitives.contains(swaggerType)) {
+ return swaggerType;
+ }
+ // In this condition, type of p is objective-c object type, e.g. `SWGPet',
+ // return type of p with pointer, e.g. `SWGPet*'
+ else {
+ return swaggerType + "*";
+ }
+ }
+ }
+
+
+ public String getTypeCoreDataDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
@@ -300,10 +388,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
-
- if(innerTypeDeclaration.equalsIgnoreCase(BinaryDataType)) {
- return "NSData*";
- }
// In this codition, type of property p is array of primitive,
// return container type with pointer, e.g. `NSArray**'
if (languageSpecificPrimitives.contains(innerTypeDeclaration)) {
@@ -324,7 +408,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
Property inner = mp.getAdditionalProperties();
String innerTypeDeclaration = getTypeDeclaration(inner);
-
+
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
@@ -360,6 +444,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
}
}
+ @Override
+ public boolean isDataTypeBinary(String dataType) {
+ return dataType.toLowerCase().startsWith("nsdata");
+ }
+
@Override
public String toModelName(String type) {
// model name cannot use reserved keyword
@@ -454,12 +543,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String apiFileFolder() {
- return outputFolder + File.separatorChar + apiPackage();
+ return (outputFolder + "/"+ apiPackage() + "/" + apiFilesPath).replace("/", File.separator);
}
@Override
public String modelFileFolder() {
- return outputFolder + File.separatorChar + modelPackage();
+ return (outputFolder + "/"+ modelPackage() + "/" + modelFilesPath).replace("/", File.separator);
+ }
+
+ public String coreFileFolder() {
+ return (apiPackage() + "/" + coreFilesPath).replace("/", File.separator);
}
@Override
@@ -576,6 +669,12 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
return objs;
}
+ @Override
+ public void postProcessModelProperty(CodegenModel model, CodegenProperty property){
+ super.postProcessModelProperty(model,property);
+ property.vendorExtensions.put("x-uppercaseName", camelize(property.name));
+ }
+
/**
* Return the default value of the property
*
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 738ffd4e0d5..ac76770c1a4 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
@@ -3,6 +3,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.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
@@ -13,6 +14,7 @@ import io.swagger.models.properties.*;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.HashSet;
import java.util.regex.Matcher;
@@ -32,10 +34,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String COMPOSER_VENDOR_NAME = "composerVendorName";
public static final String COMPOSER_PROJECT_NAME = "composerProjectName";
protected String invokerPackage = "Swagger\\Client";
- protected String composerVendorName = "swagger";
- protected String composerProjectName = "swagger-client";
+ protected String composerVendorName = null;
+ protected String composerProjectName = null;
protected String packagePath = "SwaggerClient-php";
- protected String artifactVersion = "1.0.0";
+ protected String artifactVersion = null;
protected String srcBasePath = "lib";
protected String testBasePath = "test";
protected String docsBasePath = "docs";
@@ -126,7 +128,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(new CliOption(PACKAGE_PATH, "The main package name for classes. e.g. GeneratedPetstore"));
cliOptions.add(new CliOption(SRC_BASE_PATH, "The directory under packagePath to serve as source root."));
cliOptions.add(new CliOption(COMPOSER_VENDOR_NAME, "The vendor name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. yaypets. IMPORTANT NOTE (2016/03): composerVendorName will be deprecated and replaced by gitUserId in the next swagger-codegen release"));
+ cliOptions.add(new CliOption(CodegenConstants.GIT_USER_ID, CodegenConstants.GIT_USER_ID_DESC));
cliOptions.add(new CliOption(COMPOSER_PROJECT_NAME, "The project name used in the composer package name. The template uses {{composerVendorName}}/{{composerProjectName}} for the composer package name. e.g. petstore-client. IMPORTANT NOTE (2016/03): composerProjectName will be deprecated and replaced by gitRepoId in the next swagger-codegen release"));
+ cliOptions.add(new CliOption(CodegenConstants.GIT_REPO_ID, CodegenConstants.GIT_REPO_ID_DESC));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "The version to use in the composer package version field. e.g. 1.2.3"));
}
@@ -163,6 +167,15 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
.replaceAll(regLastPathSeparator+ "$", "");
}
+ @Override
+ public String escapeText(String input) {
+ if (input != null) {
+ // Trim the string to avoid leading and trailing spaces.
+ return super.escapeText(input).trim();
+ }
+ return input;
+ }
+
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
@@ -214,12 +227,24 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
additionalProperties.put(COMPOSER_PROJECT_NAME, composerProjectName);
}
+ if (additionalProperties.containsKey(CodegenConstants.GIT_USER_ID)) {
+ this.setGitUserId((String) additionalProperties.get(CodegenConstants.GIT_USER_ID));
+ } else {
+ additionalProperties.put(CodegenConstants.GIT_USER_ID, gitUserId);
+ }
+
if (additionalProperties.containsKey(COMPOSER_VENDOR_NAME)) {
this.setComposerVendorName((String) additionalProperties.get(COMPOSER_VENDOR_NAME));
} else {
additionalProperties.put(COMPOSER_VENDOR_NAME, composerVendorName);
}
+ if (additionalProperties.containsKey(CodegenConstants.GIT_REPO_ID)) {
+ this.setGitRepoId((String) additionalProperties.get(CodegenConstants.GIT_REPO_ID));
+ } else {
+ additionalProperties.put(CodegenConstants.GIT_REPO_ID, gitRepoId);
+ }
+
if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) {
this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION));
} else {
@@ -248,7 +273,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md"));
supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", getPackagePath(), "git_push.sh"));
-
+ // apache v2 license
+ supportingFiles.add(new SupportingFile("LICENSE", getPackagePath(), "LICENSE"));
}
@Override
@@ -626,4 +652,14 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
// process enum in models
return postProcessModelsEnum(objs);
}
+
+ @Override
+ public Map postProcessOperations(Map objs) {
+ Map operations = (Map) objs.get("operations");
+ List operationList = (List) operations.get("operation");
+ for (CodegenOperation op : operationList) {
+ op.vendorExtensions.put("x-testOperationId", camelize(op.operationId));
+ }
+ return objs;
+ }
}
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 113c6a6e1c1..51bd143ba8f 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
@@ -15,7 +15,6 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -116,6 +115,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public void processOpts() {
super.processOpts();
+ Boolean excludeTests = false;
+
+ if(additionalProperties.containsKey(CodegenConstants.EXCLUDE_TESTS)) {
+ excludeTests = Boolean.valueOf(additionalProperties.get(CodegenConstants.EXCLUDE_TESTS).toString());
+ }
if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) {
setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME));
@@ -144,14 +148,23 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
apiPackage = swaggerFolder + File.separatorChar + "apis";
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
+ supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE"));
+
supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py"));
+ supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini"));
+ supportingFiles.add(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt"));
+ supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt"));
+
supportingFiles.add(new SupportingFile("api_client.mustache", swaggerFolder, "api_client.py"));
supportingFiles.add(new SupportingFile("rest.mustache", swaggerFolder, "rest.py"));
supportingFiles.add(new SupportingFile("configuration.mustache", swaggerFolder, "configuration.py"));
supportingFiles.add(new SupportingFile("__init__package.mustache", swaggerFolder, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py"));
supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py"));
- supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py"));
+
+ if(Boolean.FALSE.equals(excludeTests)) {
+ supportingFiles.add(new SupportingFile("__init__test.mustache", testFolder, "__init__.py"));
+ }
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
}
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java
new file mode 100644
index 00000000000..4bb4c8e883c
--- /dev/null
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java
@@ -0,0 +1,320 @@
+package io.swagger.codegen.languages;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import com.fasterxml.jackson.core.JsonProcessingException;
+
+import io.swagger.codegen.CodegenConfig;
+import io.swagger.codegen.CodegenType;
+import io.swagger.codegen.DefaultCodegen;
+import io.swagger.codegen.SupportingFile;
+import io.swagger.models.properties.ArrayProperty;
+import io.swagger.models.properties.MapProperty;
+import io.swagger.models.properties.Property;
+import io.swagger.models.Swagger;
+import io.swagger.util.Yaml;
+
+import java.io.File;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Map;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(Rails5ServerCodegen.class);
+ private static final SimpleDateFormat MIGRATE_FILE_NAME_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
+
+ protected String gemName;
+ protected String moduleName;
+ protected String gemVersion = "1.0.0";
+ protected String appFolder = "app";
+ protected String channelsFolder = appFolder + File.separator + "channels";
+ protected String applicationCableFolder = channelsFolder + File.separator + "application_cable";
+ protected String controllersFolder = appFolder + File.separator + "controllers";
+ protected String jobsFolder = appFolder + File.separator + "jobs";
+ protected String mailersFolder = appFolder + File.separator + "mailers";
+ protected String modelsFolder = appFolder + File.separator + "models";
+ protected String viewsFolder = appFolder + File.separator + "views";
+ protected String layoutsFolder = viewsFolder + File.separator + "layouts";
+ protected String binFolder = "bin";
+ protected String configFolder = "config";
+ protected String environmentsFolder = configFolder + File.separator + "config";
+ protected String initializersFolder = configFolder + File.separator + "initializers";
+ protected String localesFolder = configFolder + File.separator + "locales";
+ protected String dbFolder = "db";
+ protected String migrateFolder = dbFolder + File.separator + "migrate";
+ protected String libFolder = "lib";
+ protected String tasksFolder = libFolder + File.separator + "tasks";
+ protected String logFolder = "log";
+ protected String publicFolder = "public";
+ protected String testFolder = "test";
+ protected String tmpFolder = "tmp";
+ protected String cacheFolder = tmpFolder + File.separator + "cache";
+ protected String pidFolder = tmpFolder + File.separator + "pids";
+ protected String socketsFolder = tmpFolder + File.separator + "sockets";
+ protected String vendorFolder = "vendor";
+
+ public Rails5ServerCodegen() {
+ super();
+ outputFolder = "generated-code" + File.separator + "rails5";
+ apiPackage = "app/controllers";
+ apiTemplateFiles.put("controller.mustache", ".rb");
+
+ modelPackage = "app/models";
+ modelTemplateFiles.put("model.mustache", ".rb");
+
+ embeddedTemplateDir = templateDir = "rails5";
+
+ typeMapping.clear();
+ languageSpecificPrimitives.clear();
+
+ setReservedWordsLowerCase(
+ Arrays.asList(
+ "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__",
+ "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN",
+ "break", "do", "false", "next", "rescue", "then", "when", "END", "case",
+ "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif",
+ "if", "not", "return", "undef", "yield")
+ );
+
+ typeMapping.put("string", "string");
+ typeMapping.put("char", "string");
+ typeMapping.put("int", "integer");
+ typeMapping.put("integer", "integer");
+ typeMapping.put("long", "integer");
+ typeMapping.put("short", "integer");
+ typeMapping.put("float", "float");
+ typeMapping.put("double", "decimal");
+ typeMapping.put("number", "float");
+ typeMapping.put("date", "date");
+ typeMapping.put("DateTime", "datetime");
+ typeMapping.put("boolean", "boolean");
+ typeMapping.put("binary", "string");
+ typeMapping.put("ByteArray", "string");
+ typeMapping.put("UUID", "string");
+
+ // remove modelPackage and apiPackage added by default
+ cliOptions.clear();
+ }
+
+ @Override
+ public void processOpts() {
+ super.processOpts();
+
+ // use constant model/api package (folder path)
+ //setModelPackage("models");
+ setApiPackage("app/controllers");
+
+ supportingFiles.add(new SupportingFile("Gemfile", "", "Gemfile"));
+ supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
+ supportingFiles.add(new SupportingFile("Rakefile", "", "Rakefile"));
+ supportingFiles.add(new SupportingFile("config.ru", "", "config.ru"));
+ supportingFiles.add(new SupportingFile("channel.rb", applicationCableFolder, "channel.rb"));
+ supportingFiles.add(new SupportingFile("connection.rb", applicationCableFolder, "connection.rb"));
+ supportingFiles.add(new SupportingFile("application_controller.rb", controllersFolder, "application_controller.rb"));
+ supportingFiles.add(new SupportingFile("application_job.rb", jobsFolder, "application_job.rb"));
+ supportingFiles.add(new SupportingFile("application_mailer.rb", mailersFolder, "application_mailer.rb"));
+ supportingFiles.add(new SupportingFile("application_record.rb", modelsFolder, "application_record.rb"));
+ supportingFiles.add(new SupportingFile("mailer.html.erb", layoutsFolder, "mailer.html.erb"));
+ supportingFiles.add(new SupportingFile("mailer.text.erb", layoutsFolder, "mailer.text.erb"));
+ supportingFiles.add(new SupportingFile("bundle", binFolder, "bundle"));
+ supportingFiles.add(new SupportingFile("rails", binFolder, "rails"));
+ supportingFiles.add(new SupportingFile("rake", binFolder, "rake"));
+ supportingFiles.add(new SupportingFile("setup", binFolder, "setup"));
+ supportingFiles.add(new SupportingFile("update", binFolder, "update"));
+ supportingFiles.add(new SupportingFile("development.rb", environmentsFolder, "development.rb"));
+ supportingFiles.add(new SupportingFile("production.rb", environmentsFolder, "production.rb"));
+ supportingFiles.add(new SupportingFile("active_record_belongs_to_required_by_default.rb", initializersFolder, "active_record_belongs_to_required_by_default.rb"));
+ supportingFiles.add(new SupportingFile("application_controller_renderer.rb", initializersFolder, "application_controller_renderer.rb"));
+ supportingFiles.add(new SupportingFile("backtrace_silencers.rb", initializersFolder, "backtrace_silencers.rb"));
+ supportingFiles.add(new SupportingFile("callback_terminator.rb", initializersFolder, "callback_terminator.rb"));
+ supportingFiles.add(new SupportingFile("cors.rb", initializersFolder, "cors.rb"));
+ supportingFiles.add(new SupportingFile("filter_parameter_logging.rb", initializersFolder, "filter_parameter_logging.rb"));
+ supportingFiles.add(new SupportingFile("inflections.rb", initializersFolder, "inflections.rb"));
+ supportingFiles.add(new SupportingFile("mime_types.rb", initializersFolder, "mime_types.rb"));
+ supportingFiles.add(new SupportingFile("ssl_options.rb", initializersFolder, "ssl_options.rb"));
+ supportingFiles.add(new SupportingFile("to_time_preserves_timezone.rb", initializersFolder, "to_time_preserves_timezone.rb"));
+ supportingFiles.add(new SupportingFile("en.yml", localesFolder, "en.yml"));
+ supportingFiles.add(new SupportingFile("application.rb", configFolder, "application.rb"));
+ supportingFiles.add(new SupportingFile("boot.rb", configFolder, "boot.rb"));
+ supportingFiles.add(new SupportingFile("cable.yml", configFolder, "cable.yml"));
+ supportingFiles.add(new SupportingFile("database.yml", configFolder, "database.yml"));
+ supportingFiles.add(new SupportingFile("environment.rb", configFolder, "environment.rb"));
+ supportingFiles.add(new SupportingFile("puma.rb", configFolder, "puma.rb"));
+ supportingFiles.add(new SupportingFile("routes.mustache", configFolder, "routes.rb"));
+ supportingFiles.add(new SupportingFile("secrets.yml", configFolder, "secrets.yml"));
+ supportingFiles.add(new SupportingFile("spring.rb", configFolder, "spring.rb"));
+ supportingFiles.add(new SupportingFile(".keep", migrateFolder, ".keep"));
+ supportingFiles.add(new SupportingFile("migrate.mustache", migrateFolder, "0_init_tables.rb"));
+ supportingFiles.add(new SupportingFile("schema.rb", dbFolder, "schema.rb"));
+ supportingFiles.add(new SupportingFile("seeds.rb", dbFolder, "seeds.rb"));
+ supportingFiles.add(new SupportingFile(".keep", tasksFolder, ".keep"));
+ supportingFiles.add(new SupportingFile(".keep", logFolder, ".keep"));
+ supportingFiles.add(new SupportingFile("404.html", publicFolder, "404.html"));
+ supportingFiles.add(new SupportingFile("422.html", publicFolder, "422.html"));
+ supportingFiles.add(new SupportingFile("500.html", publicFolder, "500.html"));
+ supportingFiles.add(new SupportingFile("apple-touch-icon-precomposed.png", publicFolder, "apple-touch-icon-precomposed.png"));
+ supportingFiles.add(new SupportingFile("apple-touch-icon.png", publicFolder, "apple-touch-icon.png"));
+ supportingFiles.add(new SupportingFile("favicon.ico", publicFolder, "favicon.ico"));
+ supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt"));
+ supportingFiles.add(new SupportingFile("robots.txt", publicFolder, "robots.txt"));
+ supportingFiles.add(new SupportingFile("test_helper.rb", testFolder, "test_helper.rb"));
+ supportingFiles.add(new SupportingFile(".keep", cacheFolder, ".keep"));
+ supportingFiles.add(new SupportingFile(".keep", pidFolder, ".keep"));
+ supportingFiles.add(new SupportingFile(".keep", socketsFolder, ".keep"));
+ supportingFiles.add(new SupportingFile("restart.txt", tmpFolder, "restart.txt"));
+ supportingFiles.add(new SupportingFile(".keep", vendorFolder, ".keep"));
+ }
+
+ @Override
+ public CodegenType getTag() {
+ return CodegenType.SERVER;
+ }
+
+ @Override
+ public String getName() {
+ return "rails5";
+ }
+
+ @Override
+ public String getHelp() {
+ return "Generates a Rails5 server library.";
+ }
+
+ @Override
+ public String escapeReservedWord(String name) {
+ return "_" + name;
+ }
+
+ @Override
+ public String apiFileFolder() {
+ return outputFolder + File.separator + apiPackage.replace("/", File.separator);
+ }
+
+ @Override
+ public String getTypeDeclaration(Property p) {
+ if (p instanceof ArrayProperty) {
+ ArrayProperty ap = (ArrayProperty) p;
+ Property inner = ap.getItems();
+ return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
+ } else if (p instanceof MapProperty) {
+ MapProperty mp = (MapProperty) p;
+ Property inner = mp.getAdditionalProperties();
+ return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
+ }
+ return super.getTypeDeclaration(p);
+ }
+
+ @Override
+ public String toDefaultValue(Property p) {
+ return "null";
+ }
+
+ @Override
+ public String toVarName(String name) {
+ // replace - with _ e.g. created-at => created_at
+ name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
+
+ // if it's all uppper case, convert to lower case
+ if (name.matches("^[A-Z_]*$")) {
+ name = name.toLowerCase();
+ }
+
+ // camelize (lower first character) the variable name
+ // petId => pet_id
+ name = underscore(name);
+
+ // for reserved word or word starting with number, append _
+ if (isReservedWord(name) || name.matches("^\\d.*")) {
+ name = escapeReservedWord(name);
+ }
+
+ return name;
+ }
+
+ @Override
+ public String getSwaggerType(Property p) {
+ String swaggerType = super.getSwaggerType(p);
+ String type = null;
+ if (typeMapping.containsKey(swaggerType)) {
+ return typeMapping.get(swaggerType);
+ }
+ return "string";
+ }
+
+ @Override
+ public String toParamName(String name) {
+ // should be the same as variable name
+ return toVarName(name);
+ }
+
+ @Override
+ public String toModelName(String name) {
+ // model name cannot use reserved keyword, e.g. return
+ if (isReservedWord(name)) {
+ throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
+ }
+
+ // camelize the model name
+ // phone_number => PhoneNumber
+ return camelize(name);
+ }
+
+ @Override
+ public String toModelFilename(String name) {
+ // model name cannot use reserved keyword, e.g. return
+ if (isReservedWord(name)) {
+ throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
+ }
+
+ // underscore the model file name
+ // PhoneNumber.rb => phone_number.rb
+ return underscore(name);
+ }
+
+ @Override
+ public String toApiFilename(String name) {
+ // replace - with _ e.g. created-at => created_at
+ name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
+
+ // e.g. PhoneNumberApi.rb => phone_number_api.rb
+ return underscore(name) + "_controllers";
+ }
+
+ @Override
+ public String toApiName(String name) {
+ if (name.length() == 0) {
+ return "ApiController";
+ }
+ // e.g. phone_number_api => PhoneNumberApi
+ return camelize(name) + "Controller";
+ }
+
+ @Override
+ public String toOperationId(String operationId) {
+ // method name cannot use reserved keyword, e.g. return
+ if (isReservedWord(operationId)) {
+ throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
+ }
+
+ return underscore(operationId);
+ }
+
+ @Override
+ public Map postProcessSupportingFileData(Map objs) {
+ Swagger swagger = (Swagger)objs.get("swagger");
+ if(swagger != null) {
+ try {
+ objs.put("swagger-yaml", Yaml.mapper().writeValueAsString(swagger));
+ } catch (JsonProcessingException e) {
+ LOGGER.error(e.getMessage(), e);
+ }
+ }
+ return super.postProcessSupportingFileData(objs);
+ }
+
+}
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 6655a28f1d5..0db5598f7f0 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
@@ -5,6 +5,7 @@ import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
+import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
@@ -224,6 +225,9 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
+ supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE"));
+
+ // test files should not be overwritten
writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec"));
writeOptional(outputFolder, new SupportingFile("spec_helper.mustache", specFolder, "spec_helper.rb"));
writeOptional(outputFolder, new SupportingFile("configuration_spec.mustache", specFolder, "configuration_spec.rb"));
@@ -527,6 +531,57 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
return camelize(name) + "Api";
}
+ @Override
+ public String toEnumValue(String value, String datatype) {
+ if ("Integer".equals(datatype) || "Float".equals(datatype)) {
+ return value;
+ } else {
+ return "\"" + escapeText(value) + "\"";
+ }
+ }
+
+ @Override
+ public String toEnumVarName(String name, String datatype) {
+ // number
+ if ("Integer".equals(datatype) || "Float".equals(datatype)) {
+ String varName = new String(name);
+ varName = varName.replaceAll("-", "MINUS_");
+ varName = varName.replaceAll("\\+", "PLUS_");
+ varName = varName.replaceAll("\\.", "_DOT_");
+ return varName;
+ }
+
+ // string
+ String enumName = sanitizeName(underscore(name).toUpperCase());
+ enumName = enumName.replaceFirst("^_", "");
+ enumName = enumName.replaceFirst("_$", "");
+
+ if (enumName.matches("\\d.*")) { // starts with number
+ return "N" + enumName;
+ } else {
+ return enumName;
+ }
+ }
+
+ @Override
+ public String toEnumName(CodegenProperty property) {
+ String enumName = underscore(toModelName(property.name)).toUpperCase();
+ enumName = enumName.replaceFirst("^_", "");
+ enumName = enumName.replaceFirst("_$", "");
+
+ if (enumName.matches("\\d.*")) { // starts with number
+ return "N" + enumName;
+ } else {
+ return enumName;
+ }
+ }
+
+ @Override
+ public Map postProcessModels(Map objs) {
+ // process enum in models
+ return postProcessModelsEnum(objs);
+ }
+
@Override
public String toOperationId(String operationId) {
// rename to empty_method_name_1 (e.g.) if method name is empty
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 992693810da..12467f12efe 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
@@ -35,6 +35,7 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/scala";
protected String authScheme = "";
+ protected String gradleWrapperPackage = "gradle.wrapper";
protected boolean authPreemptive;
protected boolean asyncHttpClient = !authScheme.isEmpty();
@@ -74,6 +75,17 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
+ // gradle settings
+ 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"));
+ // gradleWrapper files
+ supportingFiles.add(new SupportingFile( "gradlew.mustache", "", "gradlew") );
+ supportingFiles.add(new SupportingFile( "gradlew.bat.mustache", "", "gradlew.bat") );
+ supportingFiles.add(new SupportingFile( "gradle-wrapper.properties.mustache",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.properties") );
+ supportingFiles.add(new SupportingFile( "gradle-wrapper.jar",
+ gradleWrapperPackage.replace( ".", File.separator ), "gradle-wrapper.jar") );
importMapping.remove("List");
importMapping.remove("Set");
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java
index 070f5de6d03..dbed6bc98c4 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringBootServerCodegen.java
@@ -10,16 +10,20 @@ import java.util.*;
public class SpringBootServerCodegen extends JavaClientCodegen implements CodegenConfig{
public static final String CONFIG_PACKAGE = "configPackage";
public static final String BASE_PACKAGE = "basePackage";
+ public static final String INTERFACE_ONLY = "interfaceOnly";
+ public static final String SINGLE_CONTENT_TYPES = "singleContentTypes";
protected String title = "Petstore Server";
protected String configPackage = "";
protected String basePackage = "";
+ protected boolean interfaceOnly = false;
+ protected boolean singleContentTypes = false;
protected String templateFileName = "api.mustache";
public SpringBootServerCodegen() {
super();
outputFolder = "generated-code/javaSpringBoot";
- modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put(templateFileName, ".java");
+ apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpringBoot";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
@@ -39,7 +43,9 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code"));
cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code"));
-
+ cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files."));
+ cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation."));
+
supportedLibraries.clear();
supportedLibraries.put(DEFAULT_LIBRARY, "Default Spring Boot server stub.");
supportedLibraries.put("j8-async", "Use async servlet feature and Java 8's default interface. Generating interface with service " +
@@ -78,30 +84,37 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
this.setBasePackage((String) additionalProperties.get(BASE_PACKAGE));
}
+ if (additionalProperties.containsKey(INTERFACE_ONLY)) {
+ this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString()));
+ }
+
+ if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) {
+ this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString()));
+ }
+
supportingFiles.clear();
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
- supportingFiles.add(new SupportingFile("apiException.mustache",
- (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
- supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
- (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
- supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
- (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
- supportingFiles.add(new SupportingFile("notFoundException.mustache",
- (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
-
- supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
- (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
- supportingFiles.add(new SupportingFile("homeController.mustache",
- (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
-
- supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
- (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
-
-
- supportingFiles.add(new SupportingFile("application.properties",
- ("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
+ if(!this.interfaceOnly) {
+ apiTemplateFiles.put("apiController.mustache", "Controller.java");
+ supportingFiles.add(new SupportingFile("apiException.mustache",
+ (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java"));
+ supportingFiles.add(new SupportingFile("apiOriginFilter.mustache",
+ (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java"));
+ supportingFiles.add(new SupportingFile("apiResponseMessage.mustache",
+ (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java"));
+ supportingFiles.add(new SupportingFile("notFoundException.mustache",
+ (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java"));
+ supportingFiles.add(new SupportingFile("swaggerDocumentationConfig.mustache",
+ (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "SwaggerDocumentationConfig.java"));
+ supportingFiles.add(new SupportingFile("homeController.mustache",
+ (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "HomeController.java"));
+ supportingFiles.add(new SupportingFile("swagger2SpringBoot.mustache",
+ (sourceFolder + File.separator + basePackage).replace(".", java.io.File.separator), "Swagger2SpringBoot.java"));
+ supportingFiles.add(new SupportingFile("application.properties",
+ ("src.main.resources").replace(".", java.io.File.separator), "application.properties"));
+ }
}
@Override
@@ -118,9 +131,6 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
if (basePath == "") {
basePath = "default";
} else {
- if (co.path.startsWith("/" + basePath)) {
- co.path = co.path.substring(("/" + basePath).length());
- }
co.subresourceOperation = !co.path.isEmpty();
}
List opList = operations.get(basePath);
@@ -131,10 +141,10 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
opList.add(co);
co.baseName = basePath;
}
-
+
@Override
public void preprocessSwagger(Swagger swagger) {
- System.out.println("preprocessSwagger");
+ super.preprocessSwagger(swagger);
if ("/".equals(swagger.getBasePath())) {
swagger.setBasePath("");
}
@@ -147,7 +157,7 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
port = parts[1];
}
}
-
+
this.additionalProperties.put("serverPort", port);
if (swagger != null && swagger.getPaths() != null) {
for (String pathname : swagger.getPaths().keySet()) {
@@ -255,6 +265,14 @@ public class SpringBootServerCodegen extends JavaClientCodegen implements Codege
public void setBasePackage(String configPackage) {
this.basePackage = configPackage;
}
+
+ public void setInterfaceOnly(boolean interfaceOnly) {
+ this.interfaceOnly = interfaceOnly;
+ }
+
+ public void setSingleContentTypes(boolean singleContentTypes) {
+ this.singleContentTypes = singleContentTypes;
+ }
@Override
public Map postProcessModels(Map objs) {
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java
index 8bd7e3c1f8e..47c67a4ec6d 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java
@@ -18,12 +18,14 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
outputFolder = "generated-code/javaSpringMVC";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put(templateFileName, ".java");
+ apiTestTemplateFiles.clear(); // TODO: add test template
embeddedTemplateDir = templateDir = "JavaSpringMVC";
apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model";
configPackage = "io.swagger.configuration";
invokerPackage = "io.swagger.api";
artifactId = "swagger-spring-mvc-server";
+ dateLibrary = "legacy";
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java
index ba846857cb9..6ec81c1c357 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java
@@ -342,7 +342,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
// Ensure that the enum type doesn't match a reserved word or
// the variable name doesn't match the generated enum type or the
// Swift compiler will generate an error
- if (isReservedWord(codegenProperty.datatypeWithEnum) || name.equals(codegenProperty.datatypeWithEnum)) {
+ if (isReservedWord(codegenProperty.datatypeWithEnum) || toVarName(name).equals(codegenProperty.datatypeWithEnum)) {
codegenProperty.datatypeWithEnum = codegenProperty.datatypeWithEnum + "Enum";
}
}
@@ -355,8 +355,8 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
if (value.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
return value;
}
- char[] separators = {'-', '_', ' '};
- return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ ]", "");
+ char[] separators = {'-', '_', ' ', ':'};
+ return WordUtils.capitalizeFully(StringUtils.lowerCase(value), separators).replaceAll("[-_ :]", "");
}
@@ -502,6 +502,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toEnumVarName(String name, String datatype) {
+ // TODO: this code is probably useless, because the var name is computed from the value in map.put("enum", toSwiftyEnumName(value));
// number
if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) {
String varName = new String(name);
@@ -525,8 +526,9 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String toEnumName(CodegenProperty property) {
- String enumName = underscore(toModelName(property.name)).toUpperCase();
+ String enumName = toModelName(property.name);
+ // TODO: toModelName already does something for names starting with number, so this code is probably never called
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java
index a80e0f66ae0..6a945249af6 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java
@@ -5,12 +5,15 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import io.swagger.codegen.CliOption;
+import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.SupportingFile;
+import io.swagger.models.ModelImpl;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.FileProperty;
import io.swagger.models.properties.MapProperty;
+import io.swagger.models.properties.ObjectProperty;
import io.swagger.models.properties.Property;
public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCodegen {
@@ -43,6 +46,12 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
this.cliOptions.add(new CliOption(SNAPSHOT, "When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm", BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
}
+ @Override
+ protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) {
+ codegenModel.additionalPropertiesType = getSwaggerType(swaggerModel.getAdditionalProperties());
+ addImport(codegenModel, codegenModel.additionalPropertiesType);
+ }
+
@Override
public String getName() {
return "typescript-angular2";
@@ -106,14 +115,19 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
MapProperty mp = (MapProperty)p;
inner = mp.getAdditionalProperties();
return "{ [key: string]: " + this.getTypeDeclaration(inner) + "; }";
+ } else if(p instanceof FileProperty || p instanceof ObjectProperty) {
+ return "any";
} else {
- return p instanceof FileProperty ? "any" : super.getTypeDeclaration(p);
+ return super.getTypeDeclaration(p);
}
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
+ if(languageSpecificPrimitives.contains(swaggerType)) {
+ return swaggerType;
+ }
return addModelPrefix(swaggerType);
}
@@ -121,13 +135,25 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
- if (languageSpecificPrimitives.contains(type))
- return type;
- } else
+ } else {
+ type = swaggerType;
+ }
+
+ if (!startsWithLanguageSpecificPrimitiv(type)) {
type = "models." + swaggerType;
+ }
return type;
}
+ private boolean startsWithLanguageSpecificPrimitiv(String type) {
+ for (String langPrimitive:languageSpecificPrimitives) {
+ if (type.startsWith(langPrimitive)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java
index c817162401e..90f778eae8e 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java
@@ -26,7 +26,6 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
super.processOpts();
supportingFiles.add(new SupportingFile("api.mustache", "", "api.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
- supportingFiles.add(new SupportingFile("assign.ts", "", "assign.ts"));
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json"));
diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java
index d4207f09cc8..516d34b9810 100644
--- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java
+++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java
@@ -42,7 +42,6 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen
supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
- LOGGER.warn("check additionals: " + additionalProperties.get(NPM_NAME));
if(additionalProperties.containsKey(NPM_NAME)) {
addNpmPackageGeneration();
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache
index 4629c4e17be..cb425df3563 100644
--- a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache
@@ -1,22 +1,28 @@
+{{>licenseInfo}}
+
package {{invokerPackage}};
{{>generatedAnnotation}}
public class Configuration {
- private static ApiClient defaultApiClient = new ApiClient();
+ 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;
- }
+ /**
+ * Get the default API client, which would be used when creating API
+ * instances without providing an API client.
+ *
+ * @return Default 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;
- }
+ /**
+ * Set the default API client, which would be used when creating API
+ * instances without providing an API client.
+ *
+ * @param apiClient API client
+ */
+ public static void setDefaultApiClient(ApiClient apiClient) {
+ defaultApiClient = apiClient;
+ }
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/Pair.mustache b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache
index e2a47317afe..c08f145a482 100644
--- a/modules/swagger-codegen/src/main/resources/Java/Pair.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}};
{{>generatedAnnotation}}
diff --git a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache
index 073966b0c21..7b72a7bab45 100644
--- a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}};
{{>generatedAnnotation}}
diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache
index ad7b9051f05..4d54d84d337 100644
--- a/modules/swagger-codegen/src/main/resources/Java/api.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache
@@ -78,12 +78,12 @@ public class {{classname}} {
{{/formParams}}
final String[] {{localVariablePrefix}}localVarAccepts = {
- {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
+ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
};
final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts);
final String[] {{localVariablePrefix}}localVarContentTypes = {
- {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
+ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
};
final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
diff --git a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache
index b9a62a6b231..89ed524d37e 100644
--- a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}};
import java.util.Map;
@@ -5,65 +7,74 @@ import java.util.List;
{{>generatedAnnotation}}
public class ApiException extends Exception {
- private int code = 0;
- private Map> responseHeaders = null;
- private String responseBody = null;
+ private int code = 0;
+ private Map> responseHeaders = null;
+ private String responseBody = null;
- public ApiException() {}
+ public ApiException() {}
- public ApiException(Throwable throwable) {
- super(throwable);
- }
+ public ApiException(Throwable throwable) {
+ super(throwable);
+ }
- public ApiException(String message) {
- super(message);
- }
+ public ApiException(String message) {
+ super(message);
+ }
- public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) {
- super(message, throwable);
- this.code = code;
- this.responseHeaders = responseHeaders;
- this.responseBody = responseBody;
- }
+ public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) {
+ super(message, throwable);
+ this.code = code;
+ this.responseHeaders = responseHeaders;
+ this.responseBody = responseBody;
+ }
- public ApiException(String message, int code, Map> responseHeaders, String responseBody) {
- this(message, (Throwable) null, code, responseHeaders, responseBody);
- }
+ public ApiException(String message, int code, Map> responseHeaders, String responseBody) {
+ this(message, (Throwable) null, code, responseHeaders, responseBody);
+ }
- public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) {
- this(message, throwable, code, responseHeaders, null);
- }
+ public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) {
+ this(message, throwable, code, responseHeaders, null);
+ }
- public ApiException(int code, Map> responseHeaders, String responseBody) {
- this((String) null, (Throwable) null, code, responseHeaders, responseBody);
- }
+ public ApiException(int code, Map> responseHeaders, String responseBody) {
+ this((String) null, (Throwable) null, code, responseHeaders, responseBody);
+ }
- public ApiException(int code, String message) {
- super(message);
- this.code = code;
- }
+ public ApiException(int code, String message) {
+ super(message);
+ this.code = code;
+ }
- public ApiException(int code, String message, Map> responseHeaders, String responseBody) {
- this(code, message);
- this.responseHeaders = responseHeaders;
- this.responseBody = responseBody;
- }
+ public ApiException(int code, String message, Map> responseHeaders, String responseBody) {
+ this(code, message);
+ this.responseHeaders = responseHeaders;
+ this.responseBody = responseBody;
+ }
- public int getCode() {
- return code;
- }
+ /**
+ * Get the HTTP status code.
+ *
+ * @return HTTP status code
+ */
+ public int getCode() {
+ return code;
+ }
- /**
- * Get the HTTP response headers.
- */
- public Map> getResponseHeaders() {
- return responseHeaders;
- }
+ /**
+ * Get the HTTP response headers.
+ *
+ * @return A map of list of string
+ */
+ public Map> getResponseHeaders() {
+ return responseHeaders;
+ }
- /**
- * Get the HTTP response body.
- */
- public String getResponseBody() {
- return responseBody;
- }
+ /**
+ * Get the HTTP response body.
+ *
+ * @return Response body in the form of string
+ */
+ public String getResponseBody() {
+ return responseBody;
+ }
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/api_doc.mustache b/modules/swagger-codegen/src/main/resources/Java/api_doc.mustache
index 93c5bc5b13a..bbb5b66f840 100644
--- a/modules/swagger-codegen/src/main/resources/Java/api_doc.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/api_doc.mustache
@@ -75,8 +75,8 @@ Name | Type | Description | Notes
### HTTP request headers
- - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
+ - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
+ - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
{{/operation}}
{{/operations}}
diff --git a/modules/swagger-codegen/src/main/resources/Java/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache
new file mode 100644
index 00000000000..0a7639e0ec1
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache
@@ -0,0 +1,43 @@
+{{>licenseInfo}}
+
+package {{package}};
+
+import {{invokerPackage}}.ApiException;
+{{#imports}}import {{import}};
+{{/imports}}
+import org.junit.Test;
+
+{{^fullJavaUtil}}
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+{{/fullJavaUtil}}
+
+/**
+ * API tests for {{classname}}
+ */
+public class {{classname}}Test {
+
+ private final {{classname}} api = new {{classname}}();
+
+ {{#operations}}{{#operation}}
+ /**
+ * {{summary}}
+ *
+ * {{notes}}
+ *
+ * @throws ApiException
+ * if the Api call fails
+ */
+ @Test
+ public void {{operationId}}Test() throws ApiException {
+ {{#allParams}}
+ {{{dataType}}} {{paramName}} = null;
+ {{/allParams}}
+ // {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
+
+ // TODO: test validations
+ }
+ {{/operation}}{{/operations}}
+}
diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache
index 931d17b0d04..f73a6f5b3f8 100644
--- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache
index 265c74cb76f..26174fa3b59 100644
--- a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
@@ -6,6 +8,11 @@ import java.util.Map;
import java.util.List;
public interface Authentication {
- /** Apply authentication settings to header and query params. */
- void applyToParams(List queryParams, Map headerParams);
+ /**
+ * Apply authentication settings to header and query params.
+ *
+ * @param queryParams List of query parameters
+ * @param headerParams Map of header parameters
+ */
+ void applyToParams(List queryParams, Map headerParams);
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache
index febabe33d64..0438f6a40b7 100644
--- a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache
index 902f54a2e3a..ffc9923d1fe 100644
--- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache
index 7ab35f6d890..002e9572f33 100644
--- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache
@@ -1,5 +1,7 @@
+{{>licenseInfo}}
+
package {{invokerPackage}}.auth;
public enum OAuthFlow {
accessCode, implicit, password, application
-}
\ No newline at end of file
+}
diff --git a/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache b/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache
index 32858aad3c3..7cf39af816c 100644
--- a/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/gitignore.mustache
@@ -8,5 +8,8 @@
*.war
*.ear
+# exclude jar for gradle wrapper
+!gradle/wrapper/*.jar
+
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
diff --git a/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.jar b/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.jar
new file mode 100644
index 00000000000..2c6137b8789
Binary files /dev/null and b/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.jar differ
diff --git a/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.properties.mustache b/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.properties.mustache
new file mode 100644
index 00000000000..b7a36473955
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/gradle-wrapper.properties.mustache
@@ -0,0 +1,6 @@
+#Tue May 17 23:08:05 CST 2016
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip
diff --git a/modules/swagger-codegen/src/main/resources/Java/gradlew.bat.mustache b/modules/swagger-codegen/src/main/resources/Java/gradlew.bat.mustache
new file mode 100644
index 00000000000..72d362dafd8
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/gradlew.bat.mustache
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windows variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/modules/swagger-codegen/src/main/resources/Java/gradlew.mustache b/modules/swagger-codegen/src/main/resources/Java/gradlew.mustache
new file mode 100755
index 00000000000..9d82f789151
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/gradlew.mustache
@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+ echo "$*"
+}
+
+die ( ) {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+ JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache
index 2d9fa23cf04..be2e2d5e3ab 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache
@@ -9,6 +9,7 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
+import com.fasterxml.jackson.datatype.joda.JodaModule;
import feign.Feign;
import feign.RequestInterceptor;
@@ -22,7 +23,7 @@ import {{invokerPackage}}.auth.OAuth.AccessTokenListener;
public class ApiClient {
public interface Api {}
- private ObjectMapper objectMapper;
+ protected ObjectMapper objectMapper;
private String basePath = "{{basePath}}";
private Map apiAuthorizations;
private Feign.Builder feignBuilder;
@@ -128,6 +129,13 @@ public class ApiClient {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
+ objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
+ objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ objectMapper.registerModule(new JodaModule());
+ return objectMapper;
+ }
+
+ public ObjectMapper getObjectMapper(){
return objectMapper;
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache
index fae7a93303d..c9d756d33ec 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache
@@ -26,7 +26,7 @@ public interface {{classname}} extends ApiClient.Api {
@RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}")
@Headers({
"Content-type: {{vendorExtensions.x-contentType}}",
- "Accepts: {{vendorExtensions.x-accepts}}",{{#headerParams}}
+ "Accept: {{vendorExtensions.x-accepts}}",{{#headerParams}}
"{{paramName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{#hasMore}},
{{/hasMore}}{{/headerParams}}
})
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api_test.mustache
new file mode 100644
index 00000000000..303fda344e9
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api_test.mustache
@@ -0,0 +1,44 @@
+package {{package}};
+
+import {{invokerPackage}}.ApiClient;
+{{#imports}}import {{import}};
+{{/imports}}
+import org.junit.Before;
+import org.junit.Test;
+
+{{^fullJavaUtil}}
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+{{/fullJavaUtil}}
+
+/**
+ * API tests for {{classname}}
+ */
+public class {{classname}}Test {
+
+ private {{classname}} api;
+
+ @Before
+ public void setup() {
+ api = new ApiClient().buildClient({{classname}}.class);
+ }
+
+ {{#operations}}{{#operation}}
+ /**
+ * {{summary}}
+ *
+ * {{notes}}
+ */
+ @Test
+ public void {{operationId}}Test() {
+ {{#allParams}}
+ {{{dataType}}} {{paramName}} = null;
+ {{/allParams}}
+ // {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
+
+ // TODO: test validations
+ }
+ {{/operation}}{{/operations}}
+}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache
index 74ff86ebd1b..1df88d403a2 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache
@@ -23,14 +23,17 @@ import feign.Request.Options;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Response;
+import feign.RetryableException;
import feign.Util;
import {{invokerPackage}}.StringUtil;
public class OAuth implements RequestInterceptor {
+ static final int MILLIS_PER_SECOND = 1000;
+
public interface AccessTokenListener {
- public void notify(BasicOAuthToken token);
+ void notify(BasicOAuthToken token);
}
private volatile String accessToken;
@@ -41,21 +44,13 @@ public class OAuth implements RequestInterceptor {
private AccessTokenListener accessTokenListener;
public OAuth(Client client, TokenRequestBuilder requestBuilder) {
- setOauthClient(client);
+ this.oauthClient = new OAuthClient(new OAuthFeignClient(client));
this.tokenRequestBuilder = requestBuilder;
}
public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes));
- setFlow(flow);
- authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl);
- }
- public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
- this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes);
- }
-
- public void setFlow(OAuthFlow flow) {
switch(flow) {
case accessCode:
case implicit:
@@ -70,6 +65,11 @@ public class OAuth implements RequestInterceptor {
default:
break;
}
+ authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl);
+ }
+
+ public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
+ this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes);
}
@Override
@@ -80,34 +80,29 @@ public class OAuth implements RequestInterceptor {
}
// If first time, get the token
if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) {
- try {
- updateAccessToken();
- } catch (OAuthSystemException e) {
- e.printStackTrace();
- return;
- } catch (OAuthProblemException e) {
- e.printStackTrace();
- return;
- }
+ updateAccessToken();
}
if (getAccessToken() != null) {
template.header("Authorization", "Bearer " + getAccessToken());
}
}
- public synchronized void updateAccessToken() throws OAuthSystemException, OAuthProblemException {
- if (getAccessToken() == null) {
- OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage());
- if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
- setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn());
- if (accessTokenListener != null) {
- accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken());
- }
+ public synchronized void updateAccessToken() {
+ OAuthJSONAccessTokenResponse accessTokenResponse;
+ try {
+ accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage());
+ } catch (Exception e) {
+ throw new RetryableException(e.getMessage(), e,null);
+ }
+ if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
+ setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn());
+ if (accessTokenListener != null) {
+ accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken());
}
}
}
- public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
+ public synchronized void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
this.accessTokenListener = accessTokenListener;
}
@@ -117,7 +112,7 @@ public class OAuth implements RequestInterceptor {
public synchronized void setAccessToken(String accessToken, Long expiresIn) {
this.accessToken = accessToken;
- this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * 1000;
+ this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND;
}
public TokenRequestBuilder getTokenRequestBuilder() {
@@ -148,7 +143,7 @@ public class OAuth implements RequestInterceptor {
this.oauthClient = new OAuthClient( new OAuthFeignClient(client));
}
- public class OAuthFeignClient implements HttpClient {
+ public static class OAuthFeignClient implements HttpClient {
private Client client;
@@ -198,6 +193,5 @@ public class OAuth implements RequestInterceptor {
public void shutdown() {
// Nothing to do here
}
-
}
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache
new file mode 100644
index 00000000000..37eabbd27b2
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache
@@ -0,0 +1,26 @@
+lazy val root = (project in file(".")).
+ settings(
+ organization := "{{groupId}}",
+ name := "{{artifactId}}",
+ version := "{{artifactVersion}}",
+ scalaVersion := "2.11.4",
+ scalacOptions ++= Seq("-feature"),
+ javacOptions in compile ++= Seq("-Xlint:deprecation"),
+ publishArtifact in (Compile, packageDoc) := false,
+ resolvers += Resolver.mavenLocal,
+ libraryDependencies ++= Seq(
+ "io.swagger" % "swagger-annotations" % "1.5.8" % "compile",
+ "com.netflix.feign" % "feign-core" % "8.16.0" % "compile",
+ "com.netflix.feign" % "feign-jackson" % "8.16.0" % "compile",
+ "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0" % "compile",
+ "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0" % "compile",
+ "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5" % "compile",
+ "joda-time" % "joda-time" % "2.9.3" % "compile",
+ "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
+ "com.brsanthu" % "migbase64" % "2.2" % "compile",
+ "junit" % "junit" % "4.12" % "test",
+ "com.novocode" % "junit-interface" % "0.10" % "test"
+ )
+ )
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache
index 03323a65a03..df5b965984e 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache
@@ -149,19 +149,7 @@
com.fasterxml.jackson.datatype
jackson-datatype-joda
- 2.1.5
-
-
- joda-time
- joda-time
- ${jodatime-version}
-
-
-
-
- com.brsanthu
- migbase64
- 2.2
+ ${jackson-version}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache
index 6c980b727fa..26cb9d7d946 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache
@@ -76,12 +76,12 @@ public class {{classname}} {
{{/formParams}}
final String[] {{localVariablePrefix}}localVarAccepts = {
- {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
+ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
};
final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts);
final String[] {{localVariablePrefix}}localVarContentTypes = {
- {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
+ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
};
final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache
new file mode 100644
index 00000000000..0a297497d9d
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.sbt.mustache
@@ -0,0 +1,25 @@
+lazy val root = (project in file(".")).
+ settings(
+ organization := "{{groupId}}",
+ name := "{{artifactId}}",
+ version := "{{artifactVersion}}",
+ scalaVersion := "2.11.4",
+ scalacOptions ++= Seq("-feature"),
+ javacOptions in compile ++= Seq("-Xlint:deprecation"),
+ publishArtifact in (Compile, packageDoc) := false,
+ resolvers += Resolver.mavenLocal,
+ libraryDependencies ++= Seq(
+ "io.swagger" % "swagger-annotations" % "1.5.8",
+ "org.glassfish.jersey.core" % "jersey-client" % "2.22.2",
+ "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.22.2",
+ "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.22.1",
+ "com.fasterxml.jackson.core" % "jackson-core" % "2.7.0",
+ "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.0",
+ "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.0",
+ "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.1.5",
+ "joda-time" % "joda-time" % "2.9.3",
+ "com.brsanthu" % "migbase64" % "2.2",
+ "junit" % "junit" % "4.12" % "test",
+ "com.novocode" % "junit-interface" % "0.10" % "test"
+ )
+ )
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache
index bfc1aedbc11..4cc99a76ec3 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}};
import java.io.IOException;
@@ -11,39 +13,39 @@ import java.util.List;
* @param The return type
*/
public interface ApiCallback {
- /**
- * This is called when the API call fails.
- *
- * @param e The exception causing the failure
- * @param statusCode Status code of the response if available, otherwise it would be 0
- * @param responseHeaders Headers of the response if available, otherwise it would be null
- */
- void onFailure(ApiException e, int statusCode, Map> responseHeaders);
+ /**
+ * This is called when the API call fails.
+ *
+ * @param e The exception causing the failure
+ * @param statusCode Status code of the response if available, otherwise it would be 0
+ * @param responseHeaders Headers of the response if available, otherwise it would be null
+ */
+ void onFailure(ApiException e, int statusCode, Map> responseHeaders);
- /**
- * This is called when the API call succeeded.
- *
- * @param result The result deserialized from response
- * @param statusCode Status code of the response
- * @param responseHeaders Headers of the response
- */
- void onSuccess(T result, int statusCode, Map> responseHeaders);
+ /**
+ * This is called when the API call succeeded.
+ *
+ * @param result The result deserialized from response
+ * @param statusCode Status code of the response
+ * @param responseHeaders Headers of the response
+ */
+ void onSuccess(T result, int statusCode, Map> responseHeaders);
- /**
- * This is called when the API upload processing.
- *
- * @param bytesWritten bytes Written
- * @param contentLength content length of request body
- * @param done write end
- */
- void onUploadProgress(long bytesWritten, long contentLength, boolean done);
+ /**
+ * This is called when the API upload processing.
+ *
+ * @param bytesWritten bytes Written
+ * @param contentLength content length of request body
+ * @param done write end
+ */
+ void onUploadProgress(long bytesWritten, long contentLength, boolean done);
- /**
- * This is called when the API downlond processing.
- *
- * @param bytesRead bytes Read
- * @param contentLength content lenngth of the response
- * @param done Read end
- */
- void onDownloadProgress(long bytesRead, long contentLength, boolean done);
+ /**
+ * This is called when the API downlond processing.
+ *
+ * @param bytesRead bytes Read
+ * @param contentLength content lenngth of the response
+ * @param done Read end
+ */
+ void onDownloadProgress(long bytesRead, long contentLength, boolean done);
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache
index 4c8e304ed97..3d6b3fe17f0 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}};
import com.squareup.okhttp.Call;
@@ -67,1073 +69,1234 @@ import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.OAuth;
public class ApiClient {
- public static final double JAVA_VERSION;
- public static final boolean IS_ANDROID;
- public static final int ANDROID_SDK_VERSION;
+ public static final double JAVA_VERSION;
+ public static final boolean IS_ANDROID;
+ public static final int ANDROID_SDK_VERSION;
- static {
- JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version"));
- boolean isAndroid;
- try {
- Class.forName("android.app.Activity");
- isAndroid = true;
- } catch (ClassNotFoundException e) {
- isAndroid = false;
- }
- IS_ANDROID = isAndroid;
- int sdkVersion = 0;
- if (IS_ANDROID) {
- try {
- sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null);
- } catch (Exception e) {
+ static {
+ JAVA_VERSION = Double.parseDouble(System.getProperty("java.specification.version"));
+ boolean isAndroid;
try {
- sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null));
- } catch (Exception e2) { }
- }
+ Class.forName("android.app.Activity");
+ isAndroid = true;
+ } catch (ClassNotFoundException e) {
+ isAndroid = false;
+ }
+ IS_ANDROID = isAndroid;
+ int sdkVersion = 0;
+ if (IS_ANDROID) {
+ try {
+ sdkVersion = Class.forName("android.os.Build$VERSION").getField("SDK_INT").getInt(null);
+ } catch (Exception e) {
+ try {
+ sdkVersion = Integer.parseInt((String) Class.forName("android.os.Build$VERSION").getField("SDK").get(null));
+ } catch (Exception e2) { }
+ }
+ }
+ ANDROID_SDK_VERSION = sdkVersion;
}
- ANDROID_SDK_VERSION = sdkVersion;
- }
- /**
- * The datetime format to be used when lenientDatetimeFormat
is enabled.
- */
- public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
+ /**
+ * The datetime format to be used when lenientDatetimeFormat
is enabled.
+ */
+ public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
- private String basePath = "{{basePath}}";
- private boolean lenientOnJson = false;
- private boolean debugging = false;
- private Map defaultHeaderMap = new HashMap();
- private String tempFolderPath = null;
+ private String basePath = "{{basePath}}";
+ private boolean lenientOnJson = false;
+ private boolean debugging = false;
+ private Map defaultHeaderMap = new HashMap();
+ private String tempFolderPath = null;
- private Map authentications;
+ private Map authentications;
- private DateFormat dateFormat;
- private DateFormat datetimeFormat;
- private boolean lenientDatetimeFormat;
- private int dateLength;
+ private DateFormat dateFormat;
+ private DateFormat datetimeFormat;
+ private boolean lenientDatetimeFormat;
+ private int dateLength;
- private InputStream sslCaCert;
- private boolean verifyingSsl;
+ private InputStream sslCaCert;
+ private boolean verifyingSsl;
- private OkHttpClient httpClient;
- private JSON json;
+ private OkHttpClient httpClient;
+ private JSON json;
- private HttpLoggingInterceptor loggingInterceptor;
-
- public ApiClient() {
- httpClient = new OkHttpClient();
-
- verifyingSsl = true;
-
- json = new JSON(this);
+ private HttpLoggingInterceptor loggingInterceptor;
/*
- * Use RFC3339 format for date and datetime.
- * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
+ * Constructor for ApiClient
*/
- this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
- // Always use UTC as the default time zone when dealing with date (without time).
- this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
- initDatetimeFormat();
+ public ApiClient() {
+ httpClient = new OkHttpClient();
- // Be lenient on datetime formats when parsing datetime from string.
- // See parseDatetime
.
- this.lenientDatetimeFormat = true;
+ verifyingSsl = true;
- // Set default User-Agent.
- setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}");
+ json = new JSON(this);
- // Setup authentications (key: authentication name, value: authentication).
- authentications = new HashMap();{{#authMethods}}{{#isBasic}}
- authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
- authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
- authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
- // Prevent the authentications from being modified.
- authentications = Collections.unmodifiableMap(authentications);
- }
+ /*
+ * Use RFC3339 format for date and datetime.
+ * See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
+ */
+ this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
+ // Always use UTC as the default time zone when dealing with date (without time).
+ this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ initDatetimeFormat();
- public String getBasePath() {
- return basePath;
- }
+ // Be lenient on datetime formats when parsing datetime from string.
+ // See parseDatetime
.
+ this.lenientDatetimeFormat = true;
- public ApiClient setBasePath(String basePath) {
- this.basePath = basePath;
- return this;
- }
+ // Set default User-Agent.
+ setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/java{{/httpUserAgent}}");
- public OkHttpClient getHttpClient() {
- return httpClient;
- }
-
- public ApiClient setHttpClient(OkHttpClient httpClient) {
- this.httpClient = httpClient;
- return this;
- }
-
- public JSON getJSON() {
- return json;
- }
-
- public ApiClient setJSON(JSON json) {
- this.json = json;
- return this;
- }
-
- public boolean isVerifyingSsl() {
- return verifyingSsl;
- }
-
- /**
- * Configure whether to verify certificate and hostname when making https requests.
- * Default to true.
- * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks.
- */
- public ApiClient setVerifyingSsl(boolean verifyingSsl) {
- this.verifyingSsl = verifyingSsl;
- applySslSettings();
- return this;
- }
-
- public InputStream getSslCaCert() {
- return sslCaCert;
- }
-
- /**
- * Configure the CA certificate to be trusted when making https requests.
- * Use null to reset to default.
- */
- public ApiClient setSslCaCert(InputStream sslCaCert) {
- this.sslCaCert = sslCaCert;
- applySslSettings();
- return this;
- }
-
- public DateFormat getDateFormat() {
- return dateFormat;
- }
-
- public ApiClient setDateFormat(DateFormat dateFormat) {
- this.dateFormat = dateFormat;
- this.dateLength = this.dateFormat.format(new Date()).length();
- return this;
- }
-
- public DateFormat getDatetimeFormat() {
- return datetimeFormat;
- }
-
- public ApiClient setDatetimeFormat(DateFormat datetimeFormat) {
- this.datetimeFormat = datetimeFormat;
- return this;
- }
-
- /**
- * Whether to allow various ISO 8601 datetime formats when parsing a datetime string.
- * @see #parseDatetime(String)
- */
- public boolean isLenientDatetimeFormat() {
- return lenientDatetimeFormat;
- }
-
- public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) {
- this.lenientDatetimeFormat = lenientDatetimeFormat;
- return this;
- }
-
- /**
- * Parse the given date string into Date object.
- * The default dateFormat
supports these ISO 8601 date formats:
- * 2015-08-16
- * 2015-8-16
- */
- public Date parseDate(String str) {
- if (str == null)
- return null;
- try {
- return dateFormat.parse(str);
- } catch (ParseException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Parse the given datetime string into Date object.
- * When lenientDatetimeFormat
is enabled, the following ISO 8601 datetime formats are supported:
- * 2015-08-16T08:20:05Z
- * 2015-8-16T8:20:05Z
- * 2015-08-16T08:20:05+00:00
- * 2015-08-16T08:20:05+0000
- * 2015-08-16T08:20:05.376Z
- * 2015-08-16T08:20:05.376+00:00
- * 2015-08-16T08:20:05.376+00
- * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of
- * these formats:
- * Z (same with +0000)
- * +08:00 (same with +0800)
- * -02 (same with -0200)
- * -0200
- * @see https://en.wikipedia.org/wiki/ISO_8601
- */
- public Date parseDatetime(String str) {
- if (str == null)
- return null;
-
- DateFormat format;
- if (lenientDatetimeFormat) {
- /*
- * When lenientDatetimeFormat is enabled, normalize the date string
- * into LENIENT_DATETIME_FORMAT
to support various formats
- * defined by ISO 8601.
- */
- // normalize time zone
- // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000
- str = str.replaceAll("[zZ]\\z", "+0000");
- // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000
- str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2");
- // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000
- str = str.replaceAll("([+-]\\d{2})\\z", "$100");
- // add milliseconds when missing
- // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000
- str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2");
- format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT);
- } else {
- format = this.datetimeFormat;
+ // Setup authentications (key: authentication name, value: authentication).
+ authentications = new HashMap();{{#authMethods}}{{#isBasic}}
+ authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
+ authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
+ authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
+ // Prevent the authentications from being modified.
+ authentications = Collections.unmodifiableMap(authentications);
}
- try {
- return format.parse(str);
- } catch (ParseException e) {
- throw new RuntimeException(e);
- }
- }
-
- public Date parseDateOrDatetime(String str) {
- if (str == null)
- return null;
- else if (str.length() <= dateLength)
- return parseDate(str);
- else
- return parseDatetime(str);
- }
-
- /**
- * Format the given Date object into string.
- */
- public String formatDate(Date date) {
- return dateFormat.format(date);
- }
-
- /**
- * Format the given Date object into string.
- */
- public String formatDatetime(Date date) {
- return datetimeFormat.format(date);
- }
-
- /**
- * 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!");
- }
-
- /**
- * Helper method to set access token for the first OAuth2 authentication.
- */
- public void setAccessToken(String accessToken) {
- for (Authentication auth : authentications.values()) {
- if (auth instanceof OAuth) {
- ((OAuth) auth).setAccessToken(accessToken);
- return;
- }
- }
- throw new RuntimeException("No OAuth2 authentication configured!");
- }
-
- /**
- * Set the User-Agent header's value (by adding to the default header map).
- */
- 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;
- }
-
- /**
- * @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
- */
- public boolean isLenientOnJson() {
- return lenientOnJson;
- }
-
- public ApiClient setLenientOnJson(boolean lenient) {
- this.lenientOnJson = lenient;
- 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) {
- if (debugging != this.debugging) {
- if (debugging) {
- loggingInterceptor = new HttpLoggingInterceptor();
- loggingInterceptor.setLevel(Level.BODY);
- httpClient.interceptors().add(loggingInterceptor);
- } else {
- httpClient.interceptors().remove(loggingInterceptor);
- loggingInterceptor = null;
- }
- }
- this.debugging = debugging;
- return this;
- }
-
- /**
- * The path of temporary folder used to store downloaded files from endpoints
- * with file response. The default value is null
, i.e. using
- * the system's default tempopary folder.
- *
- * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File)
- */
- public String getTempFolderPath() {
- return tempFolderPath;
- }
-
- public ApiClient setTempFolderPath(String tempFolderPath) {
- this.tempFolderPath = tempFolderPath;
- return this;
- }
-
- /**
- * Connect timeout (in milliseconds).
- */
- public int getConnectTimeout() {
- return httpClient.getConnectTimeout();
- }
-
- /**
- * Sets the connect timeout (in milliseconds).
- * A value of 0 means no timeout, otherwise values must be between 1 and
- * {@link Integer#MAX_VALUE}.
- */
- public ApiClient setConnectTimeout(int connectionTimeout) {
- httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS);
- return this;
- }
-
- /**
- * Format the given parameter object into string.
- */
- public String parameterToString(Object param) {
- if (param == null) {
- return "";
- } else if (param instanceof Date) {
- return formatDatetime((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;
+ /**
+ * Get base path
+ *
+ * @return Baes path
+ */
+ public String getBasePath() {
+ return basePath;
}
- if (valueCollection.isEmpty()){
- return params;
+ /**
+ * Set base path
+ *
+ * @param basePath Base path of the URL (e.g {{basePath}})
+ * @return An instance of OkHttpClient
+ */
+ public ApiClient setBasePath(String basePath) {
+ this.basePath = basePath;
+ return this;
}
- // 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;
+ /**
+ * Get HTTP client
+ *
+ * @return An instance of OkHttpClient
+ */
+ public OkHttpClient getHttpClient() {
+ return httpClient;
}
- 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 = "|";
+ /**
+ * Set HTTP client
+ *
+ * @param httpClient An instance of OkHttpClient
+ * @return Api Client
+ */
+ public ApiClient setHttpClient(OkHttpClient httpClient) {
+ this.httpClient = httpClient;
+ return this;
}
- StringBuilder sb = new StringBuilder() ;
- for (Object item : valueCollection) {
- sb.append(delimiter);
- sb.append(parameterToString(item));
+ /**
+ * Get JSON
+ *
+ * @return JSON object
+ */
+ public JSON getJSON() {
+ return json;
}
- params.add(new Pair(name, sb.substring(1)));
-
- return params;
- }
-
- /**
- * Sanitize filename by removing path.
- * e.g. ../../sun.gif becomes sun.gif
- *
- * @param filename The filename to be sanitized
- * @return The sanitized filename
- */
- public String sanitizeFilename(String filename) {
- return filename.replaceAll(".*[/\\\\]", "");
- }
-
- /**
- * Check if the given MIME is a JSON MIME.
- * JSON MIME examples:
- * application/json
- * application/json; charset=UTF8
- * APPLICATION/JSON
- */
- public boolean isJsonMime(String mime) {
- return mime != null && mime.matches("(?i)application\\/json(;.*)?");
- }
-
- /**
- * 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;
- }
- for (String accept : accepts) {
- if (isJsonMime(accept)) {
- return accept;
- }
- }
- 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";
- }
- for (String contentType : contentTypes) {
- if (isJsonMime(contentType)) {
- return contentType;
- }
- }
- 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;
- }
- }
-
- /**
- * Deserialize response body to Java object, according to the return type and
- * the Content-Type response header.
- *
- * @param response HTTP response
- * @param returnType The type of the Java object
- * @return The deserialized Java object
- * @throws ApiException If fail to deserialize response body, i.e. cannot read response body
- * or the Content-Type of the response is not supported.
- */
- public T deserialize(Response response, Type returnType) throws ApiException {
- if (response == null || returnType == null) {
- return null;
+ /**
+ * Set JSON
+ *
+ * @param json JSON object
+ * @return Api client
+ */
+ public ApiClient setJSON(JSON json) {
+ this.json = json;
+ return this;
}
- if ("byte[]".equals(returnType.toString())) {
- // Handle binary response (byte array).
- try {
- return (T) response.body().bytes();
- } catch (IOException e) {
- throw new ApiException(e);
- }
- } else if (returnType.equals(File.class)) {
- // Handle file downloading.
- return (T) downloadFileFromResponse(response);
+ /**
+ * True if isVerifyingSsl flag is on
+ *
+ * @return True if isVerifySsl flag is on
+ */
+ public boolean isVerifyingSsl() {
+ return verifyingSsl;
}
- String respBody;
- try {
- if (response.body() != null)
- respBody = response.body().string();
- else
- respBody = null;
- } catch (IOException e) {
- throw new ApiException(e);
+ /**
+ * Configure whether to verify certificate and hostname when making https requests.
+ * Default to true.
+ * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks.
+ *
+ * @param verifyingSsl True to verify TLS/SSL connection
+ * @return ApiClient
+ */
+ public ApiClient setVerifyingSsl(boolean verifyingSsl) {
+ this.verifyingSsl = verifyingSsl;
+ applySslSettings();
+ return this;
}
- if (respBody == null || "".equals(respBody)) {
- return null;
+ /**
+ * Get SSL CA cert.
+ *
+ * @return Input stream to the SSL CA cert
+ */
+ public InputStream getSslCaCert() {
+ return sslCaCert;
}
- String contentType = response.headers().get("Content-Type");
- if (contentType == null) {
- // ensuring a default content type
- contentType = "application/json";
- }
- if (isJsonMime(contentType)) {
- return json.deserialize(respBody, returnType);
- } else if (returnType.equals(String.class)) {
- // Expecting string, return the raw response body.
- return (T) respBody;
- } else {
- throw new ApiException(
- "Content type \"" + contentType + "\" is not supported for type: " + returnType,
- response.code(),
- response.headers().toMultimap(),
- respBody);
- }
- }
-
- /**
- * Serialize the given Java object into request body according to the object's
- * class and the request Content-Type.
- *
- * @param obj The Java object
- * @param contentType The request Content-Type
- * @return The serialized request body
- * @throws ApiException If fail to serialize the given object
- */
- public RequestBody serialize(Object obj, String contentType) throws ApiException {
- if (obj instanceof byte[]) {
- // Binary (byte array) body parameter support.
- return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
- } else if (obj instanceof File) {
- // File body parameter support.
- return RequestBody.create(MediaType.parse(contentType), (File) obj);
- } else if (isJsonMime(contentType)) {
- String content;
- if (obj != null) {
- content = json.serialize(obj);
- } else {
- content = null;
- }
- return RequestBody.create(MediaType.parse(contentType), content);
- } else {
- throw new ApiException("Content type \"" + contentType + "\" is not supported");
- }
- }
-
- /**
- * Download file from the given response.
- * @throws ApiException If fail to read file content from response and write to disk
- */
- public File downloadFileFromResponse(Response response) throws ApiException {
- try {
- File file = prepareDownloadFile(response);
- BufferedSink sink = Okio.buffer(Okio.sink(file));
- sink.writeAll(response.body().source());
- sink.close();
- return file;
- } catch (IOException e) {
- throw new ApiException(e);
- }
- }
-
- public File prepareDownloadFile(Response response) throws IOException {
- String filename = null;
- String contentDisposition = response.header("Content-Disposition");
- if (contentDisposition != null && !"".equals(contentDisposition)) {
- // Get filename from the Content-Disposition header.
- Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?");
- Matcher matcher = pattern.matcher(contentDisposition);
- if (matcher.find()) {
- filename = sanitizeFilename(matcher.group(1));
- }
+ /**
+ * Configure the CA certificate to be trusted when making https requests.
+ * Use null to reset to default.
+ *
+ * @param sslCaCert input stream for SSL CA cert
+ * @return ApiClient
+ */
+ public ApiClient setSslCaCert(InputStream sslCaCert) {
+ this.sslCaCert = sslCaCert;
+ applySslSettings();
+ return this;
}
- String prefix = null;
- String suffix = null;
- if (filename == null) {
- prefix = "download-";
- suffix = "";
- } else {
- int pos = filename.lastIndexOf(".");
- if (pos == -1) {
- prefix = filename + "-";
- } else {
- prefix = filename.substring(0, pos) + "-";
- suffix = filename.substring(pos);
- }
- // File.createTempFile requires the prefix to be at least three characters long
- if (prefix.length() < 3)
- prefix = "download-";
+ public DateFormat getDateFormat() {
+ return dateFormat;
}
- if (tempFolderPath == null)
- return File.createTempFile(prefix, suffix);
- else
- return File.createTempFile(prefix, suffix, new File(tempFolderPath));
- }
-
- /**
- * @see #execute(Call, Type)
- */
- public ApiResponse execute(Call call) throws ApiException {
- return execute(call, null);
- }
-
- /**
- * Execute HTTP call and deserialize the HTTP response body into the given return type.
- *
- * @param returnType The return type used to deserialize HTTP response body
- * @param The return type corresponding to (same with) returnType
- * @return ApiResponse
object containing response status, headers and
- * data, which is a Java object deserialized from response body and would be null
- * when returnType is null.
- * @throws ApiException If fail to execute the call
- */
- public ApiResponse execute(Call call, Type returnType) throws ApiException {
- try {
- Response response = call.execute();
- T data = handleResponse(response, returnType);
- return new ApiResponse(response.code(), response.headers().toMultimap(), data);
- } catch (IOException e) {
- throw new ApiException(e);
+ public ApiClient setDateFormat(DateFormat dateFormat) {
+ this.dateFormat = dateFormat;
+ this.dateLength = this.dateFormat.format(new Date()).length();
+ return this;
}
- }
- /**
- * #see executeAsync(Call, Type, ApiCallback)
- */
- public void executeAsync(Call call, ApiCallback callback) {
- executeAsync(call, null, callback);
- }
+ public DateFormat getDatetimeFormat() {
+ return datetimeFormat;
+ }
- /**
- * Execute HTTP call asynchronously.
- *
- * @see #execute(Call, Type)
- * @param The callback to be executed when the API call finishes
- */
- public void executeAsync(Call call, final Type returnType, final ApiCallback callback) {
- call.enqueue(new Callback() {
- @Override
- public void onFailure(Request request, IOException e) {
- callback.onFailure(new ApiException(e), 0, null);
- }
+ public ApiClient setDatetimeFormat(DateFormat datetimeFormat) {
+ this.datetimeFormat = datetimeFormat;
+ return this;
+ }
- @Override
- public void onResponse(Response response) throws IOException {
- T result;
+ /**
+ * Whether to allow various ISO 8601 datetime formats when parsing a datetime string.
+ * @see #parseDatetime(String)
+ * @return True if lenientDatetimeFormat flag is set to true
+ */
+ public boolean isLenientDatetimeFormat() {
+ return lenientDatetimeFormat;
+ }
+
+ public ApiClient setLenientDatetimeFormat(boolean lenientDatetimeFormat) {
+ this.lenientDatetimeFormat = lenientDatetimeFormat;
+ return this;
+ }
+
+ /**
+ * Parse the given date string into Date object.
+ * The default dateFormat
supports these ISO 8601 date formats:
+ * 2015-08-16
+ * 2015-8-16
+ * @param str String to be parsed
+ * @return Date
+ */
+ public Date parseDate(String str) {
+ if (str == null)
+ return null;
try {
- result = (T) handleResponse(response, returnType);
- } catch (ApiException e) {
- callback.onFailure(e, response.code(), response.headers().toMultimap());
- return;
+ return dateFormat.parse(str);
+ } catch (ParseException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Parse the given datetime string into Date object.
+ * When lenientDatetimeFormat is enabled, the following ISO 8601 datetime formats are supported:
+ * 2015-08-16T08:20:05Z
+ * 2015-8-16T8:20:05Z
+ * 2015-08-16T08:20:05+00:00
+ * 2015-08-16T08:20:05+0000
+ * 2015-08-16T08:20:05.376Z
+ * 2015-08-16T08:20:05.376+00:00
+ * 2015-08-16T08:20:05.376+00
+ * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of
+ * these formats:
+ * Z (same with +0000)
+ * +08:00 (same with +0800)
+ * -02 (same with -0200)
+ * -0200
+ * @see ISO 8601
+ * @param str Date time string to be parsed
+ * @return Date representation of the string
+ */
+ public Date parseDatetime(String str) {
+ if (str == null)
+ return null;
+
+ DateFormat format;
+ if (lenientDatetimeFormat) {
+ /*
+ * When lenientDatetimeFormat is enabled, normalize the date string
+ * into LENIENT_DATETIME_FORMAT
to support various formats
+ * defined by ISO 8601.
+ */
+ // normalize time zone
+ // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000
+ str = str.replaceAll("[zZ]\\z", "+0000");
+ // remove colon in time zone: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000
+ str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2");
+ // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000
+ str = str.replaceAll("([+-]\\d{2})\\z", "$100");
+ // add milliseconds when missing
+ // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000
+ str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2");
+ format = new SimpleDateFormat(LENIENT_DATETIME_FORMAT);
+ } else {
+ format = this.datetimeFormat;
}
- callback.onSuccess(result, response.code(), response.headers().toMultimap());
- }
- });
- }
- /**
- * Handle the given response, return the deserialized object when the response is successful.
- *
- * @throws ApiException If the response has a unsuccessful status code or
- * fail to deserialize the response body
- */
- public T handleResponse(Response response, Type returnType) throws ApiException {
- if (response.isSuccessful()) {
- if (returnType == null || response.code() == 204) {
- // returning null if the returnType is not defined,
- // or the status code is 204 (No Content)
- return null;
- } else {
- return deserialize(response, returnType);
- }
- } else {
- String respBody = null;
- if (response.body() != null) {
try {
- respBody = response.body().string();
+ return format.parse(str);
+ } catch (ParseException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /*
+ * Parse date or date time in string format into Date object.
+ *
+ * @param str Date time string to be parsed
+ * @return Date representation of the string
+ */
+ public Date parseDateOrDatetime(String str) {
+ if (str == null)
+ return null;
+ else if (str.length() <= dateLength)
+ return parseDate(str);
+ else
+ return parseDatetime(str);
+ }
+
+ /**
+ * Format the given Date object into string (Date format).
+ *
+ * @param date Date object
+ * @return Formatted date in string representation
+ */
+ public String formatDate(Date date) {
+ return dateFormat.format(date);
+ }
+
+ /**
+ * Format the given Date object into string (Datetime format).
+ *
+ * @param date Date object
+ * @return Formatted datetime in string representation
+ */
+ public String formatDatetime(Date date) {
+ return datetimeFormat.format(date);
+ }
+
+ /**
+ * Get authentications (key: authentication name, value: authentication).
+ *
+ * @return Map of authentication objects
+ */
+ 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.
+ *
+ * @param username Username
+ */
+ 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.
+ *
+ * @param password Password
+ */
+ 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.
+ *
+ * @param apiKey API key
+ */
+ 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.
+ *
+ * @param apiKeyPrefix API key prefix
+ */
+ 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!");
+ }
+
+ /**
+ * Helper method to set access token for the first OAuth2 authentication.
+ *
+ * @param accessToken Access token
+ */
+ public void setAccessToken(String accessToken) {
+ for (Authentication auth : authentications.values()) {
+ if (auth instanceof OAuth) {
+ ((OAuth) auth).setAccessToken(accessToken);
+ return;
+ }
+ }
+ throw new RuntimeException("No OAuth2 authentication configured!");
+ }
+
+ /**
+ * Set the User-Agent header's value (by adding to the default header map).
+ *
+ * @param userAgent HTTP request's user agent
+ * @return ApiClient
+ */
+ 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
+ * @return ApiClient
+ */
+ public ApiClient addDefaultHeader(String key, String value) {
+ defaultHeaderMap.put(key, value);
+ return this;
+ }
+
+ /**
+ * @see setLenient
+ *
+ * @return True if lenientOnJson is enabled, false otherwise.
+ */
+ public boolean isLenientOnJson() {
+ return lenientOnJson;
+ }
+
+ /**
+ * Set LenientOnJson
+ *
+ * @param lenient True to enable lenientOnJson
+ * @return ApiClient
+ */
+ public ApiClient setLenientOnJson(boolean lenient) {
+ this.lenientOnJson = lenient;
+ return this;
+ }
+
+ /**
+ * Check that whether debugging is enabled for this API client.
+ *
+ * @return True if debugging is enabled, false otherwise.
+ */
+ public boolean isDebugging() {
+ return debugging;
+ }
+
+ /**
+ * Enable/disable debugging for this API client.
+ *
+ * @param debugging To enable (true) or disable (false) debugging
+ * @return ApiClient
+ */
+ public ApiClient setDebugging(boolean debugging) {
+ if (debugging != this.debugging) {
+ if (debugging) {
+ loggingInterceptor = new HttpLoggingInterceptor();
+ loggingInterceptor.setLevel(Level.BODY);
+ httpClient.interceptors().add(loggingInterceptor);
+ } else {
+ httpClient.interceptors().remove(loggingInterceptor);
+ loggingInterceptor = null;
+ }
+ }
+ this.debugging = debugging;
+ return this;
+ }
+
+ /**
+ * The path of temporary folder used to store downloaded files from endpoints
+ * with file response. The default value is null
, i.e. using
+ * the system's default tempopary folder.
+ *
+ * @see createTempFile
+ * @return Temporary folder path
+ */
+ public String getTempFolderPath() {
+ return tempFolderPath;
+ }
+
+ /**
+ * Set the tempoaray folder path (for downloading files)
+ *
+ * @param tempFolderPath Temporary folder path
+ * @return ApiClient
+ */
+ public ApiClient setTempFolderPath(String tempFolderPath) {
+ this.tempFolderPath = tempFolderPath;
+ return this;
+ }
+
+ /**
+ * Get connection timeout (in milliseconds).
+ *
+ * @return Timeout in milliseconds
+ */
+ public int getConnectTimeout() {
+ return httpClient.getConnectTimeout();
+ }
+
+ /**
+ * Sets the connect timeout (in milliseconds).
+ * A value of 0 means no timeout, otherwise values must be between 1 and
+ *
+ * @param connectionTimeout connection timeout in milliseconds
+ * @return Api client
+ */
+ public ApiClient setConnectTimeout(int connectionTimeout) {
+ httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS);
+ return this;
+ }
+
+ /**
+ * Format the given parameter object into string.
+ *
+ * @param param Parameter
+ * @return String representation of the parameter
+ */
+ public String parameterToString(Object param) {
+ if (param == null) {
+ return "";
+ } else if (param instanceof Date) {
+ return formatDatetime((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.
+ *
+ * @param collectionFormat collection format (e.g. csv, tsv)
+ * @param name Name
+ * @param value Value
+ * @return A list of 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;
+ }
+
+ /**
+ * Sanitize filename by removing path.
+ * e.g. ../../sun.gif becomes sun.gif
+ *
+ * @param filename The filename to be sanitized
+ * @return The sanitized filename
+ */
+ public String sanitizeFilename(String filename) {
+ return filename.replaceAll(".*[/\\\\]", "");
+ }
+
+ /**
+ * Check if the given MIME is a JSON MIME.
+ * JSON MIME examples:
+ * application/json
+ * application/json; charset=UTF8
+ * APPLICATION/JSON
+ *
+ * @param mime MIME (Multipurpose Internet Mail Extensions)
+ * @return True if the given MIME is JSON, false otherwise.
+ */
+ public boolean isJsonMime(String mime) {
+ return mime != null && mime.matches("(?i)application\\/json(;.*)?");
+ }
+
+ /**
+ * 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;
+ }
+ for (String accept : accepts) {
+ if (isJsonMime(accept)) {
+ return accept;
+ }
+ }
+ 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";
+ }
+ for (String contentType : contentTypes) {
+ if (isJsonMime(contentType)) {
+ return contentType;
+ }
+ }
+ return contentTypes[0];
+ }
+
+ /**
+ * Escape the given string to be used as URL query value.
+ *
+ * @param str String to be escaped
+ * @return Escaped string
+ */
+ public String escapeString(String str) {
+ try {
+ return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
+ } catch (UnsupportedEncodingException e) {
+ return str;
+ }
+ }
+
+ /**
+ * Deserialize response body to Java object, according to the return type and
+ * the Content-Type response header.
+ *
+ * @param Type
+ * @param response HTTP response
+ * @param returnType The type of the Java object
+ * @return The deserialized Java object
+ * @throws ApiException If fail to deserialize response body, i.e. cannot read response body
+ * or the Content-Type of the response is not supported.
+ */
+ public T deserialize(Response response, Type returnType) throws ApiException {
+ if (response == null || returnType == null) {
+ return null;
+ }
+
+ if ("byte[]".equals(returnType.toString())) {
+ // Handle binary response (byte array).
+ try {
+ return (T) response.body().bytes();
+ } catch (IOException e) {
+ throw new ApiException(e);
+ }
+ } else if (returnType.equals(File.class)) {
+ // Handle file downloading.
+ return (T) downloadFileFromResponse(response);
+ }
+
+ String respBody;
+ try {
+ if (response.body() != null)
+ respBody = response.body().string();
+ else
+ respBody = null;
} catch (IOException e) {
- throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
+ throw new ApiException(e);
}
- }
- throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
- }
- }
- /**
- * Build HTTP call with the given options.
- *
- * @param path The sub-path of the HTTP URL
- * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
- * @param queryParams The query parameters
- * @param body The request body object
- * @param headerParams The header parameters
- * @param formParams The form parameters
- * @param authNames The authentications to apply
- * @return The HTTP call
- * @throws ApiException If fail to serialize the request body object
- */
- public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
- updateParamsForAuth(authNames, queryParams, headerParams);
-
- final String url = buildUrl(path, queryParams);
- final Request.Builder reqBuilder = new Request.Builder().url(url);
- processHeaderParams(headerParams, reqBuilder);
-
- String contentType = (String) headerParams.get("Content-Type");
- // ensuring a default content type
- if (contentType == null) {
- contentType = "application/json";
- }
-
- RequestBody reqBody;
- if (!HttpMethod.permitsRequestBody(method)) {
- reqBody = null;
- } else if ("application/x-www-form-urlencoded".equals(contentType)) {
- reqBody = buildRequestBodyFormEncoding(formParams);
- } else if ("multipart/form-data".equals(contentType)) {
- reqBody = buildRequestBodyMultipart(formParams);
- } else if (body == null) {
- if ("DELETE".equals(method)) {
- // allow calling DELETE without sending a request body
- reqBody = null;
- } else {
- // use an empty request body (for POST, PUT and PATCH)
- reqBody = RequestBody.create(MediaType.parse(contentType), "");
- }
- } else {
- reqBody = serialize(body, contentType);
- }
-
- Request request = null;
-
- if(progressRequestListener != null && reqBody != null) {
- ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener);
- request = reqBuilder.method(method, progressRequestBody).build();
- } else {
- request = reqBuilder.method(method, reqBody).build();
- }
-
- return httpClient.newCall(request);
- }
-
- /**
- * Build full URL by concatenating base path, the given sub path and query parameters.
- *
- * @param path The sub path
- * @param queryParams The query parameters
- * @return The full URL
- */
- public String buildUrl(String path, List queryParams) {
- final StringBuilder url = new StringBuilder();
- url.append(basePath).append(path);
-
- if (queryParams != null && !queryParams.isEmpty()) {
- // support (constant) query string in `path`, e.g. "/posts?draft=1"
- String prefix = path.contains("?") ? "&" : "?";
- for (Pair param : queryParams) {
- if (param.getValue() != null) {
- if (prefix != null) {
- url.append(prefix);
- prefix = null;
- } else {
- url.append("&");
- }
- String value = parameterToString(param.getValue());
- url.append(escapeString(param.getName())).append("=").append(escapeString(value));
+ if (respBody == null || "".equals(respBody)) {
+ return null;
}
- }
- }
- return url.toString();
- }
-
- /**
- * Set header parameters to the request builder, including default headers.
- */
- public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) {
- for (Entry param : headerParams.entrySet()) {
- reqBuilder.header(param.getKey(), parameterToString(param.getValue()));
- }
- for (Entry header : defaultHeaderMap.entrySet()) {
- if (!headerParams.containsKey(header.getKey())) {
- reqBuilder.header(header.getKey(), parameterToString(header.getValue()));
- }
- }
- }
-
- /**
- * Update query and header parameters based on authentication settings.
- *
- * @param authNames The authentications to apply
- */
- public 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);
- }
- }
-
- /**
- * Build a form-encoding request body with the given form parameters.
- */
- public RequestBody buildRequestBodyFormEncoding(Map formParams) {
- FormEncodingBuilder formBuilder = new FormEncodingBuilder();
- for (Entry param : formParams.entrySet()) {
- formBuilder.add(param.getKey(), parameterToString(param.getValue()));
- }
- return formBuilder.build();
- }
-
- /**
- * Build a multipart (file uploading) request body with the given form parameters,
- * which could contain text fields and file fields.
- */
- public RequestBody buildRequestBodyMultipart(Map formParams) {
- MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
- for (Entry param : formParams.entrySet()) {
- if (param.getValue() instanceof File) {
- File file = (File) param.getValue();
- Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\"");
- MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
- mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file));
- } else {
- Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"");
- mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue())));
- }
- }
- return mpBuilder.build();
- }
-
- /**
- * Guess Content-Type header from the given file (defaults to "application/octet-stream").
- *
- * @param file The given file
- * @return The Content-Type guessed
- */
- public String guessContentTypeFromFile(File file) {
- String contentType = URLConnection.guessContentTypeFromName(file.getName());
- if (contentType == null) {
- return "application/octet-stream";
- } else {
- return contentType;
- }
- }
-
- /**
- * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android.
- */
- private void initDatetimeFormat() {
- String formatWithTimeZone = null;
- if (IS_ANDROID) {
- if (ANDROID_SDK_VERSION >= 18) {
- // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18)
- formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ";
- }
- } else if (JAVA_VERSION >= 1.7) {
- // The time zone format "XXX" is available since Java 1.7
- formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
- }
- if (formatWithTimeZone != null) {
- this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone);
- // NOTE: Use the system's default time zone (mainly for datetime formatting).
- } else {
- // Use a common format that works across all systems.
- this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
- // Always use the UTC time zone as we are using a constant trailing "Z" here.
- this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
- }
- }
-
- /**
- * Apply SSL related settings to httpClient according to the current values of
- * verifyingSsl and sslCaCert.
- */
- private void applySslSettings() {
- try {
- KeyManager[] keyManagers = null;
- TrustManager[] trustManagers = null;
- HostnameVerifier hostnameVerifier = null;
- if (!verifyingSsl) {
- TrustManager trustAll = new X509TrustManager() {
- @Override
- public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
- @Override
- public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
- @Override
- public X509Certificate[] getAcceptedIssuers() { return null; }
- };
- SSLContext sslContext = SSLContext.getInstance("TLS");
- trustManagers = new TrustManager[]{ trustAll };
- hostnameVerifier = new HostnameVerifier() {
- @Override
- public boolean verify(String hostname, SSLSession session) { return true; }
- };
- } else if (sslCaCert != null) {
- char[] password = null; // Any password will work.
- CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
- Collection extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
- if (certificates.isEmpty()) {
- throw new IllegalArgumentException("expected non-empty set of trusted certificates");
+ String contentType = response.headers().get("Content-Type");
+ if (contentType == null) {
+ // ensuring a default content type
+ contentType = "application/json";
}
- KeyStore caKeyStore = newEmptyKeyStore(password);
- int index = 0;
- for (Certificate certificate : certificates) {
- String certificateAlias = "ca" + Integer.toString(index++);
- caKeyStore.setCertificateEntry(certificateAlias, certificate);
+ if (isJsonMime(contentType)) {
+ return json.deserialize(respBody, returnType);
+ } else if (returnType.equals(String.class)) {
+ // Expecting string, return the raw response body.
+ return (T) respBody;
+ } else {
+ throw new ApiException(
+ "Content type \"" + contentType + "\" is not supported for type: " + returnType,
+ response.code(),
+ response.headers().toMultimap(),
+ respBody);
}
- TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
- trustManagerFactory.init(caKeyStore);
- trustManagers = trustManagerFactory.getTrustManagers();
- }
-
- if (keyManagers != null || trustManagers != null) {
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagers, trustManagers, new SecureRandom());
- httpClient.setSslSocketFactory(sslContext.getSocketFactory());
- } else {
- httpClient.setSslSocketFactory(null);
- }
- httpClient.setHostnameVerifier(hostnameVerifier);
- } catch (GeneralSecurityException e) {
- throw new RuntimeException(e);
}
- }
- private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
- try {
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- keyStore.load(null, password);
- return keyStore;
- } catch (IOException e) {
- throw new AssertionError(e);
+ /**
+ * Serialize the given Java object into request body according to the object's
+ * class and the request Content-Type.
+ *
+ * @param obj The Java object
+ * @param contentType The request Content-Type
+ * @return The serialized request body
+ * @throws ApiException If fail to serialize the given object
+ */
+ public RequestBody serialize(Object obj, String contentType) throws ApiException {
+ if (obj instanceof byte[]) {
+ // Binary (byte array) body parameter support.
+ return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
+ } else if (obj instanceof File) {
+ // File body parameter support.
+ return RequestBody.create(MediaType.parse(contentType), (File) obj);
+ } else if (isJsonMime(contentType)) {
+ String content;
+ if (obj != null) {
+ content = json.serialize(obj);
+ } else {
+ content = null;
+ }
+ return RequestBody.create(MediaType.parse(contentType), content);
+ } else {
+ throw new ApiException("Content type \"" + contentType + "\" is not supported");
+ }
+ }
+
+ /**
+ * Download file from the given response.
+ *
+ * @param response An instance of the Response object
+ * @throws ApiException If fail to read file content from response and write to disk
+ * @return Downloaded file
+ */
+ public File downloadFileFromResponse(Response response) throws ApiException {
+ try {
+ File file = prepareDownloadFile(response);
+ BufferedSink sink = Okio.buffer(Okio.sink(file));
+ sink.writeAll(response.body().source());
+ sink.close();
+ return file;
+ } catch (IOException e) {
+ throw new ApiException(e);
+ }
+ }
+
+ /**
+ * Prepare file for download
+ *
+ * @param response An instance of the Response object
+ * @throws IOException If fail to prepare file for download
+ * @return Prepared file for the download
+ */
+ public File prepareDownloadFile(Response response) throws IOException {
+ String filename = null;
+ String contentDisposition = response.header("Content-Disposition");
+ if (contentDisposition != null && !"".equals(contentDisposition)) {
+ // Get filename from the Content-Disposition header.
+ Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?");
+ Matcher matcher = pattern.matcher(contentDisposition);
+ if (matcher.find()) {
+ filename = sanitizeFilename(matcher.group(1));
+ }
+ }
+
+ String prefix = null;
+ String suffix = null;
+ if (filename == null) {
+ prefix = "download-";
+ suffix = "";
+ } else {
+ int pos = filename.lastIndexOf(".");
+ if (pos == -1) {
+ prefix = filename + "-";
+ } else {
+ prefix = filename.substring(0, pos) + "-";
+ suffix = filename.substring(pos);
+ }
+ // File.createTempFile requires the prefix to be at least three characters long
+ if (prefix.length() < 3)
+ prefix = "download-";
+ }
+
+ if (tempFolderPath == null)
+ return File.createTempFile(prefix, suffix);
+ else
+ return File.createTempFile(prefix, suffix, new File(tempFolderPath));
+ }
+
+ /**
+ * {@link #execute(Call, Type)}
+ *
+ * @param Type
+ * @param call An instance of the Call object
+ * @throws ApiException If fail to execute the call
+ * @return ApiResponse<T>
+ */
+ public ApiResponse execute(Call call) throws ApiException {
+ return execute(call, null);
+ }
+
+ /**
+ * Execute HTTP call and deserialize the HTTP response body into the given return type.
+ *
+ * @param returnType The return type used to deserialize HTTP response body
+ * @param The return type corresponding to (same with) returnType
+ * @param call Call
+ * @return ApiResponse object containing response status, headers and
+ * data, which is a Java object deserialized from response body and would be null
+ * when returnType is null.
+ * @throws ApiException If fail to execute the call
+ */
+ public ApiResponse execute(Call call, Type returnType) throws ApiException {
+ try {
+ Response response = call.execute();
+ T data = handleResponse(response, returnType);
+ return new ApiResponse(response.code(), response.headers().toMultimap(), data);
+ } catch (IOException e) {
+ throw new ApiException(e);
+ }
+ }
+
+ /**
+ * {@link #executeAsync(Call, Type, ApiCallback)}
+ *
+ * @param Type
+ * @param call An instance of the Call object
+ * @param callback ApiCallback<T>
+ */
+ public void executeAsync(Call call, ApiCallback callback) {
+ executeAsync(call, null, callback);
+ }
+
+ /**
+ * Execute HTTP call asynchronously.
+ *
+ * @see #execute(Call, Type)
+ * @param Type
+ * @param call The callback to be executed when the API call finishes
+ * @param returnType Return type
+ * @param callback ApiCallback
+ */
+ public void executeAsync(Call call, final Type returnType, final ApiCallback callback) {
+ call.enqueue(new Callback() {
+ @Override
+ public void onFailure(Request request, IOException e) {
+ callback.onFailure(new ApiException(e), 0, null);
+ }
+
+ @Override
+ public void onResponse(Response response) throws IOException {
+ T result;
+ try {
+ result = (T) handleResponse(response, returnType);
+ } catch (ApiException e) {
+ callback.onFailure(e, response.code(), response.headers().toMultimap());
+ return;
+ }
+ callback.onSuccess(result, response.code(), response.headers().toMultimap());
+ }
+ });
+ }
+
+ /**
+ * Handle the given response, return the deserialized object when the response is successful.
+ *
+ * @param Type
+ * @param response Response
+ * @param returnType Return type
+ * @throws ApiException If the response has a unsuccessful status code or
+ * fail to deserialize the response body
+ * @return Type
+ */
+ public T handleResponse(Response response, Type returnType) throws ApiException {
+ if (response.isSuccessful()) {
+ if (returnType == null || response.code() == 204) {
+ // returning null if the returnType is not defined,
+ // or the status code is 204 (No Content)
+ return null;
+ } else {
+ return deserialize(response, returnType);
+ }
+ } else {
+ String respBody = null;
+ if (response.body() != null) {
+ try {
+ respBody = response.body().string();
+ } catch (IOException e) {
+ throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
+ }
+ }
+ throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
+ }
+ }
+
+ /**
+ * Build HTTP call with the given options.
+ *
+ * @param path The sub-path of the HTTP URL
+ * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
+ * @param queryParams The query parameters
+ * @param body The request body object
+ * @param headerParams The header parameters
+ * @param formParams The form parameters
+ * @param authNames The authentications to apply
+ * @param progressRequestListener Progress request listener
+ * @return The HTTP call
+ * @throws ApiException If fail to serialize the request body object
+ */
+ public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+ updateParamsForAuth(authNames, queryParams, headerParams);
+
+ final String url = buildUrl(path, queryParams);
+ final Request.Builder reqBuilder = new Request.Builder().url(url);
+ processHeaderParams(headerParams, reqBuilder);
+
+ String contentType = (String) headerParams.get("Content-Type");
+ // ensuring a default content type
+ if (contentType == null) {
+ contentType = "application/json";
+ }
+
+ RequestBody reqBody;
+ if (!HttpMethod.permitsRequestBody(method)) {
+ reqBody = null;
+ } else if ("application/x-www-form-urlencoded".equals(contentType)) {
+ reqBody = buildRequestBodyFormEncoding(formParams);
+ } else if ("multipart/form-data".equals(contentType)) {
+ reqBody = buildRequestBodyMultipart(formParams);
+ } else if (body == null) {
+ if ("DELETE".equals(method)) {
+ // allow calling DELETE without sending a request body
+ reqBody = null;
+ } else {
+ // use an empty request body (for POST, PUT and PATCH)
+ reqBody = RequestBody.create(MediaType.parse(contentType), "");
+ }
+ } else {
+ reqBody = serialize(body, contentType);
+ }
+
+ Request request = null;
+
+ if(progressRequestListener != null && reqBody != null) {
+ ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener);
+ request = reqBuilder.method(method, progressRequestBody).build();
+ } else {
+ request = reqBuilder.method(method, reqBody).build();
+ }
+
+ return httpClient.newCall(request);
+ }
+
+ /**
+ * Build full URL by concatenating base path, the given sub path and query parameters.
+ *
+ * @param path The sub path
+ * @param queryParams The query parameters
+ * @return The full URL
+ */
+ public String buildUrl(String path, List queryParams) {
+ final StringBuilder url = new StringBuilder();
+ url.append(basePath).append(path);
+
+ if (queryParams != null && !queryParams.isEmpty()) {
+ // support (constant) query string in `path`, e.g. "/posts?draft=1"
+ String prefix = path.contains("?") ? "&" : "?";
+ for (Pair param : queryParams) {
+ if (param.getValue() != null) {
+ if (prefix != null) {
+ url.append(prefix);
+ prefix = null;
+ } else {
+ url.append("&");
+ }
+ String value = parameterToString(param.getValue());
+ url.append(escapeString(param.getName())).append("=").append(escapeString(value));
+ }
+ }
+ }
+
+ return url.toString();
+ }
+
+ /**
+ * Set header parameters to the request builder, including default headers.
+ *
+ * @param headerParams Header parameters in the ofrm of Map
+ * @param reqBuilder Reqeust.Builder
+ */
+ public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) {
+ for (Entry param : headerParams.entrySet()) {
+ reqBuilder.header(param.getKey(), parameterToString(param.getValue()));
+ }
+ for (Entry header : defaultHeaderMap.entrySet()) {
+ if (!headerParams.containsKey(header.getKey())) {
+ reqBuilder.header(header.getKey(), parameterToString(header.getValue()));
+ }
+ }
+ }
+
+ /**
+ * Update query and header parameters based on authentication settings.
+ *
+ * @param authNames The authentications to apply
+ * @param queryParams List of query parameters
+ * @param headerParams Map of header parameters
+ */
+ public 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);
+ }
+ }
+
+ /**
+ * Build a form-encoding request body with the given form parameters.
+ *
+ * @param formParams Form parameters in the form of Map
+ * @return RequestBody
+ */
+ public RequestBody buildRequestBodyFormEncoding(Map formParams) {
+ FormEncodingBuilder formBuilder = new FormEncodingBuilder();
+ for (Entry param : formParams.entrySet()) {
+ formBuilder.add(param.getKey(), parameterToString(param.getValue()));
+ }
+ return formBuilder.build();
+ }
+
+ /**
+ * Build a multipart (file uploading) request body with the given form parameters,
+ * which could contain text fields and file fields.
+ *
+ * @param formParams Form parameters in the form of Map
+ * @return RequestBody
+ */
+ public RequestBody buildRequestBodyMultipart(Map formParams) {
+ MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
+ for (Entry param : formParams.entrySet()) {
+ if (param.getValue() instanceof File) {
+ File file = (File) param.getValue();
+ Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\"");
+ MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
+ mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file));
+ } else {
+ Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"");
+ mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue())));
+ }
+ }
+ return mpBuilder.build();
+ }
+
+ /**
+ * Guess Content-Type header from the given file (defaults to "application/octet-stream").
+ *
+ * @param file The given file
+ * @return The guessed Content-Type
+ */
+ public String guessContentTypeFromFile(File file) {
+ String contentType = URLConnection.guessContentTypeFromName(file.getName());
+ if (contentType == null) {
+ return "application/octet-stream";
+ } else {
+ return contentType;
+ }
+ }
+
+ /**
+ * Initialize datetime format according to the current environment, e.g. Java 1.7 and Android.
+ */
+ private void initDatetimeFormat() {
+ String formatWithTimeZone = null;
+ if (IS_ANDROID) {
+ if (ANDROID_SDK_VERSION >= 18) {
+ // The time zone format "ZZZZZ" is available since Android 4.3 (SDK version 18)
+ formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ";
+ }
+ } else if (JAVA_VERSION >= 1.7) {
+ // The time zone format "XXX" is available since Java 1.7
+ formatWithTimeZone = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
+ }
+ if (formatWithTimeZone != null) {
+ this.datetimeFormat = new SimpleDateFormat(formatWithTimeZone);
+ // NOTE: Use the system's default time zone (mainly for datetime formatting).
+ } else {
+ // Use a common format that works across all systems.
+ this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+ // Always use the UTC time zone as we are using a constant trailing "Z" here.
+ this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+ }
+ }
+
+ /**
+ * Apply SSL related settings to httpClient according to the current values of
+ * verifyingSsl and sslCaCert.
+ */
+ private void applySslSettings() {
+ try {
+ KeyManager[] keyManagers = null;
+ TrustManager[] trustManagers = null;
+ HostnameVerifier hostnameVerifier = null;
+ if (!verifyingSsl) {
+ TrustManager trustAll = new X509TrustManager() {
+ @Override
+ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
+ @Override
+ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
+ @Override
+ public X509Certificate[] getAcceptedIssuers() { return null; }
+ };
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ trustManagers = new TrustManager[]{ trustAll };
+ hostnameVerifier = new HostnameVerifier() {
+ @Override
+ public boolean verify(String hostname, SSLSession session) { return true; }
+ };
+ } else if (sslCaCert != null) {
+ char[] password = null; // Any password will work.
+ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
+ Collection extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
+ if (certificates.isEmpty()) {
+ throw new IllegalArgumentException("expected non-empty set of trusted certificates");
+ }
+ KeyStore caKeyStore = newEmptyKeyStore(password);
+ int index = 0;
+ for (Certificate certificate : certificates) {
+ String certificateAlias = "ca" + Integer.toString(index++);
+ caKeyStore.setCertificateEntry(certificateAlias, certificate);
+ }
+ TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ trustManagerFactory.init(caKeyStore);
+ trustManagers = trustManagerFactory.getTrustManagers();
+ }
+
+ if (keyManagers != null || trustManagers != null) {
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(keyManagers, trustManagers, new SecureRandom());
+ httpClient.setSslSocketFactory(sslContext.getSocketFactory());
+ } else {
+ httpClient.setSslSocketFactory(null);
+ }
+ httpClient.setHostnameVerifier(hostnameVerifier);
+ } catch (GeneralSecurityException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
+ try {
+ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ keyStore.load(null, password);
+ return keyStore;
+ } catch (IOException e) {
+ throw new AssertionError(e);
+ }
}
- }
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache
index 452f4e1e982..82c86b3e215 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiResponse.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}};
import java.util.List;
@@ -9,38 +11,38 @@ import java.util.Map;
* @param T The type of data that is deserialized from response body
*/
public class ApiResponse {
- final private int statusCode;
- final private Map> headers;
- final private T data;
+ final private int statusCode;
+ final private Map> headers;
+ final private T data;
- /**
- * @param statusCode The status code of HTTP response
- * @param headers The headers of HTTP response
- */
- public ApiResponse(int statusCode, Map> headers) {
- this(statusCode, headers, null);
- }
+ /**
+ * @param statusCode The status code of HTTP response
+ * @param headers The headers of HTTP response
+ */
+ public ApiResponse(int statusCode, Map> headers) {
+ this(statusCode, headers, null);
+ }
- /**
- * @param statusCode The status code of HTTP response
- * @param headers The headers of HTTP response
- * @param data The object deserialized from response bod
- */
- public ApiResponse(int statusCode, Map> headers, T data) {
- this.statusCode = statusCode;
- this.headers = headers;
- this.data = data;
- }
+ /**
+ * @param statusCode The status code of HTTP response
+ * @param headers The headers of HTTP response
+ * @param data The object deserialized from response bod
+ */
+ public ApiResponse(int statusCode, Map> headers, T data) {
+ this.statusCode = statusCode;
+ this.headers = headers;
+ this.data = data;
+ }
- public int getStatusCode() {
- return statusCode;
- }
+ public int getStatusCode() {
+ return statusCode;
+ }
- public Map> getHeaders() {
- return headers;
- }
+ public Map> getHeaders() {
+ return headers;
+ }
- public T getData() {
- return data;
- }
+ public T getData() {
+ return data;
+ }
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache
index 9cc1324acb6..b1be00ea985 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}};
import com.google.gson.Gson;
@@ -10,76 +12,118 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
+import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.Date;
+import org.joda.time.DateTime;
+import org.joda.time.LocalDate;
+import org.joda.time.format.DateTimeFormatter;
+import org.joda.time.format.ISODateTimeFormat;
+
public class JSON {
- private ApiClient apiClient;
- private Gson gson;
+ private ApiClient apiClient;
+ private Gson gson;
- public JSON(ApiClient apiClient) {
- this.apiClient = apiClient;
- gson = new GsonBuilder()
- .registerTypeAdapter(Date.class, new DateAdapter(apiClient))
- .create();
- }
-
- public Gson getGson() {
- return gson;
- }
-
- public void setGson(Gson gson) {
- this.gson = gson;
- }
-
- /**
- * Serialize the given Java object into JSON string.
- */
- public String serialize(Object obj) {
- return gson.toJson(obj);
- }
-
- /**
- * 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, Type returnType) {
- try {
- if (apiClient.isLenientOnJson()) {
- JsonReader jsonReader = new JsonReader(new StringReader(body));
- // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
- jsonReader.setLenient(true);
- return gson.fromJson(jsonReader, returnType);
- } else {
- return gson.fromJson(body, returnType);
- }
- } catch (JsonParseException e) {
- // Fallback processing when failed to parse JSON form response body:
- // return the response body string directly for the String return type;
- // parse response body into date or datetime for the Date return type.
- if (returnType.equals(String.class))
- return (T) body;
- else if (returnType.equals(Date.class))
- return (T) apiClient.parseDateOrDatetime(body);
- else throw(e);
+ /**
+ * JSON constructor.
+ *
+ * @param apiClient An instance of ApiClient
+ */
+ public JSON(ApiClient apiClient) {
+ this.apiClient = apiClient;
+ gson = new GsonBuilder()
+ .registerTypeAdapter(Date.class, new DateAdapter(apiClient))
+ .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
+ .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
+ .create();
+ }
+
+ /**
+ * Get Gson.
+ *
+ * @return Gson
+ */
+ public Gson getGson() {
+ return gson;
+ }
+
+ /**
+ * Set Gson.
+ *
+ * @param gson Gson
+ */
+ public void setGson(Gson gson) {
+ this.gson = gson;
+ }
+
+ /**
+ * Serialize the given Java object into JSON string.
+ *
+ * @param obj Object
+ * @return String representation of the JSON
+ */
+ public String serialize(Object obj) {
+ return gson.toJson(obj);
+ }
+
+ /**
+ * Deserialize the given JSON string to Java object.
+ *
+ * @param Type
+ * @param body The JSON string
+ * @param returnType The type to deserialize inot
+ * @return The deserialized Java object
+ */
+ public T deserialize(String body, Type returnType) {
+ try {
+ if (apiClient.isLenientOnJson()) {
+ JsonReader jsonReader = new JsonReader(new StringReader(body));
+ // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
+ jsonReader.setLenient(true);
+ return gson.fromJson(jsonReader, returnType);
+ } else {
+ return gson.fromJson(body, returnType);
+ }
+ } catch (JsonParseException e) {
+ // Fallback processing when failed to parse JSON form response body:
+ // return the response body string directly for the String return type;
+ // parse response body into date or datetime for the Date return type.
+ if (returnType.equals(String.class))
+ return (T) body;
+ else if (returnType.equals(Date.class))
+ return (T) apiClient.parseDateOrDatetime(body);
+ else throw(e);
+ }
}
- }
}
class DateAdapter implements JsonSerializer, JsonDeserializer {
private final ApiClient apiClient;
+ /**
+ * Constructor for DateAdapter
+ *
+ * @param apiClient Api client
+ */
public DateAdapter(ApiClient apiClient) {
super();
this.apiClient = apiClient;
}
+ /**
+ * Serialize
+ *
+ * @param src Date
+ * @param typeOfSrc Type
+ * @param context Json Serialization Context
+ * @return Json Element
+ */
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
if (src == null) {
@@ -89,6 +133,16 @@ class DateAdapter implements JsonSerializer, JsonDeserializer {
}
}
+ /**
+ * Deserialize
+ *
+ * @param json Json element
+ * @param date Type
+ * @param typeOfSrc Type
+ * @param context Json Serialization Context
+ * @return Date
+ * @throw JsonParseException if fail to parse
+ */
@Override
public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException {
String str = json.getAsJsonPrimitive().getAsString();
@@ -99,3 +153,62 @@ class DateAdapter implements JsonSerializer, JsonDeserializer {
}
}
}
+
+/**
+ * Gson TypeAdapter for Joda DateTime type
+ */
+class DateTimeTypeAdapter extends TypeAdapter {
+
+ private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
+
+ @Override
+ public void write(JsonWriter out, DateTime date) throws IOException {
+ if (date == null) {
+ out.nullValue();
+ } else {
+ out.value(formatter.print(date));
+ }
+ }
+
+ @Override
+ public DateTime read(JsonReader in) throws IOException {
+ switch (in.peek()) {
+ case NULL:
+ in.nextNull();
+ return null;
+ default:
+ String date = in.nextString();
+ return formatter.parseDateTime(date);
+ }
+ }
+}
+
+/**
+ * Gson TypeAdapter for Joda LocalDate type
+ */
+class LocalDateTypeAdapter extends TypeAdapter {
+
+ private final DateTimeFormatter formatter = ISODateTimeFormat.date();
+
+ @Override
+ public void write(JsonWriter out, LocalDate date) throws IOException {
+ if (date == null) {
+ out.nullValue();
+ } else {
+ out.value(formatter.print(date));
+ }
+ }
+
+ @Override
+ public LocalDate read(JsonReader in) throws IOException {
+ switch (in.peek()) {
+ case NULL:
+ in.nextNull();
+ return null;
+ default:
+ String date = in.nextString();
+ return formatter.parseLocalDate(date);
+ }
+ }
+}
+
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache
index 57931ef4cfc..d6570bd0d3b 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressRequestBody.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}};
import com.squareup.okhttp.MediaType;
@@ -18,9 +20,9 @@ public class ProgressRequestBody extends RequestBody {
}
private final RequestBody requestBody;
-
+
private final ProgressRequestListener progressListener;
-
+
private BufferedSink bufferedSink;
public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) {
@@ -43,7 +45,7 @@ public class ProgressRequestBody extends RequestBody {
if (bufferedSink == null) {
bufferedSink = Okio.buffer(sink(sink));
}
-
+
requestBody.writeTo(bufferedSink);
bufferedSink.flush();
@@ -51,7 +53,7 @@ public class ProgressRequestBody extends RequestBody {
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
-
+
long bytesWritten = 0L;
long contentLength = 0L;
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache
index 061a95ac299..3f53133697c 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ProgressResponseBody.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}};
import com.squareup.okhttp.MediaType;
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache
index 6c46a9aed9a..7abe897d42e 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{package}};
import {{invokerPackage}}.ApiCallback;
@@ -11,10 +13,6 @@ import {{invokerPackage}}.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
-import com.squareup.okhttp.Call;
-import com.squareup.okhttp.Interceptor;
-import com.squareup.okhttp.Response;
-
import java.io.IOException;
{{#imports}}import {{import}};
@@ -30,138 +28,138 @@ import java.util.Map;
{{#operations}}
public class {{classname}} {
- private ApiClient {{localVariablePrefix}}apiClient;
+ private ApiClient {{localVariablePrefix}}apiClient;
- public {{classname}}() {
- this(Configuration.getDefaultApiClient());
- }
-
- public {{classname}}(ApiClient apiClient) {
- this.{{localVariablePrefix}}apiClient = apiClient;
- }
-
- public ApiClient getApiClient() {
- return {{localVariablePrefix}}apiClient;
- }
-
- public void setApiClient(ApiClient apiClient) {
- this.{{localVariablePrefix}}apiClient = apiClient;
- }
-
- {{#operation}}
- /* Build call for {{operationId}} */
- private Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
- Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
- {{#allParams}}{{#required}}
- // verify the required parameter '{{paramName}}' is set
- if ({{paramName}} == null) {
- throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)");
- }
- {{/required}}{{/allParams}}
-
- // create path and map variables
- String {{localVariablePrefix}}localVarPath = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}
- .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
-
- {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}}
- if ({{paramName}} != null)
- {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}}
-
- {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}}
- if ({{paramName}} != null)
- {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}}
-
- {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}}
- if ({{paramName}} != null)
- {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}}
-
- final String[] {{localVariablePrefix}}localVarAccepts = {
- {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
- };
- final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts);
- if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept);
-
- final String[] {{localVariablePrefix}}localVarContentTypes = {
- {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
- };
- final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
- {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType);
-
- if(progressListener != null) {
- apiClient.getHttpClient().networkInterceptors().add(new Interceptor() {
- @Override
- public Response intercept(Interceptor.Chain chain) throws IOException {
- Response originalResponse = chain.proceed(chain.request());
- return originalResponse.newBuilder()
- .body(new ProgressResponseBody(originalResponse.body(), progressListener))
- .build();
- }
- });
+ public {{classname}}() {
+ this(Configuration.getDefaultApiClient());
}
- String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
- return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener);
- }
-
- /**
- * {{summary}}
- * {{notes}}{{#allParams}}
- * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
- * @return {{{returnType}}}{{/returnType}}
- * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
- */
- public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
- {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
- return {{localVariablePrefix}}resp.getData();{{/returnType}}
- }
-
- /**
- * {{summary}}
- * {{notes}}{{#allParams}}
- * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
- * @return ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
- * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
- */
- public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
- Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null);
- {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
- return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}}
- }
-
- /**
- * {{summary}} (asynchronously)
- * {{notes}}{{#allParams}}
- * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
- * @param callback The callback to be executed when the API call finishes
- * @return The request call
- * @throws ApiException If fail to process the API call, e.g. serializing the request body object
- */
- public Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException {
-
- ProgressResponseBody.ProgressListener progressListener = null;
- ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
-
- if (callback != null) {
- progressListener = new ProgressResponseBody.ProgressListener() {
- @Override
- public void update(long bytesRead, long contentLength, boolean done) {
- callback.onDownloadProgress(bytesRead, contentLength, done);
- }
- };
-
- progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
- @Override
- public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
- callback.onUploadProgress(bytesWritten, contentLength, done);
- }
- };
+ public {{classname}}(ApiClient apiClient) {
+ this.{{localVariablePrefix}}apiClient = apiClient;
}
- Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
- {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
- {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}}
- return {{localVariablePrefix}}call;
- }
- {{/operation}}
+ public ApiClient getApiClient() {
+ return {{localVariablePrefix}}apiClient;
+ }
+
+ public void setApiClient(ApiClient apiClient) {
+ this.{{localVariablePrefix}}apiClient = apiClient;
+ }
+
+ {{#operation}}
+ /* Build call for {{operationId}} */
+ private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
+ Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
+ {{#allParams}}{{#required}}
+ // verify the required parameter '{{paramName}}' is set
+ if ({{paramName}} == null) {
+ throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)");
+ }
+ {{/required}}{{/allParams}}
+
+ // create path and map variables
+ String {{localVariablePrefix}}localVarPath = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}
+ .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
+
+ {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}}
+ if ({{paramName}} != null)
+ {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}}
+
+ {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}}
+ if ({{paramName}} != null)
+ {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}}
+
+ {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}}
+ if ({{paramName}} != null)
+ {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}}
+
+ final String[] {{localVariablePrefix}}localVarAccepts = {
+ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
+ };
+ final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts);
+ if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept);
+
+ final String[] {{localVariablePrefix}}localVarContentTypes = {
+ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
+ };
+ final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
+ {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType);
+
+ if(progressListener != null) {
+ apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
+ @Override
+ public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
+ com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
+ return originalResponse.newBuilder()
+ .body(new ProgressResponseBody(originalResponse.body(), progressListener))
+ .build();
+ }
+ });
+ }
+
+ String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
+ return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener);
+ }
+
+ /**
+ * {{summary}}
+ * {{notes}}{{#allParams}}
+ * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}}
+ * @return {{returnType}}{{/returnType}}
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
+ {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
+ return {{localVariablePrefix}}resp.getData();{{/returnType}}
+ }
+
+ /**
+ * {{summary}}
+ * {{notes}}{{#allParams}}
+ * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
+ * @return ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
+ * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
+ */
+ public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
+ com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}null, null);
+ {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
+ return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}}
+ }
+
+ /**
+ * {{summary}} (asynchronously)
+ * {{notes}}{{#allParams}}
+ * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
+ * @param callback The callback to be executed when the API call finishes
+ * @return The request call
+ * @throws ApiException If fail to process the API call, e.g. serializing the request body object
+ */
+ public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException {
+
+ ProgressResponseBody.ProgressListener progressListener = null;
+ ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
+
+ if (callback != null) {
+ progressListener = new ProgressResponseBody.ProgressListener() {
+ @Override
+ public void update(long bytesRead, long contentLength, boolean done) {
+ callback.onDownloadProgress(bytesRead, contentLength, done);
+ }
+ };
+
+ progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
+ @Override
+ public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
+ callback.onUploadProgress(bytesWritten, contentLength, done);
+ }
+ };
+ }
+
+ com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
+ {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
+ {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}}
+ return {{localVariablePrefix}}call;
+ }
+ {{/operation}}
}
{{/operations}}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache
index f3ed85d980b..320903b0319 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
@@ -10,32 +12,32 @@ import java.util.List;
import java.io.UnsupportedEncodingException;
public class HttpBasicAuth implements Authentication {
- private String username;
- private String password;
+ 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) {
- if (username == null && password == null) {
- return;
+ 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) {
+ if (username == null && password == null) {
+ return;
+ }
+ headerParams.put("Authorization", Credentials.basic(
+ username == null ? "" : username,
+ password == null ? "" : password));
}
- headerParams.put("Authorization", Credentials.basic(
- username == null ? "" : username,
- password == null ? "" : password));
- }
}
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 4e7b0d1c395..d05d7746e89 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
@@ -98,5 +98,6 @@ dependencies {
compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.squareup.okhttp:logging-interceptor:2.7.5'
compile 'com.google.code.gson:gson:2.6.2'
+ compile 'joda-time:joda-time:2.9.3'
testCompile 'junit:junit:4.12'
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache
index bee8e03fa0e..1352db97988 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache
@@ -13,6 +13,8 @@ lazy val root = (project in file(".")).
"com.squareup.okhttp" % "okhttp" % "2.7.5",
"com.squareup.okhttp" % "logging-interceptor" % "2.7.5",
"com.google.code.gson" % "gson" % "2.6.2",
- "junit" % "junit" % "4.12.0" % "test"
+ "joda-time" % "joda-time" % "2.9.3" % "compile",
+ "junit" % "junit" % "4.12" % "test",
+ "com.novocode" % "junit-interface" % "0.10" % "test"
)
)
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache
index 4bd6d5638b4..0c262eaa3a3 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache
@@ -1,3 +1,5 @@
+{{>licenseInfo}}
+
package {{package}};
import java.util.Objects;
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache
index f7af4c89f2f..213acb31568 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache
@@ -2,19 +2,19 @@
* {{^description}}Gets or Sets {{name}}{{/description}}{{#description}}{{description}}{{/description}}
*/
public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
- {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}})
- {{{name}}}({{{value}}}){{^-last}},
+ {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}})
+ {{{name}}}({{{value}}}){{^-last}},
- {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
+ {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
- private {{dataType}} value;
+ private {{dataType}} value;
- {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{dataType}} value) {
- this.value = value;
- }
+ {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{dataType}} value) {
+ this.value = value;
+ }
- @Override
- public String toString() {
- return String.valueOf(value);
- }
+ @Override
+ public String toString() {
+ return String.valueOf(value);
+ }
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache
index 30ebf3febb6..bb69f71d24b 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache
@@ -1,20 +1,20 @@
- /**
- * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
- */
- public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
- {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}})
- {{{name}}}({{{value}}}){{^-last}},
+ /**
+ * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}}
+ */
+ public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {
+ {{#allowableValues}}{{#enumVars}}@SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}})
+ {{{name}}}({{{value}}}){{^-last}},
- {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
+ {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
- private {{datatype}} value;
+ private {{datatype}} value;
- {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) {
- this.value = value;
+ {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{datatype}} value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return String.valueOf(value);
+ }
}
-
- @Override
- public String toString() {
- return String.valueOf(value);
- }
- }
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache
index b20499078a2..f2aad04d54b 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache
@@ -3,69 +3,93 @@
*/{{#description}}
@ApiModel(description = "{{{description}}}"){{/description}}
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
- {{#vars}}{{#isEnum}}
+ {{#vars}}
+ {{#isEnum}}
+{{>libraries/common/modelInnerEnum}}
+ {{/isEnum}}
+ {{#items.isEnum}}
+ {{#items}}
+{{>libraries/common/modelInnerEnum}}
+ {{/items}}
+ {{/items.isEnum}}
+ @SerializedName("{{baseName}}")
+ private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};
+ {{/vars}}
-{{>libraries/common/modelInnerEnum}}{{/isEnum}}{{#items.isEnum}}{{#items}}
-
-{{>libraries/common/modelInnerEnum}}{{/items}}{{/items.isEnum}}
- @SerializedName("{{baseName}}")
- private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};
- {{/vars}}
-
- {{#vars}}
- /**{{#description}}
- * {{{description}}}{{/description}}{{#minimum}}
- * minimum: {{minimum}}{{/minimum}}{{#maximum}}
- * maximum: {{maximum}}{{/maximum}}
- **/
- @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
- public {{{datatypeWithEnum}}} {{getter}}() {
- return {{name}};
- }{{^isReadOnly}}
- public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
- this.{{name}} = {{name}};
- }{{/isReadOnly}}
-
- {{/vars}}
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
+ {{#vars}}
+ /**
+ {{#description}}
+ * {{{description}}}
+ {{/description}}
+ {{^description}}
+ * Get {{name}}
+ {{/description}}
+ {{#minimum}}
+ * minimum: {{minimum}}
+ {{/minimum}}
+ {{#maximum}}
+ * maximum: {{maximum}}
+ {{/maximum}}
+ * @return {{name}}
+ **/
+ @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
+ public {{{datatypeWithEnum}}} {{getter}}() {
+ return {{name}};
}
- if (o == null || getClass() != o.getClass()) {
- return false;
- }{{#hasVars}}
- {{classname}} {{classVarName}} = ({{classname}}) o;
- return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} &&
+
+ {{^isReadOnly}}
+ /**
+ * Set {{name}}
+ *
+ * @param {{name}} {{name}}
+ */
+ public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
+ this.{{name}} = {{name}};
+ }
+
+ {{/isReadOnly}}
+ {{/vars}}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }{{#hasVars}}
+ {{classname}} {{classVarName}} = ({{classname}}) o;
+ return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} &&
{{/hasMore}}{{/vars}}{{#parent}} &&
super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}}
- return true;{{/hasVars}}
- }
-
- @Override
- public int hashCode() {
- return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("class {{classname}} {\n");
- {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}}
- {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n");
- {{/vars}}sb.append("}");
- return sb.toString();
- }
-
- /**
- * Convert the given object to string with each line indented by 4 spaces
- * (except the first line).
- */
- private String toIndentedString(Object o) {
- if (o == null) {
- return "null";
+ return true;{{/hasVars}}
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}});
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("class {{classname}} {\n");
+ {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}}
+ {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n");
+ {{/vars}}sb.append("}");
+ return sb.toString();
+ }
+
+ /**
+ * Convert the given object to string with each line indented by 4 spaces
+ * (except the first line).
+ *
+ * @param o Object to be converted to indented string
+ */
+ private String toIndentedString(Object o) {
+ if (o == null) {
+ return "null";
+ }
+ return o.toString().replace("\n", "\n ");
}
- return o.toString().replace("\n", "\n ");
- }
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache
index 7f08e5afb58..b1ec0b62461 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache
@@ -68,6 +68,7 @@
org.codehaus.mojo
build-helper-maven-plugin
+ 1.10
add_sources
@@ -104,28 +105,6 @@
1.7
-
-
- org.codehaus.mojo
- exec-maven-plugin
- 1.2.1
-
-
- gradle-test
- integration-test
-
- exec
-
-
- gradle
-
- check
-
-
-
-
-
-
@@ -149,6 +128,11 @@
gson
${gson-version}
+
+ joda-time
+ joda-time
+ ${jodatime-version}
+
@@ -159,10 +143,12 @@
- 1.5.8
+ 1.5.9
2.7.5
2.6.2
+ 2.9.3
1.0.0
4.12
+ UTF-8
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache
index 183fb5f27ce..c7b86b66b9c 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache
@@ -9,6 +9,10 @@ import java.util.Map;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
+import org.joda.time.DateTime;
+import org.joda.time.LocalDate;
+import org.joda.time.format.DateTimeFormatter;
+import org.joda.time.format.ISODateTimeFormat;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
@@ -22,6 +26,9 @@ import retrofit.mime.TypedOutput;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
@@ -108,6 +115,8 @@ public class ApiClient {
public void createDefaultAdapter() {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
+ .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
+ .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create();
okClient = new OkHttpClient();
@@ -339,3 +348,61 @@ class GsonConverterWrapper implements Converter {
}
}
+
+/**
+ * Gson TypeAdapter for Joda DateTime type
+ */
+class DateTimeTypeAdapter extends TypeAdapter {
+
+ private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
+
+ @Override
+ public void write(JsonWriter out, DateTime date) throws IOException {
+ if (date == null) {
+ out.nullValue();
+ } else {
+ out.value(formatter.print(date));
+ }
+ }
+
+ @Override
+ public DateTime read(JsonReader in) throws IOException {
+ switch (in.peek()) {
+ case NULL:
+ in.nextNull();
+ return null;
+ default:
+ String date = in.nextString();
+ return formatter.parseDateTime(date);
+ }
+ }
+}
+
+/**
+ * Gson TypeAdapter for Joda DateTime type
+ */
+class LocalDateTypeAdapter extends TypeAdapter {
+
+ private final DateTimeFormatter formatter = ISODateTimeFormat.date();
+
+ @Override
+ public void write(JsonWriter out, LocalDate date) throws IOException {
+ if (date == null) {
+ out.nullValue();
+ } else {
+ out.value(formatter.print(date));
+ }
+ }
+
+ @Override
+ public LocalDate read(JsonReader in) throws IOException {
+ switch (in.peek()) {
+ case NULL:
+ in.nextNull();
+ return null;
+ default:
+ String date = in.nextString();
+ return formatter.parseLocalDate(date);
+ }
+ }
+}
\ No newline at end of file
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api_test.mustache
new file mode 100644
index 00000000000..a34cfe0e12b
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api_test.mustache
@@ -0,0 +1,44 @@
+package {{package}};
+
+import {{invokerPackage}}.ApiClient;
+{{#imports}}import {{import}};
+{{/imports}}
+import org.junit.Before;
+import org.junit.Test;
+
+{{^fullJavaUtil}}
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+{{/fullJavaUtil}}
+
+/**
+ * API tests for {{classname}}
+ */
+public class {{classname}}Test {
+
+ private {{classname}} api;
+
+ @Before
+ public void setup() {
+ api = new ApiClient().createService({{classname}}.class);
+ }
+
+ {{#operations}}{{#operation}}
+ /**
+ * {{summary}}
+ *
+ * {{notes}}
+ */
+ @Test
+ public void {{operationId}}Test() {
+ {{#allParams}}
+ {{{dataType}}} {{paramName}} = null;
+ {{/allParams}}
+ // {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
+
+ // TODO: test validations
+ }
+ {{/operation}}{{/operations}}
+}
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 6be9ba586f3..179bda3b8d8 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
@@ -99,6 +99,7 @@ ext {
retrofit_version = "1.9.0"
swagger_annotations_version = "1.5.8"
junit_version = "4.12"
+ jodatime_version = "2.9.3"
}
dependencies {
@@ -106,5 +107,6 @@ dependencies {
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
+ compile "joda-time:joda-time:$jodatime_version"
testCompile "junit:junit:$junit_version"
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.sbt.mustache
new file mode 100644
index 00000000000..56f6cee13ab
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.sbt.mustache
@@ -0,0 +1,20 @@
+lazy val root = (project in file(".")).
+ settings(
+ organization := "{{groupId}}",
+ name := "{{artifactId}}",
+ version := "{{artifactVersion}}",
+ scalaVersion := "2.11.4",
+ scalacOptions ++= Seq("-feature"),
+ javacOptions in compile ++= Seq("-Xlint:deprecation"),
+ publishArtifact in (Compile, packageDoc) := false,
+ resolvers += Resolver.mavenLocal,
+ libraryDependencies ++= Seq(
+ "com.squareup.okhttp" % "okhttp" % "2.7.5" % "compile",
+ "com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile",
+ "io.swagger" % "swagger-annotations" % "1.5.8" % "compile",
+ "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
+ "joda-time" % "joda-time" % "2.9.3" % "compile",
+ "junit" % "junit" % "4.12" % "test",
+ "com.novocode" % "junit-interface" % "0.10" % "test"
+ )
+ )
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache
index 9a917f19caf..c9991c230e5 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache
@@ -127,6 +127,11 @@
okhttp
${okhttp-version}
+
+ joda-time
+ joda-time
+ ${jodatime-version}
+
@@ -140,6 +145,7 @@
1.5.8
1.9.0
2.7.5
+ 2.9.3
1.0.1
1.0.0
4.12
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache
index ad5f02c49e4..a4d62eece24 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache
@@ -9,6 +9,10 @@ import java.util.Map;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
+import org.joda.time.DateTime;
+import org.joda.time.LocalDate;
+import org.joda.time.format.DateTimeFormatter;
+import org.joda.time.format.ISODateTimeFormat;
import retrofit2.Converter;
import retrofit2.Retrofit;
@@ -19,6 +23,9 @@ import retrofit2.converter.scalars.ScalarsConverterFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
+import com.google.gson.TypeAdapter;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonWriter;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
@@ -108,6 +115,8 @@ public class ApiClient {
public void createDefaultAdapter() {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
+ .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
+ .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create();
okClient = new OkHttpClient();
@@ -346,3 +355,58 @@ class GsonCustomConverterFactory extends Converter.Factory
}
}
+
+/**
+ * Gson TypeAdapter for Joda DateTime type
+ */
+class DateTimeTypeAdapter extends TypeAdapter {
+
+ private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
+
+ @Override
+ public void write(JsonWriter out, DateTime date) throws IOException {
+ if (date == null) {
+ out.nullValue();
+ } else {
+ out.value(formatter.print(date));
+ }
+ }
+
+ @Override
+ public DateTime read(JsonReader in) throws IOException {
+ switch (in.peek()) {
+ case NULL:
+ in.nextNull();
+ return null;
+ default:
+ String date = in.nextString();
+ return formatter.parseDateTime(date);
+ }
+ }
+}
+
+class LocalDateTypeAdapter extends TypeAdapter {
+
+ private final DateTimeFormatter formatter = ISODateTimeFormat.date();
+
+ @Override
+ public void write(JsonWriter out, LocalDate date) throws IOException {
+ if (date == null) {
+ out.nullValue();
+ } else {
+ out.value(formatter.print(date));
+ }
+ }
+
+ @Override
+ public LocalDate read(JsonReader in) throws IOException {
+ switch (in.peek()) {
+ case NULL:
+ in.nextNull();
+ return null;
+ default:
+ String date = in.nextString();
+ return formatter.parseLocalDate(date);
+ }
+ }
+}
\ No newline at end of file
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api_test.mustache
new file mode 100644
index 00000000000..a34cfe0e12b
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api_test.mustache
@@ -0,0 +1,44 @@
+package {{package}};
+
+import {{invokerPackage}}.ApiClient;
+{{#imports}}import {{import}};
+{{/imports}}
+import org.junit.Before;
+import org.junit.Test;
+
+{{^fullJavaUtil}}
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+{{/fullJavaUtil}}
+
+/**
+ * API tests for {{classname}}
+ */
+public class {{classname}}Test {
+
+ private {{classname}} api;
+
+ @Before
+ public void setup() {
+ api = new ApiClient().createService({{classname}}.class);
+ }
+
+ {{#operations}}{{#operation}}
+ /**
+ * {{summary}}
+ *
+ * {{notes}}
+ */
+ @Test
+ public void {{operationId}}Test() {
+ {{#allParams}}
+ {{{dataType}}} {{paramName}} = null;
+ {{/allParams}}
+ // {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
+
+ // TODO: test validations
+ }
+ {{/operation}}{{/operations}}
+}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache
index 0997418a210..3b245597f21 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/auth/OAuth.mustache
@@ -1,6 +1,7 @@
package {{invokerPackage}}.auth;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
+import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import java.io.IOException;
import java.util.Map;
@@ -85,42 +86,55 @@ public class OAuth implements Interceptor {
updateAccessToken(null);
}
- // Build the request
- Builder rb = request.newBuilder();
+ if (getAccessToken() != null) {
+ // Build the request
+ Builder rb = request.newBuilder();
- String requestAccessToken = new String(getAccessToken());
- try {
- oAuthRequest = new OAuthBearerClientRequest(request.url().toString())
- .setAccessToken(requestAccessToken)
- .buildHeaderMessage();
- } catch (OAuthSystemException e) {
- throw new IOException(e);
+ String requestAccessToken = new String(getAccessToken());
+ try {
+ oAuthRequest = new OAuthBearerClientRequest(request.url().toString())
+ .setAccessToken(requestAccessToken)
+ .buildHeaderMessage();
+ } catch (OAuthSystemException e) {
+ throw new IOException(e);
+ }
+
+ for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) {
+ rb.addHeader(header.getKey(), header.getValue());
+ }
+ rb.url( oAuthRequest.getLocationUri());
+
+ //Execute the request
+ Response response = chain.proceed(rb.build());
+
+ // 401 most likely indicates that access token has expired.
+ // Time to refresh and resend the request
+ if ( response != null && (response.code() == HTTP_UNAUTHORIZED | response.code() == HTTP_FORBIDDEN) ) {
+ if (updateAccessToken(requestAccessToken)) {
+ return intercept( chain );
+ }
+ }
+ return response;
+ } else {
+ return chain.proceed(chain.request());
}
-
- for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) {
- rb.addHeader(header.getKey(), header.getValue());
- }
- rb.url( oAuthRequest.getLocationUri());
-
- //Execute the request
- Response response = chain.proceed(rb.build());
-
- // 401 most likely indicates that access token has expired.
- // Time to refresh and resend the request
- if ( response.code() == HTTP_UNAUTHORIZED ) {
- updateAccessToken(requestAccessToken);
- return intercept( chain );
- }
- return response;
}
- public synchronized void updateAccessToken(String requestAccessToken) throws IOException {
+ /*
+ * Returns true if the access token has been updated
+ */
+ public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException {
if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
try {
OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage());
- setAccessToken(accessTokenResponse.getAccessToken());
- if (accessTokenListener != null) {
- accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken());
+ if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
+ setAccessToken(accessTokenResponse.getAccessToken());
+ if (accessTokenListener != null) {
+ accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken());
+ }
+ return getAccessToken().equals(requestAccessToken);
+ } else {
+ return false;
}
} catch (OAuthSystemException e) {
throw new IOException(e);
@@ -128,6 +142,7 @@ public class OAuth implements Interceptor {
throw new IOException(e);
}
}
+ return true;
}
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache
index e56e682cfcd..fd2e94b582e 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache
@@ -97,25 +97,20 @@ ext {
oltu_version = "1.0.1"
retrofit_version = "2.0.2"
swagger_annotations_version = "1.5.8"
- junit_version = "4.12"
-{{#useRxJava}}
- rx_java_version = "1.1.3"
-{{/useRxJava}}
-{{^useRxJava}}{{/useRxJava}}
+ junit_version = "4.12"{{#useRxJava}}
+ rx_java_version = "1.1.3"{{/useRxJava}}
+ jodatime_version = "2.9.3"
}
dependencies {
compile "com.squareup.retrofit2:retrofit:$retrofit_version"
compile "com.squareup.retrofit2:converter-scalars:$retrofit_version"
- compile "com.squareup.retrofit2:converter-gson:$retrofit_version"
-{{#useRxJava}}
+ compile "com.squareup.retrofit2:converter-gson:$retrofit_version"{{#useRxJava}}
compile "com.squareup.retrofit2:adapter-rxjava:$retrofit_version"
- compile "io.reactivex:rxjava:$rx_java_version"
-{{/useRxJava}}
-{{^useRxJava}}{{/useRxJava}}
-
+ compile "io.reactivex:rxjava:$rx_java_version"{{/useRxJava}}
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
+ compile "joda-time:joda-time:$jodatime_version"
testCompile "junit:junit:$junit_version"
}
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache
new file mode 100644
index 00000000000..ff564803b44
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache
@@ -0,0 +1,23 @@
+lazy val root = (project in file(".")).
+ settings(
+ organization := "{{groupId}}",
+ name := "{{artifactId}}",
+ version := "{{artifactVersion}}",
+ scalaVersion := "2.11.4",
+ scalacOptions ++= Seq("-feature"),
+ javacOptions in compile ++= Seq("-Xlint:deprecation"),
+ publishArtifact in (Compile, packageDoc) := false,
+ resolvers += Resolver.mavenLocal,
+ libraryDependencies ++= Seq(
+ "com.squareup.retrofit2" % "retrofit" % "2.0.2" % "compile",
+ "com.squareup.retrofit2" % "converter-scalars" % "2.0.2" % "compile",
+ "com.squareup.retrofit2" % "converter-gson" % "2.0.2" % "compile",{{#useRxJava}}
+ "com.squareup.retrofit2" % "adapter-rxjava" % "2.0.2" % "compile",
+ "io.reactivex" % "rxjava" % "1.1.3" % "compile",{{/useRxJava}}
+ "io.swagger" % "swagger-annotations" % "1.5.8" % "compile",
+ "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile",
+ "joda-time" % "joda-time" % "2.9.3" % "compile",
+ "junit" % "junit" % "4.12" % "test",
+ "com.novocode" % "junit-interface" % "0.10" % "test"
+ )
+ )
diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache
index 30f6a71d285..2cc806ebbd3 100644
--- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache
+++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache
@@ -131,6 +131,11 @@
org.apache.oltu.oauth2
org.apache.oltu.oauth2.client
${oltu-version}
+
+
+ joda-time
+ joda-time
+ ${jodatime-version}
{{#useRxJava}}
io.reactivex
@@ -153,9 +158,9 @@
1.5.8
- 2.0.2
- {{#useRxJava}}1.1.3{{/useRxJava}}
- 3.2.0
+ 2.0.2{{#useRxJava}}
+ 1.1.3{{/useRxJava}}
+ 2.9.3
1.0.1
1.0.0
4.12
diff --git a/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache
new file mode 100644
index 00000000000..861d97234cf
--- /dev/null
+++ b/modules/swagger-codegen/src/main/resources/Java/licenseInfo.mustache
@@ -0,0 +1,23 @@
+/**
+ * {{{appName}}}
+ * {{{appDescription}}}
+ *
+ * {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
+ * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
+ *
+ * NOTE: This class is auto generated by the swagger code generator program.
+ * https://github.com/swagger-api/swagger-codegen.git
+ * Do not edit the class manually.
+ *
+ * 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.
+ */
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache
index 5d25496a1b3..7d57616610d 100644
--- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache
+++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache
@@ -18,8 +18,8 @@ public interface {{classname}} {
{{#operation}}
@{{httpMethod}}
{{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}}
- {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
- {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
+ {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
+ {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{/allParams}});
{{/operation}}
}
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiException.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiException.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiException.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiOriginFilter.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiOriginFilter.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiOriginFilter.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiResponseMessage.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiResponseMessage.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/ApiResponseMessage.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/ApiResponseMessage.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/JodaDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/JodaDateTimeProvider.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/JodaDateTimeProvider.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/JodaDateTimeProvider.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/JodaLocalDateProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/JodaLocalDateProvider.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/JodaLocalDateProvider.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/JodaLocalDateProvider.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/LocalDateProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/LocalDateProvider.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/LocalDateProvider.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/LocalDateProvider.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/LocalDateTimeProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/LocalDateTimeProvider.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/LocalDateTimeProvider.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/LocalDateTimeProvider.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/NotFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/NotFoundException.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/NotFoundException.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/NotFoundException.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/README.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/README.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/README.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/README.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/StringUtil.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/StringUtil.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/StringUtil.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/allowableValues.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/allowableValues.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/allowableValues.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/allowableValues.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache
similarity index 83%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/api.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache
index 16f46ce0534..15442ad4748 100644
--- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/api.mustache
+++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache
@@ -25,8 +25,8 @@ import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.*;
@Path("/{{baseName}}")
-{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
-{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
+{{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
+{{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
@io.swagger.annotations.Api(description = "the {{baseName}} API")
{{>generatedAnnotation}}
{{#operations}}
@@ -36,8 +36,8 @@ public class {{classname}} {
{{#operation}}
@{{httpMethod}}
{{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}}
- {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
- {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
+ {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}}
+ {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}}
@io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = {
{{#authMethods}}@io.swagger.annotations.Authorization(value = "{{name}}"{{#isOAuth}}, scopes = {
{{#scopes}}@io.swagger.annotations.AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}},
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiService.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiServiceFactory.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceFactory.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiServiceFactory.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceFactory.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/apiServiceImpl.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/bodyParams.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/bodyParams.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/bodyParams.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/bootstrap.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/bootstrap.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/bootstrap.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/bootstrap.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/enumClass.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/enumClass.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/enumClass.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/enumOuterClass.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/enumOuterClass.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/enumOuterClass.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/formParams.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/formParams.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/generatedAnnotation.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/generatedAnnotation.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/generatedAnnotation.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/headerParams.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/headerParams.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/headerParams.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/jacksonJsonProvider.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/jacksonJsonProvider.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/jacksonJsonProvider.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/jacksonJsonProvider.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/model.mustache
similarity index 76%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/model.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/model.mustache
index b9512d2b83c..738fe1c1440 100644
--- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey2/model.mustache
+++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/model.mustache
@@ -1,6 +1,8 @@
package {{package}};
import java.util.Objects;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonValue;
{{#imports}}import {{import}};
{{/imports}}
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pathParams.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pathParams.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pathParams.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pojo.mustache
similarity index 100%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pojo.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pojo.mustache
diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache
similarity index 95%
rename from modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pom.mustache
rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache
index 180450ce73f..96e657cac2b 100644
--- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/jersey1_18/pom.mustache
+++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache
@@ -168,11 +168,12 @@