Merge remote-tracking branch 'upstream/master' into add-auth-annotations-jaxrs

This commit is contained in:
Nick Bruno 2015-10-18 17:19:44 -04:00
commit b83db8e535
68 changed files with 2799 additions and 429 deletions

View File

@ -67,6 +67,8 @@ public interface CodegenConfig {
CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions); CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions);
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger);
CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions); CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map<String, Model> definitions);
List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes); List<CodegenSecurity> fromSecurity(Map<String, SecuritySchemeDefinition> schemes);

View File

@ -7,7 +7,8 @@ import java.util.List;
public class CodegenParameter { public class CodegenParameter {
public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam, isBinary; isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer,
secondaryParam, isBinary, isCollectionFormatMulti;
public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue; public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue;
public String jsonSchema; public String jsonSchema;
public boolean isEnum; public boolean isEnum;
@ -33,6 +34,7 @@ public class CodegenParameter {
output.paramName = this.paramName; output.paramName = this.paramName;
output.dataType = this.dataType; output.dataType = this.dataType;
output.collectionFormat = this.collectionFormat; output.collectionFormat = this.collectionFormat;
output.isCollectionFormatMulti = this.isCollectionFormatMulti;
output.description = this.description; output.description = this.description;
output.baseType = this.baseType; output.baseType = this.baseType;
output.isFormParam = this.isFormParam; output.isFormParam = this.isFormParam;

View File

@ -867,8 +867,12 @@ public class DefaultCodegen {
} }
return responses.get(code); return responses.get(code);
} }
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions) { public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions) {
return fromOperation(path, httpMethod, operation, definitions, null);
}
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION);
Set<String> imports = new HashSet<String>(); Set<String> imports = new HashSet<String>();
op.vendorExtensions = operation.getVendorExtensions(); op.vendorExtensions = operation.getVendorExtensions();
@ -904,15 +908,32 @@ public class DefaultCodegen {
op.summary = escapeText(operation.getSummary()); op.summary = escapeText(operation.getSummary());
op.notes = escapeText(operation.getDescription()); op.notes = escapeText(operation.getDescription());
op.tags = operation.getTags(); op.tags = operation.getTags();
op.hasConsumes = false;
op.hasProduces = false;
if (operation.getConsumes() != null && operation.getConsumes().size() > 0) { List<String> consumes = new ArrayList<String>();
if (operation.getConsumes() != null) {
if (operation.getConsumes().size() > 0) {
// use consumes defined in the operation
consumes = operation.getConsumes();
} else {
// empty list, do nothing to override global setting
}
} else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) {
// use consumes defined globally
consumes = swagger.getConsumes();
LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId);
}
// if "consumes" is defined (per operation or using global definition)
if (consumes != null && consumes.size() > 0) {
List<Map<String, String>> c = new ArrayList<Map<String, String>>(); List<Map<String, String>> c = new ArrayList<Map<String, String>>();
int count = 0; int count = 0;
for (String key : operation.getConsumes()) { for (String key : consumes) {
Map<String, String> mediaType = new HashMap<String, String>(); Map<String, String> mediaType = new HashMap<String, String>();
mediaType.put("mediaType", key); mediaType.put("mediaType", key);
count += 1; count += 1;
if (count < operation.getConsumes().size()) { if (count < consumes.size()) {
mediaType.put("hasMore", "true"); mediaType.put("hasMore", "true");
} else { } else {
mediaType.put("hasMore", null); mediaType.put("hasMore", null);
@ -923,14 +944,29 @@ public class DefaultCodegen {
op.hasConsumes = true; op.hasConsumes = true;
} }
if (operation.getProduces() != null && operation.getProduces().size() > 0) { List<String> produces = new ArrayList<String>();
if (operation.getProduces() != null) {
if (operation.getProduces().size() > 0) {
// use produces defined in the operation
produces = operation.getProduces();
} else {
// empty list, do nothing to override global setting
}
} else if (swagger != null && swagger.getProduces() != null && swagger.getProduces().size() > 0) {
// use produces defined globally
produces = swagger.getProduces();
LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId);
}
// if "produces" is defined (per operation or using global definition)
if (produces != null && produces.size() > 0) {
List<Map<String, String>> c = new ArrayList<Map<String, String>>(); List<Map<String, String>> c = new ArrayList<Map<String, String>>();
int count = 0; int count = 0;
for (String key : operation.getProduces()) { for (String key : produces) {
Map<String, String> mediaType = new HashMap<String, String>(); Map<String, String> mediaType = new HashMap<String, String>();
mediaType.put("mediaType", key); mediaType.put("mediaType", key);
count += 1; count += 1;
if (count < operation.getProduces().size()) { if (count < produces.size()) {
mediaType.put("hasMore", "true"); mediaType.put("hasMore", "true");
} else { } else {
mediaType.put("hasMore", null); mediaType.put("hasMore", null);
@ -1044,7 +1080,7 @@ public class DefaultCodegen {
} }
} }
for (String i : imports) { for (String i : imports) {
if (!defaultIncludes.contains(i) && !languageSpecificPrimitives.contains(i)) { if (needToImport(i)) {
op.imports.add(i); op.imports.add(i);
} }
} }
@ -1205,6 +1241,9 @@ public class DefaultCodegen {
p._enum = model._enum; p._enum = model._enum;
p.allowableValues = model.allowableValues; p.allowableValues = model.allowableValues;
p.collectionFormat = collectionFormat; p.collectionFormat = collectionFormat;
if(collectionFormat != null && collectionFormat.equals("multi")) {
p.isCollectionFormatMulti = true;
}
p.paramName = toParamName(qp.getName()); p.paramName = toParamName(qp.getName());
if (model.complexType != null) { if (model.complexType != null) {
@ -1333,6 +1372,12 @@ public class DefaultCodegen {
return secs; return secs;
} }
protected boolean needToImport(String type) {
return !defaultIncludes.contains(type)
&& !languageSpecificPrimitives.contains(type)
&& type.indexOf(".") < 0;
}
protected List<Map<String, Object>> toExamples(Map<String, Object> examples) { protected List<Map<String, Object>> toExamples(Map<String, Object> examples) {
if (examples == null) { if (examples == null) {
return null; return null;
@ -1436,7 +1481,7 @@ public class DefaultCodegen {
} }
private void addImport(CodegenModel m, String type) { private void addImport(CodegenModel m, String type) {
if (type != null && !languageSpecificPrimitives.contains(type) && !defaultIncludes.contains(type)) { if (type != null && needToImport(type)) {
m.imports.add(type); m.imports.add(type);
} }
} }
@ -1615,8 +1660,8 @@ public class DefaultCodegen {
* @return sanitized string * @return sanitized string
*/ */
public String sanitizeName(String name) { public String sanitizeName(String name) {
// NOTE: performance wise, we should have written with 2 replaceAll to replace desired // NOTE: performance wise, we should have written with 2 replaceAll to replace desired
// character with _ or empty character. Below aims to spell out different cases we've // character with _ or empty character. Below aims to spell out different cases we've
// encountered so far and hopefully make it easier for others to add more special // encountered so far and hopefully make it easier for others to add more special
// cases in the future. // cases in the future.
@ -1639,7 +1684,7 @@ public class DefaultCodegen {
// input name and age => input_name_and_age // input name and age => input_name_and_age
name = name.replaceAll(" ", "_"); name = name.replaceAll(" ", "_");
// remove everything else other than word, number and _ // remove everything else other than word, number and _
// $php_variable => php_variable // $php_variable => php_variable
return name.replaceAll("[^a-zA-Z0-9_]", ""); return name.replaceAll("[^a-zA-Z0-9_]", "");

View File

@ -12,6 +12,7 @@ import io.swagger.models.License;
import io.swagger.models.Model; import io.swagger.models.Model;
import io.swagger.models.Operation; import io.swagger.models.Operation;
import io.swagger.models.Path; import io.swagger.models.Path;
import io.swagger.models.SecurityRequirement;
import io.swagger.models.Swagger; import io.swagger.models.Swagger;
import io.swagger.models.auth.OAuth2Definition; import io.swagger.models.auth.OAuth2Definition;
import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.models.auth.SecuritySchemeDefinition;
@ -470,22 +471,31 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
for (String tag : tags) { for (String tag : tags) {
CodegenOperation co = null; CodegenOperation co = null;
try { try {
co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions()); co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger);
co.tags = new ArrayList<String>(); co.tags = new ArrayList<String>();
co.tags.add(sanitizeTag(tag)); co.tags.add(sanitizeTag(tag));
config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations);
List<Map<String, List<String>>> securities = operation.getSecurity(); List<Map<String, List<String>>> securities = operation.getSecurity();
if (securities == null) { if (securities == null && swagger.getSecurity() != null) {
securities = new ArrayList<Map<String, List<String>>>();
for (SecurityRequirement sr : swagger.getSecurity()) {
securities.add(sr.getRequirements());
}
}
if (securities == null || securities.isEmpty()) {
continue; continue;
} }
Map<String, SecuritySchemeDefinition> authMethods = new HashMap<String, SecuritySchemeDefinition>(); Map<String, SecuritySchemeDefinition> authMethods = new HashMap<String, SecuritySchemeDefinition>();
for (Map<String, List<String>> security : securities) { // NOTE: Use only the first security requirement for now.
if (security.size() != 1) { // See the "security" field of "Swagger Object":
//Not sure what to do // https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object
continue; // "there is a logical OR between the security requirements"
} if (securities.size() > 1) {
String securityName = security.keySet().iterator().next(); LOGGER.warn("More than 1 security requirements are found, using only the first one");
}
Map<String, List<String>> security = securities.get(0);
for (String securityName : security.keySet()) {
SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); SecuritySchemeDefinition securityDefinition = fromSecurity(securityName);
if (securityDefinition != null) { if (securityDefinition != null) {
if(securityDefinition instanceof OAuth2Definition) { if(securityDefinition instanceof OAuth2Definition) {
@ -496,7 +506,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
oauth2Operation.setFlow(oauth2Definition.getFlow()); oauth2Operation.setFlow(oauth2Definition.getFlow());
oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl()); oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl());
oauth2Operation.setScopes(new HashMap<String, String>()); oauth2Operation.setScopes(new HashMap<String, String>());
for (String scope : security.values().iterator().next()) { for (String scope : security.get(securityName)) {
if (oauth2Definition.getScopes().containsKey(scope)) { if (oauth2Definition.getScopes().containsKey(scope)) {
oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope)); oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope));
} }

View File

@ -104,13 +104,13 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
} }
additionalProperties.put("clientPackage", clientPackage); additionalProperties.put("clientPackage", clientPackage);
supportingFiles.add(new SupportingFile("Configuration.mustache", supportingFiles.add(new SupportingFile("Configuration.mustache",
(sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "Configuration.cs")); sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", supportingFiles.add(new SupportingFile("ApiClient.mustache",
(sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiClient.cs")); sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiClient.cs"));
supportingFiles.add(new SupportingFile("ApiException.mustache", supportingFiles.add(new SupportingFile("ApiException.mustache",
(sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiException.cs")); sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs"));
supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll"));
supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll")); supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll"));
supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat"));
@ -137,12 +137,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
@Override @Override
public String apiFileFolder() { public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar);
return outputFolder + File.separator + (sourceFolder + File.separator + apiPackage()).replace('.', File.separatorChar);
} }
public String modelFileFolder() { public String modelFileFolder() {
return outputFolder + File.separator + (sourceFolder + File.separator + modelPackage()).replace('.', File.separatorChar); return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar);
} }
@Override @Override

View File

@ -108,11 +108,11 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
} }
supportingFiles.add(new SupportingFile("Configuration.mustache", supportingFiles.add(new SupportingFile("Configuration.mustache",
(sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "Configuration.cs")); sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", supportingFiles.add(new SupportingFile("ApiClient.mustache",
(sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiClient.cs")); sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiClient.cs"));
supportingFiles.add(new SupportingFile("ApiException.mustache", supportingFiles.add(new SupportingFile("ApiException.mustache",
(sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiException.cs")); sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs"));
supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", "packages.config")); supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", "packages.config"));
supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh")); supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh"));
supportingFiles.add(new SupportingFile("README.md", "", "README.md")); supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
@ -142,11 +142,11 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege
@Override @Override
public String apiFileFolder() { public String apiFileFolder() {
return (outputFolder + File.separator + sourceFolder + File.separator + apiPackage()).replace('.', File.separatorChar); return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar);
} }
public String modelFileFolder() { public String modelFileFolder() {
return (outputFolder + File.separator + sourceFolder + File.separator + modelPackage()).replace('.', File.separatorChar); return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar);
} }
@Override @Override

View File

@ -12,6 +12,7 @@ import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile; import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model; import io.swagger.models.Model;
import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property; import io.swagger.models.properties.Property;
@ -37,6 +38,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String artifactVersion = "1.0.0"; protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/java"; protected String sourceFolder = "src/main/java";
protected String localVariablePrefix = ""; protected String localVariablePrefix = "";
protected boolean fullJavaUtil = false;
protected String javaUtilPrefix = "";
protected Boolean serializableModel = false; protected Boolean serializableModel = false;
public JavaClientCodegen() { public JavaClientCodegen() {
@ -81,6 +84,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC));
cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC));
cliOptions.add(new CliOption(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); cliOptions.add(new CliOption(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC));
cliOptions.add(new CliOption("fullJavaUtil", "whether to use fully qualified name for classes under java.util (default to false)"));
supportedLibraries.put("<default>", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("<default>", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2");
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6");
@ -107,7 +111,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public void processOpts() { public void processOpts() {
super.processOpts(); super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
} else { } else {
@ -149,16 +153,49 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
this.setSerializableModel(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); this.setSerializableModel(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString()));
} }
if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) {
this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY));
}
// need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string
additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel);
if (additionalProperties.containsKey("fullJavaUtil")) {
fullJavaUtil = Boolean.valueOf(additionalProperties.get("fullJavaUtil").toString());
}
if (fullJavaUtil) {
javaUtilPrefix = "java.util.";
}
additionalProperties.put("fullJavaUtil", fullJavaUtil);
additionalProperties.put("javaUtilPrefix", javaUtilPrefix);
if (fullJavaUtil) {
typeMapping.put("array", "java.util.List");
typeMapping.put("map", "java.util.Map");
typeMapping.put("DateTime", "java.util.Date");
typeMapping.remove("List");
importMapping.remove("Date");
importMapping.remove("Map");
importMapping.remove("HashMap");
importMapping.remove("Array");
importMapping.remove("ArrayList");
importMapping.remove("List");
importMapping.remove("Set");
importMapping.remove("DateTime");
instantiationTypes.put("array", "java.util.ArrayList");
instantiationTypes.put("map", "java.util.HashMap");
}
this.sanitizeConfig(); this.sanitizeConfig();
final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator);
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle"));
supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java"));
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator);
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java"));
@ -172,42 +209,41 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java"));
supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java"));
} }
// library-specific files // library-specific files
if ("okhttp-gson".equals(getLibrary())) { if ("okhttp-gson".equals(getLibrary())) {
// the "okhttp-gson" library template requires "ApiCallback.mustache" for async call // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call
supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java"));
// "build.gradle" is for development with Gradle
supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle"));
// "build.sbt" is for development with SBT // "build.sbt" is for development with SBT
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
} else if ("retrofit".equals(getLibrary())) { } else if ("retrofit".equals(getLibrary())) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java"));
} else { } else {
supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java"));
} }
} }
private void sanitizeConfig() { private void sanitizeConfig() {
// Sanitize any config options here. We also have to update the additionalProperties because // Sanitize any config options here. We also have to update the additionalProperties because
// the whole additionalProperties object is injected into the main object passed to the mustache layer // the whole additionalProperties object is injected into the main object passed to the mustache layer
this.setApiPackage(sanitizePackageName(apiPackage)); this.setApiPackage(sanitizePackageName(apiPackage));
if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) {
this.additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); this.additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage);
} }
this.setModelPackage(sanitizePackageName(modelPackage)); this.setModelPackage(sanitizePackageName(modelPackage));
if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) {
this.additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); this.additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage);
} }
this.setInvokerPackage(sanitizePackageName(invokerPackage)); this.setInvokerPackage(sanitizePackageName(invokerPackage));
if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
} }
} }
@Override @Override
public String escapeReservedWord(String name) { public String escapeReservedWord(String name) {
return "_" + name; return "_" + name;
@ -294,10 +330,28 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
public String toDefaultValue(Property p) { public String toDefaultValue(Property p) {
if (p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
final ArrayProperty ap = (ArrayProperty) p; final ArrayProperty ap = (ArrayProperty) p;
return String.format("new ArrayList<%s>()", getTypeDeclaration(ap.getItems())); final String pattern;
if (fullJavaUtil) {
pattern = "new java.util.ArrayList<%s>()";
} else {
pattern = "new ArrayList<%s>()";
}
return String.format(pattern, getTypeDeclaration(ap.getItems()));
} else if (p instanceof MapProperty) { } else if (p instanceof MapProperty) {
final MapProperty ap = (MapProperty) p; final MapProperty ap = (MapProperty) p;
return String.format("new HashMap<String, %s>()", getTypeDeclaration(ap.getAdditionalProperties())); final String pattern;
if (fullJavaUtil) {
pattern = "new java.util.HashMap<String, %s>()";
} else {
pattern = "new HashMap<String, %s>()";
}
return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties()));
} else if (p instanceof LongProperty) {
LongProperty dp = (LongProperty) p;
if (dp.getDefault() != null) {
return dp.getDefault().toString()+"l";
}
return "null";
} }
return super.toDefaultValue(p); return super.toDefaultValue(p);
} }
@ -308,7 +362,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
String type = null; String type = null;
if (typeMapping.containsKey(swaggerType)) { if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType); type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) { if (languageSpecificPrimitives.contains(type) || type.indexOf(".") >= 0) {
return type; return type;
} }
} else { } else {
@ -394,7 +448,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
return objs; return objs;
} }
public Map<String, Object> postProcessOperations(Map<String, Object> objs) { public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
if("retrofit".equals(getLibrary())) { if("retrofit".equals(getLibrary())) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations"); Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
@ -418,6 +472,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
return objs; return objs;
} }
protected boolean needToImport(String type) {
return super.needToImport(type) && type.indexOf(".") < 0;
}
private String findCommonPrefixOfVars(List<String> vars) { private String findCommonPrefixOfVars(List<String> vars) {
String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()])); String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()]));
// exclude trailing characters that should be part of a valid variable // exclude trailing characters that should be part of a valid variable
@ -426,7 +484,12 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
private String toEnumVarName(String value) { private String toEnumVarName(String value) {
return value.replaceAll("\\W+", "_").toUpperCase(); String var = value.replaceAll("\\W+", "_").toUpperCase();
if (var.matches("\\d.*")) {
return "_" + var;
} else {
return var;
}
} }
private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) {

View File

@ -22,10 +22,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public class JavaInflectorServerCodegen extends JavaClientCodegen implements CodegenConfig { public class JavaInflectorServerCodegen extends JavaClientCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.handler";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-inflector-server";
protected String artifactVersion = "1.0.0";
protected String title = "Swagger Inflector"; protected String title = "Swagger Inflector";
public JavaInflectorServerCodegen() { public JavaInflectorServerCodegen() {
@ -35,6 +31,8 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod
modelTemplateFiles.put("model.mustache", ".java"); modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java");
templateDir = "JavaInflector"; templateDir = "JavaInflector";
invokerPackage = "io.swagger.handler";
artifactId = "swagger-inflector-server";
apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler"); apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler");
modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model");

View File

@ -16,16 +16,14 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig { public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.api";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-jaxrs-server";
protected String artifactVersion = "1.0.0";
protected String title = "Swagger Server"; protected String title = "Swagger Server";
public JaxRSServerCodegen() { public JaxRSServerCodegen() {
super.processOpts(); super.processOpts();
sourceFolder = "src/gen/java"; sourceFolder = "src/gen/java";
invokerPackage = "io.swagger.api";
artifactId = "swagger-jaxrs-server";
outputFolder = System.getProperty("swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS"); outputFolder = System.getProperty("swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS");
modelTemplateFiles.put("model.mustache", ".java"); modelTemplateFiles.put("model.mustache", ".java");

View File

@ -15,13 +15,7 @@ import java.util.Map;
import java.util.Iterator; import java.util.Iterator;
public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig { public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.api";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-spring-mvc-server";
protected String artifactVersion = "1.0.0";
protected String sourceFolder = "src/main/java";
protected String title = "Petstore Server"; protected String title = "Petstore Server";
protected String configPackage = ""; protected String configPackage = "";
public SpringMVCServerCodegen() { public SpringMVCServerCodegen() {
@ -33,7 +27,8 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
apiPackage = "io.swagger.api"; apiPackage = "io.swagger.api";
modelPackage = "io.swagger.model"; modelPackage = "io.swagger.model";
configPackage = "io.swagger.configuration"; configPackage = "io.swagger.configuration";
invokerPackage = "io.swagger.api";
artifactId = "swagger-spring-mvc-server";
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
additionalProperties.put(CodegenConstants.GROUP_ID, groupId); additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
@ -201,4 +196,3 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
return objs; return objs;
} }
} }

View File

@ -1,9 +1,11 @@
package io.swagger.codegen.languages; package io.swagger.codegen.languages;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.Iterators; import com.google.common.collect.Iterators;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import io.swagger.codegen.*; import io.swagger.codegen.*;
import io.swagger.models.Swagger;
import io.swagger.models.Model; import io.swagger.models.Model;
import io.swagger.models.Operation; import io.swagger.models.Operation;
import io.swagger.models.parameters.HeaderParameter; import io.swagger.models.parameters.HeaderParameter;
@ -256,7 +258,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
} }
@Override @Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions) { public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions, Swagger swagger) {
path = normalizePath(path); path = normalizePath(path);
List<Parameter> parameters = operation.getParameters(); List<Parameter> parameters = operation.getParameters();
parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate<Parameter>() { parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate<Parameter>() {
@ -266,7 +268,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
} }
})); }));
operation.setParameters(parameters); operation.setParameters(parameters);
return super.fromOperation(path, httpMethod, operation, definitions); return super.fromOperation(path, httpMethod, operation, definitions, swagger);
} }
private static String normalizePath(String path) { private static String normalizePath(String path) {

View File

@ -6,16 +6,12 @@ import {{invokerPackage}}.Configuration;
import {{invokerPackage}}.Pair; import {{invokerPackage}}.Pair;
import {{invokerPackage}}.TypeRef; import {{invokerPackage}}.TypeRef;
import {{modelPackage}}.*;
import java.util.*;
{{#imports}}import {{import}}; {{#imports}}import {{import}};
{{/imports}} {{/imports}}
import java.io.File; {{^fullJavaUtil}}
import java.util.Map; import java.util.*;
import java.util.HashMap; {{/fullJavaUtil}}
{{>generatedAnnotation}} {{>generatedAnnotation}}
{{#operations}} {{#operations}}
@ -59,9 +55,9 @@ public class {{classname}} {
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params // query params
List<Pair> {{localVariablePrefix}}queryParams = new ArrayList<Pair>(); {{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}queryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
Map<String, String> {{localVariablePrefix}}headerParams = new HashMap<String, String>(); {{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}headerParams = new {{javaUtilPrefix}}HashMap<String, String>();
Map<String, Object> {{localVariablePrefix}}formParams = new HashMap<String, Object>(); {{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}formParams = new {{javaUtilPrefix}}HashMap<String, Object>();
{{#queryParams}} {{#queryParams}}
{{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));

View File

@ -0,0 +1,107 @@
group = '{{groupId}}'
version = '{{artifactVersion}}'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
repositories {
jcenter()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
install {
repositories.mavenInstaller {
pom.artifactId = '{{artifactId}}'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
swagger_annotations_version = "1.5.0"
jackson_version = "2.4.2"
jersey_version = "1.18"
jodatime_version = "2.3"
junit_version = "4.8.1"
}
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.sun.jersey:jersey-client:$jersey_version"
compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
compile "joda-time:joda-time:$jodatime_version"
testCompile "junit:junit:$junit_version"
}

View File

@ -0,0 +1,2 @@
# Uncomment to build for Android
#target = android

View File

@ -6,16 +6,12 @@ import {{invokerPackage}}.Configuration;
import {{invokerPackage}}.Pair; import {{invokerPackage}}.Pair;
import {{invokerPackage}}.TypeRef; import {{invokerPackage}}.TypeRef;
import {{modelPackage}}.*;
import java.util.*;
{{#imports}}import {{import}}; {{#imports}}import {{import}};
{{/imports}} {{/imports}}
import java.io.File; {{^fullJavaUtil}}
import java.util.Map; import java.util.*;
import java.util.HashMap; {{/fullJavaUtil}}
{{>generatedAnnotation}} {{>generatedAnnotation}}
{{#operations}} {{#operations}}
@ -58,9 +54,9 @@ public class {{classname}} {
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params // query params
List<Pair> {{localVariablePrefix}}queryParams = new ArrayList<Pair>(); {{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}queryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
Map<String, String> {{localVariablePrefix}}headerParams = new HashMap<String, String>(); {{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}headerParams = new {{javaUtilPrefix}}HashMap<String, String>();
Map<String, Object> {{localVariablePrefix}}formParams = new HashMap<String, Object>(); {{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}formParams = new {{javaUtilPrefix}}HashMap<String, Object>();
{{#queryParams}} {{#queryParams}}
{{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));

View File

@ -0,0 +1,107 @@
group = '{{groupId}}'
version = '{{artifactVersion}}'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
repositories {
jcenter()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
install {
repositories.mavenInstaller {
pom.artifactId = '{{artifactId}}'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
swagger_annotations_version = "1.5.0"
jackson_version = "2.4.2"
jersey_version = "2.6"
jodatime_version = "2.3"
junit_version = "4.8.1"
}
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.glassfish.jersey.core:jersey-client:$jersey_version"
compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
compile "joda-time:joda-time:$jodatime_version"
testCompile "junit:junit:$junit_version"
}

View File

@ -6,22 +6,17 @@ import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Configuration;
import {{invokerPackage}}.Pair; import {{invokerPackage}}.Pair;
import {{modelPackage}}.*;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Call; import com.squareup.okhttp.Call;
import java.lang.reflect.Type;
import java.util.*;
{{#imports}}import {{import}}; {{#imports}}import {{import}};
{{/imports}} {{/imports}}
import java.io.File; import java.lang.reflect.Type;
import java.util.Map; {{^fullJavaUtil}}
import java.util.HashMap; import java.util.*;
{{/fullJavaUtil}}
{{#operations}} {{#operations}}
public class {{classname}} { public class {{classname}} {
@ -58,15 +53,15 @@ public class {{classname}} {
String {{localVariablePrefix}}path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} String {{localVariablePrefix}}path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
List<Pair> {{localVariablePrefix}}queryParams = new ArrayList<Pair>();{{#queryParams}} {{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}queryParams = new {{javaUtilPrefix}}ArrayList<Pair>();{{#queryParams}}
if ({{paramName}} != null) if ({{paramName}} != null)
{{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}}
Map<String, String> {{localVariablePrefix}}headerParams = new HashMap<String, String>();{{#headerParams}} {{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}headerParams = new {{javaUtilPrefix}}HashMap<String, String>();{{#headerParams}}
if ({{paramName}} != null) if ({{paramName}} != null)
{{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} {{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}}
Map<String, Object> {{localVariablePrefix}}formParams = new HashMap<String, Object>();{{#formParams}} {{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}formParams = new {{javaUtilPrefix}}HashMap<String, Object>();{{#formParams}}
if ({{paramName}} != null) if ({{paramName}} != null)
{{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}});{{/formParams}} {{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}});{{/formParams}}

View File

@ -1,11 +1,89 @@
apply plugin: 'java' group = '{{groupId}}'
apply plugin: 'maven' version = '{{artifactVersion}}'
sourceCompatibility = JavaVersion.VERSION_1_7 buildscript {
targetCompatibility = JavaVersion.VERSION_1_7 repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
repositories { repositories {
mavenCentral() jcenter()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
install {
repositories.mavenInstaller {
pom.artifactId = '{{artifactId}}'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
} }
dependencies { dependencies {
@ -15,17 +93,3 @@ dependencies {
compile 'com.brsanthu:migbase64:2.2' compile 'com.brsanthu:migbase64:2.2'
testCompile 'junit:junit:4.8.1' testCompile 'junit:junit:4.8.1'
} }
group = '{{groupId}}'
version = '{{artifactVersion}}'
install {
repositories.mavenInstaller {
pom.artifactId = '{{artifactId}}'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}

View File

@ -49,16 +49,16 @@ public class ApiClient {
for(String authName : authNames) { for(String authName : authNames) {
if (apiAuthorizations.containsKey(authName)) { if (apiAuthorizations.containsKey(authName)) {
throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations");
} }{{#authMethods}}
Interceptor auth;{{#authMethods}} Interceptor auth;
if (authName == "{{name}}") { {{#isBasic}} if (authName == "{{name}}") { {{#isBasic}}
auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}}
auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}}
auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}} auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}}
} else {{/authMethods}}{ } else {
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
} }
apiAuthorizations.put(authName, auth); apiAuthorizations.put(authName, auth);{{/authMethods}}
} }
addAuthsToOkClient(okClient); addAuthsToOkClient(okClient);
} }

View File

@ -0,0 +1,95 @@
package {{invokerPackage}};
import java.util.Arrays;
import java.util.List;
public class CollectionFormats {
public static class CSVParams {
protected List<String> params;
public CSVParams() {
}
public CSVParams(List<String> params) {
this.params = params;
}
public CSVParams(String... params) {
this.params = Arrays.asList(params);
}
public List<String> getParams() {
return params;
}
public void setParams(List<String> params) {
this.params = params;
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), ",");
}
}
public static class SSVParams extends CSVParams {
public SSVParams() {
}
public SSVParams(List<String> params) {
super(params);
}
public SSVParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), " ");
}
}
public static class TSVParams extends CSVParams {
public TSVParams() {
}
public TSVParams(List<String> params) {
super(params);
}
public TSVParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join( params.toArray(new String[0]), "\t");
}
}
public static class PIPESParams extends CSVParams {
public PIPESParams() {
}
public PIPESParams(List<String> params) {
super(params);
}
public PIPESParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), "|");
}
}
}

View File

@ -1,15 +1,18 @@
package {{package}}; package {{package}};
import {{modelPackage}}.*; import {{invokerPackage}}.CollectionFormats.*;
import retrofit.Callback; import retrofit.Callback;
import retrofit.http.*; import retrofit.http.*;
import retrofit.mime.*; import retrofit.mime.*;
import java.util.*;
{{#imports}}import {{import}}; {{#imports}}import {{import}};
{{/imports}} {{/imports}}
{{^fullJavaUtil}}
import java.util.*;
{{/fullJavaUtil}}
{{#operations}} {{#operations}}
public interface {{classname}} { public interface {{classname}} {
{{#operation}} {{#operation}}
@ -22,7 +25,7 @@ public interface {{classname}} {
*/ */
{{#formParams}}{{#-first}} {{#formParams}}{{#-first}}
{{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}}
@{{httpMethod}}("{{path}}") @{{httpMethod}}("{{path}}")
{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{nickname}}({{^allParams}});{{/allParams}} {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{nickname}}({{^allParams}});{{/allParams}}
{{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}
);{{/hasMore}}{{/allParams}} );{{/hasMore}}{{/allParams}}
@ -31,15 +34,15 @@ public interface {{classname}} {
* {{summary}} * {{summary}}
* Async method * Async method
{{#allParams}} * @param {{paramName}} {{description}} {{#allParams}} * @param {{paramName}} {{description}}
{{/allParams}} * @param cb callback method {{/allParams}} * @param cb callback method
* @return void * @return void
*/ */
{{#formParams}}{{#-first}} {{#formParams}}{{#-first}}
{{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}}
@{{httpMethod}}("{{path}}") @{{httpMethod}}("{{path}}")
void {{nickname}}( void {{nickname}}(
{{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}, {{/allParams}}Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}, {{/allParams}}Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb
); );
{{/operation}} {{/operation}}
} }
{{/operations}} {{/operations}}

View File

@ -0,0 +1,103 @@
group = '{{groupId}}'
version = '{{artifactVersion}}'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
repositories {
jcenter()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
install {
repositories.mavenInstaller {
pom.artifactId = '{{artifactId}}'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
okhttp_version = "2.3.0"
oltu_version = "1.0.0"
retrofit_version = "1.9.0"
swagger_annotations_version = "1.5.0"
junit_version = "4.12"
}
dependencies {
compile "com.squareup.okhttp:okhttp:$okhttp_version"
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
testCompile "junit:junit:$junit_version"
}

View File

@ -1 +1 @@
{{#isQueryParam}}@Query("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} {{#isQueryParam}}@Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}}

View File

@ -0,0 +1 @@
rootProject.name = "{{artifactId}}"

View File

@ -3,7 +3,7 @@
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
{{#operations}} {{#operations}}
module {{package}} { namespace {{package}} {
'use strict'; 'use strict';
{{#description}} {{#description}}
@ -16,7 +16,7 @@ module {{package}} {
static $inject: string[] = ['$http', '$httpParamSerializer']; static $inject: string[] = ['$http', '$httpParamSerializer'];
constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (any) => any) { constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (d: any) => any) {
if (basePath) { if (basePath) {
this.basePath = basePath; this.basePath = basePath;
} }
@ -24,16 +24,16 @@ module {{package}} {
{{#operation}} {{#operation}}
public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> {
var path = this.basePath + '{{path}}'; let path = this.basePath + '{{path}}';
{{#pathParams}} {{#pathParams}}
path = path.replace('{' + '{{baseName}}' + '}', String({{paramName}})); path = path.replace('{' + '{{baseName}}' + '}', String({{paramName}}));
{{/pathParams}} {{/pathParams}}
var queryParameters: any = {}; let queryParameters: any = {};
var headerParams: any = {}; let headerParams: any = {};
{{#hasFormParams}} {{#hasFormParams}}
var formParams: any = {}; let formParams: any = {};
{{/hasFormParams}} {{/hasFormParams}}
{{#allParams}} {{#allParams}}
@ -63,7 +63,7 @@ module {{package}} {
formParams['{{baseName}}'] = {{paramName}}; formParams['{{baseName}}'] = {{paramName}};
{{/formParams}} {{/formParams}}
var httpRequestParams: any = { let httpRequestParams: any = {
method: '{{httpMethod}}', method: '{{httpMethod}}',
url: path, url: path,
json: {{#hasFormParams}}false{{/hasFormParams}}{{^hasFormParams}}true{{/hasFormParams}}, json: {{#hasFormParams}}false{{/hasFormParams}}{{^hasFormParams}}true{{/hasFormParams}},
@ -76,7 +76,7 @@ module {{package}} {
}; };
if (extraHttpRequestParams) { if (extraHttpRequestParams) {
for (var k in extraHttpRequestParams) { for (let k in extraHttpRequestParams) {
if (extraHttpRequestParams.hasOwnProperty(k)) { if (extraHttpRequestParams.hasOwnProperty(k)) {
httpRequestParams[k] = extraHttpRequestParams[k]; httpRequestParams[k] = extraHttpRequestParams[k];
} }

View File

@ -1,6 +1,6 @@
/// <reference path="api.d.ts" /> /// <reference path="api.d.ts" />
module {{package}} { namespace {{package}} {
'use strict'; 'use strict';
{{#models}} {{#models}}
@ -10,7 +10,7 @@ module {{package}} {
* {{{description}}} * {{{description}}}
*/ */
{{/description}} {{/description}}
export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{
{{#vars}} {{#vars}}
{{#description}} {{#description}}
@ -23,7 +23,7 @@ module {{package}} {
} }
{{#hasEnums}} {{#hasEnums}}
export module {{classname}} { export namespace {{classname}} {
{{#vars}} {{#vars}}
{{#isEnum}} {{#isEnum}}

View File

@ -27,7 +27,7 @@ export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{
} }
{{#hasEnums}} {{#hasEnums}}
export module {{classname}} { export namespace {{classname}} {
{{#vars}} {{#vars}}
{{#isEnum}} {{#isEnum}}
export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}}
@ -157,15 +157,15 @@ export class {{classname}} {
{{#operation}} {{#operation}}
public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> {
var path = this.url + this.basePath + '{{path}}'; let path = this.url + this.basePath + '{{path}}';
{{#pathParams}} {{#pathParams}}
path = path.replace('{' + '{{baseName}}' + '}', String({{paramName}})); path = path.replace('{' + '{{baseName}}' + '}', String({{paramName}}));
{{/pathParams}} {{/pathParams}}
var queryParameters: any = {}; let queryParameters: any = {};
var headerParams: any = {}; let headerParams: any = {};
var formParams: any = {}; let formParams: any = {};
{{#allParams}}{{#required}} {{#allParams}}{{#required}}
// verify required parameter '{{paramName}}' is set // verify required parameter '{{paramName}}' is set
@ -183,7 +183,7 @@ export class {{classname}} {
headerParams['{{baseName}}'] = {{paramName}}; headerParams['{{baseName}}'] = {{paramName}};
{{/headerParams}} {{/headerParams}}
var useFormData = false; let useFormData = false;
{{#formParams}} {{#formParams}}
if ({{paramName}} !== undefined) { if ({{paramName}} !== undefined) {
@ -194,9 +194,9 @@ export class {{classname}} {
{{/isFile}} {{/isFile}}
{{/formParams}} {{/formParams}}
var deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); let deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>();
var requestOptions: request.Options = { let requestOptions: request.Options = {
method: '{{httpMethod}}', method: '{{httpMethod}}',
qs: queryParameters, qs: queryParameters,
headers: headerParams, headers: headerParams,

View File

@ -1,11 +1,11 @@
<?php <?php
/** /**
* ApiClient * ApiClient
* *
* PHP version 5 * PHP version 5
* *
* @category Class * @category Class
* @package {{invokerPackage}} * @package {{invokerPackage}}
* @author http://github.com/swagger-api/swagger-codegen * @author http://github.com/swagger-api/swagger-codegen
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
* @link https://github.com/swagger-api/swagger-codegen * @link https://github.com/swagger-api/swagger-codegen
@ -26,8 +26,8 @@
* limitations under the License. * limitations under the License.
*/ */
/** /**
* NOTE: This class is auto generated by the swagger code generator program. * NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen * https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually. * Do not edit the class manually.
*/ */
@ -37,7 +37,7 @@ namespace {{invokerPackage}};
* ApiClient Class Doc Comment * ApiClient Class Doc Comment
* *
* @category Class * @category Class
* @package {{invokerPackage}} * @package {{invokerPackage}}
* @author http://github.com/swagger-api/swagger-codegen * @author http://github.com/swagger-api/swagger-codegen
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
* @link https://github.com/swagger-api/swagger-codegen * @link https://github.com/swagger-api/swagger-codegen
@ -52,19 +52,19 @@ class ApiClient
public static $OPTIONS = "OPTIONS"; public static $OPTIONS = "OPTIONS";
public static $PUT = "PUT"; public static $PUT = "PUT";
public static $DELETE = "DELETE"; public static $DELETE = "DELETE";
/** /**
* Configuration * Configuration
* @var Configuration * @var Configuration
*/ */
protected $config; protected $config;
/** /**
* Object Serializer * Object Serializer
* @var ObjectSerializer * @var ObjectSerializer
*/ */
protected $serializer; protected $serializer;
/** /**
* Constructor of the class * Constructor of the class
* @param Configuration $config config for this ApiClient * @param Configuration $config config for this ApiClient
@ -74,11 +74,11 @@ class ApiClient
if ($config == null) { if ($config == null) {
$config = Configuration::getDefaultConfiguration(); $config = Configuration::getDefaultConfiguration();
} }
$this->config = $config; $this->config = $config;
$this->serializer = new ObjectSerializer(); $this->serializer = new ObjectSerializer();
} }
/** /**
* Get the config * Get the config
* @return Configuration * @return Configuration
@ -87,7 +87,7 @@ class ApiClient
{ {
return $this->config; return $this->config;
} }
/** /**
* Get the serializer * Get the serializer
* @return ObjectSerializer * @return ObjectSerializer
@ -96,7 +96,7 @@ class ApiClient
{ {
return $this->serializer; return $this->serializer;
} }
/** /**
* Get API key (with prefix if set) * Get API key (with prefix if set)
* @param string $apiKeyIdentifier name of apikey * @param string $apiKeyIdentifier name of apikey
@ -106,20 +106,20 @@ class ApiClient
{ {
$prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier);
$apiKey = $this->config->getApiKey($apiKeyIdentifier); $apiKey = $this->config->getApiKey($apiKeyIdentifier);
if (!isset($apiKey)) { if (!isset($apiKey)) {
return null; return null;
} }
if (isset($prefix)) { if (isset($prefix)) {
$keyWithPrefix = $prefix." ".$apiKey; $keyWithPrefix = $prefix." ".$apiKey;
} else { } else {
$keyWithPrefix = $apiKey; $keyWithPrefix = $apiKey;
} }
return $keyWithPrefix; return $keyWithPrefix;
} }
/** /**
* Make the HTTP call (Sync) * Make the HTTP call (Sync)
* @param string $resourcePath path to method endpoint * @param string $resourcePath path to method endpoint
@ -133,28 +133,28 @@ class ApiClient
*/ */
public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null)
{ {
$headers = array(); $headers = array();
// construct the http header // construct the http header
$headerParams = array_merge( $headerParams = array_merge(
(array)$this->config->getDefaultHeaders(), (array)$this->config->getDefaultHeaders(),
(array)$headerParams (array)$headerParams
); );
foreach ($headerParams as $key => $val) { foreach ($headerParams as $key => $val) {
$headers[] = "$key: $val"; $headers[] = "$key: $val";
} }
// form data // form data
if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) {
$postData = http_build_query($postData); $postData = http_build_query($postData);
} else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model
$postData = json_encode($this->serializer->sanitizeForSerialization($postData)); $postData = json_encode($this->serializer->sanitizeForSerialization($postData));
} }
$url = $this->config->getHost() . $resourcePath; $url = $this->config->getHost() . $resourcePath;
$curl = curl_init(); $curl = curl_init();
// set timeout, if needed // set timeout, if needed
if ($this->config->getCurlTimeout() != 0) { if ($this->config->getCurlTimeout() != 0) {
@ -162,13 +162,19 @@ class ApiClient
} }
// return the result on success, rather than just TRUE // return the result on success, rather than just TRUE
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// disable SSL verification, if needed
if ($this->config->getSSLVerification() == false) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
}
if (! empty($queryParams)) { if (! empty($queryParams)) {
$url = ($url . '?' . http_build_query($queryParams)); $url = ($url . '?' . http_build_query($queryParams));
} }
if ($method == self::$POST) { if ($method == self::$POST) {
curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
@ -190,44 +196,44 @@ class ApiClient
throw new ApiException('Method ' . $method . ' is not recognized.'); throw new ApiException('Method ' . $method . ' is not recognized.');
} }
curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_URL, $url);
// Set user agent // Set user agent
curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent());
// debugging for curl // debugging for curl
if ($this->config->getDebug()) { if ($this->config->getDebug()) {
error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile());
curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a'));
} else { } else {
curl_setopt($curl, CURLOPT_VERBOSE, 0); curl_setopt($curl, CURLOPT_VERBOSE, 0);
} }
// obtain the HTTP response headers // obtain the HTTP response headers
curl_setopt($curl, CURLOPT_HEADER, 1); curl_setopt($curl, CURLOPT_HEADER, 1);
// Make the request // Make the request
$response = curl_exec($curl); $response = curl_exec($curl);
$http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$http_header = substr($response, 0, $http_header_size); $http_header = substr($response, 0, $http_header_size);
$http_body = substr($response, $http_header_size); $http_body = substr($response, $http_header_size);
$response_info = curl_getinfo($curl); $response_info = curl_getinfo($curl);
// debug HTTP response body // debug HTTP response body
if ($this->config->getDebug()) { if ($this->config->getDebug()) {
error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile());
} }
// Handle the response // Handle the response
if ($response_info['http_code'] == 0) { if ($response_info['http_code'] == 0) {
throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null);
} else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) {
// return raw body if response is a file // return raw body if response is a file
if ($responseType == '\SplFileObject') { if ($responseType == '\SplFileObject') {
return array($http_body, $http_header); return array($http_body, $http_header);
} }
$data = json_decode($http_body); $data = json_decode($http_body);
if (json_last_error() > 0) { // if response is a string if (json_last_error() > 0) { // if response is a string
$data = $http_body; $data = $http_body;
@ -240,7 +246,7 @@ class ApiClient
} }
return array($data, $http_header); return array($data, $http_header);
} }
/** /**
* Return the header 'Accept' based on an array of Accept provided * Return the header 'Accept' based on an array of Accept provided
* *
@ -258,7 +264,7 @@ class ApiClient
return implode(',', $accept); return implode(',', $accept);
} }
} }
/** /**
* Return the content type based on an array of content-type provided * Return the content type based on an array of content-type provided
* *

View File

@ -27,8 +27,8 @@
*/ */
/** /**
* NOTE: This class is auto generated by the swagger code generator program. * NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen * https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually. * Do not edit the class manually.
*/ */
@ -48,70 +48,70 @@ class Configuration
{ {
private static $_defaultConfiguration = null; private static $_defaultConfiguration = null;
/** /**
* Associate array to store API key(s) * Associate array to store API key(s)
* *
* @var string[] * @var string[]
*/ */
protected $apiKeys = array(); protected $apiKeys = array();
/** /**
* Associate array to store API prefix (e.g. Bearer) * Associate array to store API prefix (e.g. Bearer)
* *
* @var string[] * @var string[]
*/ */
protected $apiKeyPrefixes = array(); protected $apiKeyPrefixes = array();
/** /**
* Username for HTTP basic authentication * Username for HTTP basic authentication
* *
* @var string * @var string
*/ */
protected $username = ''; protected $username = '';
/** /**
* Password for HTTP basic authentication * Password for HTTP basic authentication
* *
* @var string * @var string
*/ */
protected $password = ''; protected $password = '';
/** /**
* The default instance of ApiClient * The default instance of ApiClient
* *
* @var \{{invokerPackage}}\ApiClient * @var \{{invokerPackage}}\ApiClient
*/ */
protected $defaultHeaders = array(); protected $defaultHeaders = array();
/** /**
* The host * The host
* *
* @var string * @var string
*/ */
protected $host = '{{basePath}}'; protected $host = '{{basePath}}';
/** /**
* Timeout (second) of the HTTP request, by default set to 0, no timeout * Timeout (second) of the HTTP request, by default set to 0, no timeout
* *
* @var string * @var string
*/ */
protected $curlTimeout = 0; protected $curlTimeout = 0;
/** /**
* User agent of the HTTP request, set to "PHP-Swagger" by default * User agent of the HTTP request, set to "PHP-Swagger" by default
* *
* @var string * @var string
*/ */
protected $userAgent = "PHP-Swagger/{{artifactVersion}}"; protected $userAgent = "PHP-Swagger/{{artifactVersion}}";
/** /**
* Debug switch (default set to false) * Debug switch (default set to false)
* *
* @var bool * @var bool
*/ */
protected $debug = false; protected $debug = false;
/** /**
* Debug file location (log to STDOUT by default) * Debug file location (log to STDOUT by default)
* *
@ -126,6 +126,15 @@ class Configuration
*/ */
protected $tempFolderPath; protected $tempFolderPath;
/**
* Indicates if SSL verification should be enabled or disabled.
*
* This is useful if the host uses a self-signed SSL certificate.
*
* @var boolean True if the certificate should be validated, false otherwise.
*/
protected $sslVerification = true;
/** /**
* Constructor * Constructor
*/ */
@ -133,7 +142,7 @@ class Configuration
{ {
$this->tempFolderPath = sys_get_temp_dir(); $this->tempFolderPath = sys_get_temp_dir();
} }
/** /**
* Sets API key * Sets API key
* *
@ -147,7 +156,7 @@ class Configuration
$this->apiKeys[$apiKeyIdentifier] = $key; $this->apiKeys[$apiKeyIdentifier] = $key;
return $this; return $this;
} }
/** /**
* Gets API key * Gets API key
* *
@ -159,7 +168,7 @@ class Configuration
{ {
return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null;
} }
/** /**
* Sets the prefix for API key (e.g. Bearer) * Sets the prefix for API key (e.g. Bearer)
* *
@ -173,7 +182,7 @@ class Configuration
$this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix;
return $this; return $this;
} }
/** /**
* Gets API key prefix * Gets API key prefix
* *
@ -185,7 +194,7 @@ class Configuration
{ {
return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null;
} }
/** /**
* Sets the username for HTTP basic authentication * Sets the username for HTTP basic authentication
* *
@ -198,7 +207,7 @@ class Configuration
$this->username = $username; $this->username = $username;
return $this; return $this;
} }
/** /**
* Gets the username for HTTP basic authentication * Gets the username for HTTP basic authentication
* *
@ -208,7 +217,7 @@ class Configuration
{ {
return $this->username; return $this->username;
} }
/** /**
* Sets the password for HTTP basic authentication * Sets the password for HTTP basic authentication
* *
@ -221,7 +230,7 @@ class Configuration
$this->password = $password; $this->password = $password;
return $this; return $this;
} }
/** /**
* Gets the password for HTTP basic authentication * Gets the password for HTTP basic authentication
* *
@ -231,7 +240,7 @@ class Configuration
{ {
return $this->password; return $this->password;
} }
/** /**
* Adds a default header * Adds a default header
* *
@ -245,11 +254,11 @@ class Configuration
if (!is_string($headerName)) { if (!is_string($headerName)) {
throw new \InvalidArgumentException('Header name must be a string.'); throw new \InvalidArgumentException('Header name must be a string.');
} }
$this->defaultHeaders[$headerName] = $headerValue; $this->defaultHeaders[$headerName] = $headerValue;
return $this; return $this;
} }
/** /**
* Gets the default header * Gets the default header
* *
@ -259,7 +268,7 @@ class Configuration
{ {
return $this->defaultHeaders; return $this->defaultHeaders;
} }
/** /**
* Deletes a default header * Deletes a default header
* *
@ -271,7 +280,7 @@ class Configuration
{ {
unset($this->defaultHeaders[$headerName]); unset($this->defaultHeaders[$headerName]);
} }
/** /**
* Sets the host * Sets the host
* *
@ -284,7 +293,7 @@ class Configuration
$this->host = $host; $this->host = $host;
return $this; return $this;
} }
/** /**
* Gets the host * Gets the host
* *
@ -294,7 +303,7 @@ class Configuration
{ {
return $this->host; return $this->host;
} }
/** /**
* Sets the user agent of the api client * Sets the user agent of the api client
* *
@ -307,11 +316,11 @@ class Configuration
if (!is_string($userAgent)) { if (!is_string($userAgent)) {
throw new \InvalidArgumentException('User-agent must be a string.'); throw new \InvalidArgumentException('User-agent must be a string.');
} }
$this->userAgent = $userAgent; $this->userAgent = $userAgent;
return $this; return $this;
} }
/** /**
* Gets the user agent of the api client * Gets the user agent of the api client
* *
@ -321,7 +330,7 @@ class Configuration
{ {
return $this->userAgent; return $this->userAgent;
} }
/** /**
* Sets the HTTP timeout value * Sets the HTTP timeout value
* *
@ -334,11 +343,11 @@ class Configuration
if (!is_numeric($seconds) || $seconds < 0) { if (!is_numeric($seconds) || $seconds < 0) {
throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.');
} }
$this->curlTimeout = $seconds; $this->curlTimeout = $seconds;
return $this; return $this;
} }
/** /**
* Gets the HTTP timeout value * Gets the HTTP timeout value
* *
@ -348,10 +357,10 @@ class Configuration
{ {
return $this->curlTimeout; return $this->curlTimeout;
} }
/** /**
* Sets debug flag * Sets debug flag
* *
* @param bool $debug Debug flag * @param bool $debug Debug flag
* *
* @return Configuration * @return Configuration
@ -361,7 +370,7 @@ class Configuration
$this->debug = $debug; $this->debug = $debug;
return $this; return $this;
} }
/** /**
* Gets the debug flag * Gets the debug flag
* *
@ -371,7 +380,7 @@ class Configuration
{ {
return $this->debug; return $this->debug;
} }
/** /**
* Sets the debug file * Sets the debug file
* *
@ -384,7 +393,7 @@ class Configuration
$this->debugFile = $debugFile; $this->debugFile = $debugFile;
return $this; return $this;
} }
/** /**
* Gets the debug file * Gets the debug file
* *
@ -394,7 +403,7 @@ class Configuration
{ {
return $this->debugFile; return $this->debugFile;
} }
/** /**
* Sets the temp folder path * Sets the temp folder path
* *
@ -407,7 +416,7 @@ class Configuration
$this->tempFolderPath = $tempFolderPath; $this->tempFolderPath = $tempFolderPath;
return $this; return $this;
} }
/** /**
* Gets the temp folder path * Gets the temp folder path
* *
@ -417,7 +426,30 @@ class Configuration
{ {
return $this->tempFolderPath; return $this->tempFolderPath;
} }
/**
* Sets if SSL verification should be enabled or disabled
*
* @param boolean $sslVerification True if the certificate should be validated, false otherwise
*
* @return Configuration
*/
public function setSSLVerification($sslVerification)
{
$this->sslVerification = $sslVerification;
return $this;
}
/**
* Gets if SSL verification should be enabled or disabled
*
* @return boolean True if the certificate should be validated, false otherwise
*/
public function getSSLVerification()
{
return $this->sslVerification;
}
/** /**
* Gets the default configuration instance * Gets the default configuration instance
* *
@ -428,10 +460,10 @@ class Configuration
if (self::$_defaultConfiguration == null) { if (self::$_defaultConfiguration == null) {
self::$_defaultConfiguration = new Configuration(); self::$_defaultConfiguration = new Configuration();
} }
return self::$_defaultConfiguration; return self::$_defaultConfiguration;
} }
/** /**
* Sets the detault configuration instance * Sets the detault configuration instance
* *
@ -443,7 +475,7 @@ class Configuration
{ {
self::$_defaultConfiguration = $config; self::$_defaultConfiguration = $config;
} }
/** /**
* Gets the essential information for debugging * Gets the essential information for debugging
* *
@ -457,8 +489,8 @@ class Configuration
$report .= " Swagger Spec Version: {{version}}\n"; $report .= " Swagger Spec Version: {{version}}\n";
$report .= " SDK Package Version: {{artifactVersion}}\n"; $report .= " SDK Package Version: {{artifactVersion}}\n";
$report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n"; $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n";
return $report; return $report;
} }
} }

View File

@ -138,7 +138,7 @@ module {{moduleName}}
end end
def base_url def base_url
url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}" url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '')
URI.encode(url) URI.encode(url)
end end

View File

@ -139,4 +139,52 @@ public class CodegenTest {
Assert.assertTrue(op.bodyParam.isBinary); Assert.assertTrue(op.bodyParam.isBinary);
Assert.assertTrue(op.responses.get(0).isBinary); Assert.assertTrue(op.responses.get(0).isBinary);
} }
@Test(description = "use operation consumes and produces")
public void localConsumesAndProducesTest() {
final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json");
final DefaultCodegen codegen = new DefaultCodegen();
final String path = "/tests/localConsumesAndProduces";
final Operation p = model.getPaths().get(path).getGet();
CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model);
Assert.assertTrue(op.hasConsumes);
Assert.assertEquals(op.consumes.size(), 1);
Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/json");
Assert.assertTrue(op.hasProduces);
Assert.assertEquals(op.produces.size(), 1);
Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/json");
}
@Test(description = "use spec consumes and produces")
public void globalConsumesAndProducesTest() {
final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json");
final DefaultCodegen codegen = new DefaultCodegen();
final String path = "/tests/globalConsumesAndProduces";
final Operation p = model.getPaths().get(path).getGet();
CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model);
Assert.assertTrue(op.hasConsumes);
Assert.assertEquals(op.consumes.size(), 1);
Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/global_consumes");
Assert.assertTrue(op.hasProduces);
Assert.assertEquals(op.produces.size(), 1);
Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/global_produces");
}
@Test(description = "use operation consumes and produces (reset in operation with empty array)")
public void localResetConsumesAndProducesTest() {
final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json");
final DefaultCodegen codegen = new DefaultCodegen();
final String path = "/tests/localResetConsumesAndProduces";
final Operation p = model.getPaths().get(path).getGet();
CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model);
Assert.assertNotNull(op);
Assert.assertFalse(op.hasConsumes);
Assert.assertNull(op.consumes);
Assert.assertFalse(op.hasProduces);
Assert.assertNull(op.produces);
}
} }

View File

@ -17,11 +17,14 @@ import java.io.OutputStreamWriter;
import java.io.Writer; import java.io.Writer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertNull;
/** /**
* Tests for DefaultGenerator logic * Tests for DefaultGenerator logic
@ -44,6 +47,102 @@ public class DefaultGeneratorTest {
folder.delete(); folder.delete();
} }
@Test
public void testSecurityWithoutGlobal() throws Exception {
final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/petstore.json");
CodegenConfig codegenConfig = new JavaClientCodegen();
ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig);
DefaultGenerator gen = new DefaultGenerator();
gen.opts(clientOptInput);
Map<String, List<CodegenOperation>> paths = gen.processPaths(swagger.getPaths());
CodegenSecurity apiKey, petstoreAuth;
// security of "getPetById": api_key
CodegenOperation getPetById = findCodegenOperationByOperationId(paths, "getPetById");
assertEquals(getPetById.authMethods.size(), 1);
apiKey = getPetById.authMethods.iterator().next();
assertEquals(apiKey.name, "api_key");
assertEquals(apiKey.type, "apiKey");
// security of "updatePetWithForm": petstore_auth
CodegenOperation updatePetWithForm = findCodegenOperationByOperationId(paths, "updatePetWithForm");
assertEquals(updatePetWithForm.authMethods.size(), 1);
petstoreAuth = updatePetWithForm.authMethods.iterator().next();
assertEquals(petstoreAuth.name, "petstore_auth");
assertEquals(petstoreAuth.type, "oauth2");
// security of "loginUser": null (no global security either)
CodegenOperation loginUser = findCodegenOperationByOperationId(paths, "loginUser");
assertNull(loginUser.authMethods);
}
@Test
public void testSecurityWithGlobal() throws Exception {
final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/globalSecurity.json");
CodegenConfig codegenConfig = new JavaClientCodegen();
ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig);
DefaultGenerator gen = new DefaultGenerator();
gen.opts(clientOptInput);
Map<String, List<CodegenOperation>> paths = gen.processPaths(swagger.getPaths());
CodegenSecurity cs, apiKey, apiKey2, petstoreAuth;
// security of "getPetById": api_key
CodegenOperation getPetById = findCodegenOperationByOperationId(paths, "getPetById");
assertEquals(getPetById.authMethods.size(), 1);
apiKey = getPetById.authMethods.iterator().next();
assertEquals(apiKey.name, "api_key");
assertEquals(apiKey.type, "apiKey");
// security of "updatePetWithForm": petstore_auth
CodegenOperation updatePetWithForm = findCodegenOperationByOperationId(paths, "updatePetWithForm");
assertEquals(updatePetWithForm.authMethods.size(), 1);
petstoreAuth = updatePetWithForm.authMethods.iterator().next();
assertEquals(petstoreAuth.name, "petstore_auth");
assertEquals(petstoreAuth.type, "oauth2");
// security of "loginUser": api_key, petstore_auth (from global security)
CodegenOperation loginUser = findCodegenOperationByOperationId(paths, "loginUser");
assertEquals(loginUser.authMethods.size(), 2);
cs = loginUser.authMethods.get(0);
if ("api_key".equals(cs.name)) {
apiKey = cs;
petstoreAuth = loginUser.authMethods.get(1);
} else {
petstoreAuth = cs;
apiKey = loginUser.authMethods.get(1);
}
assertEquals(apiKey.name, "api_key");
assertEquals(apiKey.type, "apiKey");
assertEquals(petstoreAuth.name, "petstore_auth");
assertEquals(petstoreAuth.type, "oauth2");
// security of "logoutUser": null (override global security)
CodegenOperation logoutUser = findCodegenOperationByOperationId(paths, "logoutUser");
assertNull(logoutUser.authMethods);
// security of "getUserByName": api_key, api_key2 (override global security)
CodegenOperation getUserByName = findCodegenOperationByOperationId(paths, "getUserByName");
assertEquals(getUserByName.authMethods.size(), 2);
cs = getUserByName.authMethods.get(0);
if ("api_key".equals(cs.name)) {
apiKey = cs;
apiKey2 = getUserByName.authMethods.get(1);
} else {
apiKey2 = cs;
apiKey = getUserByName.authMethods.get(1);
}
assertEquals(apiKey.name, "api_key");
assertEquals(apiKey.type, "apiKey");
assertEquals(apiKey2.name, "api_key2");
assertEquals(apiKey2.type, "apiKey");
}
@Test @Test
public void testSkipOverwrite() throws Exception { public void testSkipOverwrite() throws Exception {
final File output = folder.getRoot(); final File output = folder.getRoot();
@ -89,4 +188,15 @@ public class DefaultGeneratorTest {
out.close(); out.close();
} }
private CodegenOperation findCodegenOperationByOperationId(Map<String, List<CodegenOperation>> paths, String operationId) {
for (List<CodegenOperation> ops : paths.values()) {
for (CodegenOperation co : ops) {
if (operationId.equals(co.operationId)) {
return co;
}
}
}
return null;
}
} }

View File

@ -0,0 +1,130 @@
{
"swagger": "2.0",
"info": {
"description": "Spec for testing global consumes and produces",
"version": "1.0.0",
"title": "Swagger Petstore",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"email": "apiteam@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},
"host": "petstore.swagger.io",
"basePath": "/v2",
"consumes": ["application/global_consumes"],
"produces": ["application/global_produces"],
"schemes": [
"http"
],
"paths": {
"/tests/localConsumesAndProduces": {
"get": {
"tags": [
"tests"
],
"summary": "Operation with local consumes and produces",
"description": "",
"operationId": "localConsumesAndProduces",
"produces": [
"application/json"
],
"consumes": [
"application/json"
],
"parameters": [
],
"responses": {
"200": {
"description": "successful operation. Returning a simple int.",
"schema": {
"type": "integer",
"format": "int64"
}
}
}
}
},
"/tests/globalConsumesAndProduces": {
"get": {
"tags": [
"tests"
],
"summary": "Operation with global consumes and produces",
"description": "",
"operationId": "globalConsumesAndProduces",
"parameters": [
],
"responses": {
"200": {
"description": "successful operation. Returning a simple int.",
"schema": {
"type": "integer",
"format": "int64"
}
}
}
}
},
"/tests/localResetConsumesAndProduces": {
"get": {
"tags": [
"tests"
],
"summary": "Operation with local consumes and produces set to empty (reset)",
"description": "",
"operationId": "localResetConsumesAndProduces",
"parameters": [
],
"consumes": [],
"produces": [],
"responses": {
"200": {
"description": "successful operation. Returning a simple int.",
"schema": {
"type": "integer",
"format": "int64"
}
}
}
}
}
},
"securityDefinitions": {
"api_key": {
"type": "apiKey",
"name": "api_key",
"in": "header"
},
"petstore_auth": {
"type": "oauth2",
"authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog",
"flow": "implicit",
"scopes": {
"write:pets": "modify pets in your account",
"read:pets": "read your pets"
}
}
},
"definitions": {
"CustomModel": {
"required": [
"id"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string",
"example": "doggie"
}
}
}
}
}

View File

@ -0,0 +1,998 @@
{
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters",
"version": "1.0.0",
"title": "Swagger Petstore",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"email": "apiteam@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},
"host": "petstore.swagger.io",
"basePath": "/v2",
"schemes": [
"http"
],
"paths": {
"/pet": {
"post": {
"tags": [
"pet"
],
"summary": "Add a new pet to the store",
"description": "",
"operationId": "addPet",
"consumes": [
"application/json",
"application/xml"
],
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Pet object that needs to be added to the store",
"required": false,
"schema": {
"$ref": "#/definitions/Pet"
}
}
],
"responses": {
"405": {
"description": "Invalid input"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
},
"put": {
"tags": [
"pet"
],
"summary": "Update an existing pet",
"description": "",
"operationId": "updatePet",
"consumes": [
"application/json",
"application/xml"
],
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Pet object that needs to be added to the store",
"required": false,
"schema": {
"$ref": "#/definitions/Pet"
}
}
],
"responses": {
"405": {
"description": "Validation exception"
},
"404": {
"description": "Pet not found"
},
"400": {
"description": "Invalid ID supplied"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/findByStatus": {
"get": {
"tags": [
"pet"
],
"summary": "Finds Pets by status",
"description": "Multiple status values can be provided with comma seperated strings",
"operationId": "findPetsByStatus",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "status",
"in": "query",
"description": "Status values that need to be considered for filter",
"required": false,
"type": "array",
"items": {
"type": "string"
},
"collectionFormat": "multi",
"default": "available"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"400": {
"description": "Invalid status value"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/findByTags": {
"get": {
"tags": [
"pet"
],
"summary": "Finds Pets by tags",
"description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",
"operationId": "findPetsByTags",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "tags",
"in": "query",
"description": "Tags to filter by",
"required": false,
"type": "array",
"items": {
"type": "string"
},
"collectionFormat": "multi"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"400": {
"description": "Invalid tag value"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/{petId}": {
"get": {
"tags": [
"pet"
],
"summary": "Find pet by ID",
"description": "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions",
"operationId": "getPetById",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "petId",
"in": "path",
"description": "ID of pet that needs to be fetched",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"404": {
"description": "Pet not found"
},
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Pet"
}
},
"400": {
"description": "Invalid ID supplied"
}
},
"security": [
{
"api_key": []
},
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
},
"post": {
"tags": [
"pet"
],
"summary": "Updates a pet in the store with form data",
"description": "",
"operationId": "updatePetWithForm",
"consumes": [
"application/x-www-form-urlencoded"
],
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "petId",
"in": "path",
"description": "ID of pet that needs to be updated",
"required": true,
"type": "string"
},
{
"name": "name",
"in": "formData",
"description": "Updated name of the pet",
"required": false,
"type": "string"
},
{
"name": "status",
"in": "formData",
"description": "Updated status of the pet",
"required": false,
"type": "string"
}
],
"responses": {
"405": {
"description": "Invalid input"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
},
"delete": {
"tags": [
"pet"
],
"summary": "Deletes a pet",
"description": "",
"operationId": "deletePet",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "api_key",
"in": "header",
"description": "",
"required": false,
"type": "string"
},
{
"name": "petId",
"in": "path",
"description": "Pet id to delete",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"400": {
"description": "Invalid pet value"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/{petId}/uploadImage": {
"post": {
"tags": [
"pet"
],
"summary": "uploads an image",
"description": "",
"operationId": "uploadFile",
"consumes": [
"multipart/form-data"
],
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "petId",
"in": "path",
"description": "ID of pet to update",
"required": true,
"type": "integer",
"format": "int64"
},
{
"name": "additionalMetadata",
"in": "formData",
"description": "Additional data to pass to server",
"required": false,
"type": "string"
},
{
"name": "file",
"in": "formData",
"description": "file to upload",
"required": false,
"type": "file"
}
],
"responses": {
"default": {
"description": "successful operation"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/store/inventory": {
"get": {
"tags": [
"store"
],
"summary": "Returns pet inventories by status",
"description": "Returns a map of status codes to quantities",
"operationId": "getInventory",
"produces": [
"application/json",
"application/xml"
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "object",
"additionalProperties": {
"type": "integer",
"format": "int32"
}
}
}
},
"security": [
{
"api_key": []
}
]
}
},
"/store/order": {
"post": {
"tags": [
"store"
],
"summary": "Place an order for a pet",
"description": "",
"operationId": "placeOrder",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "order placed for purchasing the pet",
"required": false,
"schema": {
"$ref": "#/definitions/Order"
}
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Order"
}
},
"400": {
"description": "Invalid Order"
}
}
}
},
"/store/order/{orderId}": {
"get": {
"tags": [
"store"
],
"summary": "Find purchase order by ID",
"description": "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
"operationId": "getOrderById",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "orderId",
"in": "path",
"description": "ID of pet that needs to be fetched",
"required": true,
"type": "string"
}
],
"responses": {
"404": {
"description": "Order not found"
},
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Order"
}
},
"400": {
"description": "Invalid ID supplied"
}
}
},
"delete": {
"tags": [
"store"
],
"summary": "Delete purchase order by ID",
"description": "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",
"operationId": "deleteOrder",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "orderId",
"in": "path",
"description": "ID of the order that needs to be deleted",
"required": true,
"type": "string"
}
],
"responses": {
"404": {
"description": "Order not found"
},
"400": {
"description": "Invalid ID supplied"
}
}
}
},
"/user": {
"post": {
"tags": [
"user"
],
"summary": "Create user",
"description": "This can only be done by the logged in user.",
"operationId": "createUser",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Created user object",
"required": false,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/createWithArray": {
"post": {
"tags": [
"user"
],
"summary": "Creates list of users with given input array",
"description": "",
"operationId": "createUsersWithArrayInput",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "List of user object",
"required": false,
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/createWithList": {
"post": {
"tags": [
"user"
],
"summary": "Creates list of users with given input array",
"description": "",
"operationId": "createUsersWithListInput",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "List of user object",
"required": false,
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/login": {
"get": {
"tags": [
"user"
],
"summary": "Logs user into the system",
"description": "",
"operationId": "loginUser",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "username",
"in": "query",
"description": "The user name for login",
"required": false,
"type": "string"
},
{
"name": "password",
"in": "query",
"description": "The password for login in clear text",
"required": false,
"type": "string"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "string"
}
},
"400": {
"description": "Invalid username/password supplied"
}
}
}
},
"/user/logout": {
"get": {
"tags": [
"user"
],
"summary": "Logs out current logged in user session",
"description": "",
"operationId": "logoutUser",
"produces": [
"application/json",
"application/xml"
],
"responses": {
"default": {
"description": "successful operation"
}
},
"security": []
}
},
"/user/{username}": {
"get": {
"tags": [
"user"
],
"summary": "Get user by user name",
"description": "",
"operationId": "getUserByName",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "username",
"in": "path",
"description": "The name that needs to be fetched. Use user1 for testing. ",
"required": true,
"type": "string"
}
],
"responses": {
"404": {
"description": "User not found"
},
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/User"
},
"examples": {
"application/json": {
"id": 1,
"username": "johnp",
"firstName": "John",
"lastName": "Public",
"email": "johnp@swagger.io",
"password": "-secret-",
"phone": "0123456789",
"userStatus": 0
}
}
},
"400": {
"description": "Invalid username supplied"
}
},
"security": [
{
"api_key": [],
"api_key2": []
}
]
},
"put": {
"tags": [
"user"
],
"summary": "Updated user",
"description": "This can only be done by the logged in user.",
"operationId": "updateUser",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "username",
"in": "path",
"description": "name that need to be deleted",
"required": true,
"type": "string"
},
{
"in": "body",
"name": "body",
"description": "Updated user object",
"required": false,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"404": {
"description": "User not found"
},
"400": {
"description": "Invalid user supplied"
}
}
},
"delete": {
"tags": [
"user"
],
"summary": "Delete user",
"description": "This can only be done by the logged in user.",
"operationId": "deleteUser",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "username",
"in": "path",
"description": "The name that needs to be deleted",
"required": true,
"type": "string"
}
],
"responses": {
"404": {
"description": "User not found"
},
"400": {
"description": "Invalid username supplied"
}
}
}
}
},
"securityDefinitions": {
"api_key": {
"type": "apiKey",
"name": "api_key",
"in": "header"
},
"api_key2": {
"type": "apiKey",
"name": "api_key2",
"in": "query"
},
"petstore_auth": {
"type": "oauth2",
"authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog",
"flow": "implicit",
"scopes": {
"write:pets": "modify pets in your account",
"read:pets": "read your pets"
}
}
},
"security": [
{
"api_key": [],
"petstore_auth": [
"write:pets",
"read:pets"
]
}
],
"definitions": {
"User": {
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"username": {
"type": "string"
},
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"email": {
"type": "string"
},
"password": {
"type": "string"
},
"phone": {
"type": "string"
},
"userStatus": {
"type": "integer",
"format": "int32",
"description": "User Status"
}
},
"xml": {
"name": "User"
}
},
"Category": {
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
}
},
"xml": {
"name": "Category"
}
},
"Pet": {
"required": [
"name",
"photoUrls"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"category": {
"$ref": "#/definitions/Category"
},
"name": {
"type": "string",
"example": "doggie"
},
"photoUrls": {
"type": "array",
"xml": {
"name": "photoUrl",
"wrapped": true
},
"items": {
"type": "string"
}
},
"tags": {
"type": "array",
"xml": {
"name": "tag",
"wrapped": true
},
"items": {
"$ref": "#/definitions/Tag"
}
},
"status": {
"type": "string",
"description": "pet status in the store",
"enum": [
"available",
"pending",
"sold"
]
}
},
"xml": {
"name": "Pet"
}
},
"Tag": {
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
}
},
"xml": {
"name": "Tag"
}
},
"Order": {
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"petId": {
"type": "integer",
"format": "int64"
},
"quantity": {
"type": "integer",
"format": "int32"
},
"shipDate": {
"type": "string",
"format": "date-time"
},
"status": {
"type": "string",
"description": "Order Status",
"enum": [
"placed",
"approved",
"delivered"
]
},
"complete": {
"type": "boolean"
}
},
"xml": {
"name": "Order"
}
}
}
}

View File

@ -426,6 +426,7 @@
<module>samples/client/petstore/java/default</module> <module>samples/client/petstore/java/default</module>
<module>samples/client/petstore/java/jersey2</module> <module>samples/client/petstore/java/jersey2</module>
<module>samples/client/petstore/java/okhttp-gson</module> <module>samples/client/petstore/java/okhttp-gson</module>
<module>samples/client/petstore/java/retrofit</module>
<module>samples/client/petstore/scala</module> <module>samples/client/petstore/scala</module>
<module>samples/server/petstore/spring-mvc</module> <module>samples/server/petstore/spring-mvc</module>
<!--module>samples/client/petstore/objc</module--> <!--module>samples/client/petstore/objc</module-->

View File

@ -0,0 +1,107 @@
group = 'io.swagger'
version = '1.0.0'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
repositories {
jcenter()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
install {
repositories.mavenInstaller {
pom.artifactId = 'swagger-java-client'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
swagger_annotations_version = "1.5.0"
jackson_version = "2.4.2"
jersey_version = "1.18"
jodatime_version = "2.3"
junit_version = "4.8.1"
}
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.sun.jersey:jersey-client:$jersey_version"
compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
compile "joda-time:joda-time:$jodatime_version"
testCompile "junit:junit:$junit_version"
}

View File

@ -0,0 +1,2 @@
# Uncomment to build for Android
#target = android

View File

@ -0,0 +1 @@
rootProject.name = "swagger-java-client"

View File

@ -6,18 +6,12 @@ import io.swagger.client.Configuration;
import io.swagger.client.Pair; import io.swagger.client.Pair;
import io.swagger.client.TypeRef; import io.swagger.client.TypeRef;
import io.swagger.client.model.*;
import java.util.*;
import io.swagger.client.model.Pet; import io.swagger.client.model.Pet;
import java.io.File; import java.io.File;
import java.io.File; import java.util.*;
import java.util.Map;
import java.util.HashMap;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-16T10:32:51.872+08:00")
public class PetApi { public class PetApi {
private ApiClient apiClient; private ApiClient apiClient;
@ -272,7 +266,7 @@ public class PetApi {
}; };
final String contentType = apiClient.selectHeaderContentType(contentTypes); final String contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "api_key", "petstore_auth" }; String[] authNames = new String[] { "api_key" };

View File

@ -6,18 +6,12 @@ import io.swagger.client.Configuration;
import io.swagger.client.Pair; import io.swagger.client.Pair;
import io.swagger.client.TypeRef; import io.swagger.client.TypeRef;
import io.swagger.client.model.*;
import java.util.*;
import java.util.Map; import java.util.Map;
import io.swagger.client.model.Order; import io.swagger.client.model.Order;
import java.io.File; import java.util.*;
import java.util.Map;
import java.util.HashMap;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00")
public class StoreApi { public class StoreApi {
private ApiClient apiClient; private ApiClient apiClient;

View File

@ -6,18 +6,12 @@ import io.swagger.client.Configuration;
import io.swagger.client.Pair; import io.swagger.client.Pair;
import io.swagger.client.TypeRef; import io.swagger.client.TypeRef;
import io.swagger.client.model.*;
import java.util.*;
import io.swagger.client.model.User; import io.swagger.client.model.User;
import java.util.*; import java.util.*;
import java.io.File; import java.util.*;
import java.util.Map;
import java.util.HashMap;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00")
public class UserApi { public class UserApi {
private ApiClient apiClient; private ApiClient apiClient;

View File

@ -10,7 +10,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
@ApiModel(description = "") @ApiModel(description = "")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00")
public class Order { public class Order {
private Long id = null; private Long id = null;

View File

@ -2,8 +2,8 @@ package io.swagger.client.model;
import io.swagger.client.StringUtil; import io.swagger.client.StringUtil;
import io.swagger.client.model.Category; import io.swagger.client.model.Category;
import io.swagger.client.model.Tag;
import java.util.*; import java.util.*;
import io.swagger.client.model.Tag;
@ -12,7 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
@ApiModel(description = "") @ApiModel(description = "")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00")
public class Pet { public class Pet {
private Long id = null; private Long id = null;

View File

@ -0,0 +1,107 @@
group = 'io.swagger'
version = '1.0.0'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
repositories {
jcenter()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
install {
repositories.mavenInstaller {
pom.artifactId = 'swagger-petstore-jersey2'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
swagger_annotations_version = "1.5.0"
jackson_version = "2.4.2"
jersey_version = "2.6"
jodatime_version = "2.3"
junit_version = "4.8.1"
}
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.glassfish.jersey.core:jersey-client:$jersey_version"
compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5"
compile "joda-time:joda-time:$jodatime_version"
testCompile "junit:junit:$junit_version"
}

View File

@ -0,0 +1,2 @@
# Uncomment to build for Android
#target = android

View File

@ -0,0 +1 @@
rootProject.name = "swagger-petstore-jersey2"

View File

@ -6,18 +6,12 @@ import io.swagger.client.Configuration;
import io.swagger.client.Pair; import io.swagger.client.Pair;
import io.swagger.client.TypeRef; import io.swagger.client.TypeRef;
import io.swagger.client.model.*;
import java.util.*;
import io.swagger.client.model.Pet; import io.swagger.client.model.Pet;
import java.io.File; import java.io.File;
import java.io.File; import java.util.*;
import java.util.Map;
import java.util.HashMap;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-16T10:40:45.419+08:00")
public class PetApi { public class PetApi {
private ApiClient apiClient; private ApiClient apiClient;
@ -243,7 +237,7 @@ public class PetApi {
}; };
final String contentType = apiClient.selectHeaderContentType(contentTypes); final String contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth", "api_key" }; String[] authNames = new String[] { "api_key" };
TypeRef returnType = new TypeRef<Pet>() {}; TypeRef returnType = new TypeRef<Pet>() {};

View File

@ -6,18 +6,12 @@ import io.swagger.client.Configuration;
import io.swagger.client.Pair; import io.swagger.client.Pair;
import io.swagger.client.TypeRef; import io.swagger.client.TypeRef;
import io.swagger.client.model.*;
import java.util.*;
import java.util.Map; import java.util.Map;
import io.swagger.client.model.Order; import io.swagger.client.model.Order;
import java.io.File; import java.util.*;
import java.util.Map;
import java.util.HashMap;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00")
public class StoreApi { public class StoreApi {
private ApiClient apiClient; private ApiClient apiClient;

View File

@ -6,18 +6,12 @@ import io.swagger.client.Configuration;
import io.swagger.client.Pair; import io.swagger.client.Pair;
import io.swagger.client.TypeRef; import io.swagger.client.TypeRef;
import io.swagger.client.model.*;
import java.util.*;
import io.swagger.client.model.User; import io.swagger.client.model.User;
import java.util.*; import java.util.*;
import java.io.File; import java.util.*;
import java.util.Map;
import java.util.HashMap;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00")
public class UserApi { public class UserApi {
private ApiClient apiClient; private ApiClient apiClient;

View File

@ -10,7 +10,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
@ApiModel(description = "") @ApiModel(description = "")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00")
public class Order { public class Order {
private Long id = null; private Long id = null;
@ -19,7 +19,9 @@ public class Order {
private Date shipDate = null; private Date shipDate = null;
public enum StatusEnum { public enum StatusEnum {
PLACED("placed"), APPROVED("approved"), DELIVERED("delivered"); PLACED("placed"),
APPROVED("approved"),
DELIVERED("delivered");
private String value; private String value;

View File

@ -12,7 +12,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
@ApiModel(description = "") @ApiModel(description = "")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00")
public class Pet { public class Pet {
private Long id = null; private Long id = null;
@ -22,7 +22,9 @@ public class Pet {
private List<Tag> tags = new ArrayList<Tag>(); private List<Tag> tags = new ArrayList<Tag>();
public enum StatusEnum { public enum StatusEnum {
AVAILABLE("available"), PENDING("pending"), SOLD("sold"); AVAILABLE("available"),
PENDING("pending"),
SOLD("sold");
private String value; private String value;

View File

@ -1,11 +1,89 @@
apply plugin: 'java' group = 'io.swagger'
apply plugin: 'maven' version = '1.0.0'
sourceCompatibility = JavaVersion.VERSION_1_7 buildscript {
targetCompatibility = JavaVersion.VERSION_1_7 repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
repositories { repositories {
mavenCentral() jcenter()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
install {
repositories.mavenInstaller {
pom.artifactId = 'swagger-petstore-okhttp-gson'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
} }
dependencies { dependencies {
@ -15,17 +93,3 @@ dependencies {
compile 'com.brsanthu:migbase64:2.2' compile 'com.brsanthu:migbase64:2.2'
testCompile 'junit:junit:4.8.1' testCompile 'junit:junit:4.8.1'
} }
group = 'io.swagger'
version = '1.0.0'
install {
repositories.mavenInstaller {
pom.artifactId = 'swagger-petstore-okhttp-gson'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}

View File

@ -0,0 +1,2 @@
# Uncomment to build for Android
#target = android

View File

@ -0,0 +1 @@
rootProject.name = "swagger-petstore-okhttp-gson"

View File

@ -6,22 +6,15 @@ import io.swagger.client.ApiException;
import io.swagger.client.Configuration; import io.swagger.client.Configuration;
import io.swagger.client.Pair; import io.swagger.client.Pair;
import io.swagger.client.model.*;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Call; import com.squareup.okhttp.Call;
import java.lang.reflect.Type;
import java.util.*;
import io.swagger.client.model.Pet; import io.swagger.client.model.Pet;
import java.io.File; import java.io.File;
import java.io.File; import java.lang.reflect.Type;
import java.util.Map; import java.util.*;
import java.util.HashMap;
public class PetApi { public class PetApi {
private ApiClient apiClient; private ApiClient apiClient;
@ -297,7 +290,7 @@ public class PetApi {
final String contentType = apiClient.selectHeaderContentType(contentTypes); final String contentType = apiClient.selectHeaderContentType(contentTypes);
headerParams.put("Content-Type", contentType); headerParams.put("Content-Type", contentType);
String[] authNames = new String[] { "petstore_auth", "api_key" }; String[] authNames = new String[] { "api_key" };
return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames);
} }

View File

@ -6,22 +6,15 @@ import io.swagger.client.ApiException;
import io.swagger.client.Configuration; import io.swagger.client.Configuration;
import io.swagger.client.Pair; import io.swagger.client.Pair;
import io.swagger.client.model.*;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Call; import com.squareup.okhttp.Call;
import java.lang.reflect.Type;
import java.util.*;
import java.util.Map; import java.util.Map;
import io.swagger.client.model.Order; import io.swagger.client.model.Order;
import java.io.File; import java.lang.reflect.Type;
import java.util.Map; import java.util.*;
import java.util.HashMap;
public class StoreApi { public class StoreApi {
private ApiClient apiClient; private ApiClient apiClient;

View File

@ -6,22 +6,15 @@ import io.swagger.client.ApiException;
import io.swagger.client.Configuration; import io.swagger.client.Configuration;
import io.swagger.client.Pair; import io.swagger.client.Pair;
import io.swagger.client.model.*;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Call; import com.squareup.okhttp.Call;
import java.lang.reflect.Type;
import java.util.*;
import io.swagger.client.model.User; import io.swagger.client.model.User;
import java.util.*; import java.util.*;
import java.io.File; import java.lang.reflect.Type;
import java.util.Map; import java.util.*;
import java.util.HashMap;
public class UserApi { public class UserApi {
private ApiClient apiClient; private ApiClient apiClient;

View File

@ -0,0 +1,103 @@
group = 'io.swagger'
version = '1.0.0'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
repositories {
jcenter()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven'
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
install {
repositories.mavenInstaller {
pom.artifactId = 'swagger-petstore-retrofit'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
okhttp_version = "2.3.0"
oltu_version = "1.0.0"
retrofit_version = "1.9.0"
swagger_annotations_version = "1.5.0"
junit_version = "4.12"
}
dependencies {
compile "com.squareup.okhttp:okhttp:$okhttp_version"
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"
testCompile "junit:junit:$junit_version"
}

View File

@ -0,0 +1,2 @@
# Uncomment to build for Android
#target = android

View File

@ -0,0 +1 @@
rootProject.name = "swagger-petstore-retrofit"

View File

@ -0,0 +1,95 @@
package io.swagger.client;
import java.util.Arrays;
import java.util.List;
public class CollectionFormats {
public static class CSVParams {
protected List<String> params;
public CSVParams() {
}
public CSVParams(List<String> params) {
this.params = params;
}
public CSVParams(String... params) {
this.params = Arrays.asList(params);
}
public List<String> getParams() {
return params;
}
public void setParams(List<String> params) {
this.params = params;
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), ",");
}
}
public static class SSVParams extends CSVParams {
public SSVParams() {
}
public SSVParams(List<String> params) {
super(params);
}
public SSVParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), " ");
}
}
public static class TSVParams extends CSVParams {
public TSVParams() {
}
public TSVParams(List<String> params) {
super(params);
}
public TSVParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join( params.toArray(new String[0]), "\t");
}
}
public static class PIPESParams extends CSVParams {
public PIPESParams() {
}
public PIPESParams(List<String> params) {
super(params);
}
public PIPESParams(String... params) {
super(params);
}
@Override
public String toString() {
return StringUtil.join(params.toArray(new String[0]), "|");
}
}
}

View File

@ -1,6 +1,6 @@
package io.swagger.client; package io.swagger.client;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-18T14:07:38.326+02:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-11T00:10:38.251+02:00")
public class StringUtil { public class StringUtil {
/** /**
* Check if the given array contains the given value (with case-insensitive comparison). * Check if the given array contains the given value (with case-insensitive comparison).

View File

@ -1,15 +1,16 @@
package io.swagger.client.api; package io.swagger.client.api;
import io.swagger.client.model.*; import io.swagger.client.CollectionFormats.*;
import retrofit.Callback; import retrofit.Callback;
import retrofit.http.*; import retrofit.http.*;
import retrofit.mime.*; import retrofit.mime.*;
import java.util.*;
import io.swagger.client.model.Pet; import io.swagger.client.model.Pet;
import java.io.File; import java.io.File;
import java.util.*;
public interface PetApi { public interface PetApi {
/** /**
@ -20,7 +21,7 @@ public interface PetApi {
* @return Void * @return Void
*/ */
@PUT("/pet") @PUT("/pet")
Void updatePet( Void updatePet(
@Body Pet body @Body Pet body
); );
@ -29,14 +30,14 @@ public interface PetApi {
* Update an existing pet * Update an existing pet
* Async method * Async method
* @param body Pet object that needs to be added to the store * @param body Pet object that needs to be added to the store
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@PUT("/pet") @PUT("/pet")
void updatePet( void updatePet(
@Body Pet body, Callback<Void> cb @Body Pet body, Callback<Void> cb
); );
/** /**
* Add a new pet to the store * Add a new pet to the store
@ -46,7 +47,7 @@ public interface PetApi {
* @return Void * @return Void
*/ */
@POST("/pet") @POST("/pet")
Void addPet( Void addPet(
@Body Pet body @Body Pet body
); );
@ -55,14 +56,14 @@ public interface PetApi {
* Add a new pet to the store * Add a new pet to the store
* Async method * Async method
* @param body Pet object that needs to be added to the store * @param body Pet object that needs to be added to the store
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@POST("/pet") @POST("/pet")
void addPet( void addPet(
@Body Pet body, Callback<Void> cb @Body Pet body, Callback<Void> cb
); );
/** /**
* Finds Pets by status * Finds Pets by status
@ -72,7 +73,7 @@ public interface PetApi {
* @return List<Pet> * @return List<Pet>
*/ */
@GET("/pet/findByStatus") @GET("/pet/findByStatus")
List<Pet> findPetsByStatus( List<Pet> findPetsByStatus(
@Query("status") List<String> status @Query("status") List<String> status
); );
@ -81,14 +82,14 @@ public interface PetApi {
* Finds Pets by status * Finds Pets by status
* Async method * Async method
* @param status Status values that need to be considered for filter * @param status Status values that need to be considered for filter
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@GET("/pet/findByStatus") @GET("/pet/findByStatus")
void findPetsByStatus( void findPetsByStatus(
@Query("status") List<String> status, Callback<List<Pet>> cb @Query("status") List<String> status, Callback<List<Pet>> cb
); );
/** /**
* Finds Pets by tags * Finds Pets by tags
@ -98,7 +99,7 @@ public interface PetApi {
* @return List<Pet> * @return List<Pet>
*/ */
@GET("/pet/findByTags") @GET("/pet/findByTags")
List<Pet> findPetsByTags( List<Pet> findPetsByTags(
@Query("tags") List<String> tags @Query("tags") List<String> tags
); );
@ -107,14 +108,14 @@ public interface PetApi {
* Finds Pets by tags * Finds Pets by tags
* Async method * Async method
* @param tags Tags to filter by * @param tags Tags to filter by
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@GET("/pet/findByTags") @GET("/pet/findByTags")
void findPetsByTags( void findPetsByTags(
@Query("tags") List<String> tags, Callback<List<Pet>> cb @Query("tags") List<String> tags, Callback<List<Pet>> cb
); );
/** /**
* Find pet by ID * Find pet by ID
@ -124,7 +125,7 @@ public interface PetApi {
* @return Pet * @return Pet
*/ */
@GET("/pet/{petId}") @GET("/pet/{petId}")
Pet getPetById( Pet getPetById(
@Path("petId") Long petId @Path("petId") Long petId
); );
@ -133,14 +134,14 @@ public interface PetApi {
* Find pet by ID * Find pet by ID
* Async method * Async method
* @param petId ID of pet that needs to be fetched * @param petId ID of pet that needs to be fetched
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@GET("/pet/{petId}") @GET("/pet/{petId}")
void getPetById( void getPetById(
@Path("petId") Long petId, Callback<Pet> cb @Path("petId") Long petId, Callback<Pet> cb
); );
/** /**
* Updates a pet in the store with form data * Updates a pet in the store with form data
@ -153,7 +154,7 @@ public interface PetApi {
*/ */
@FormUrlEncoded @FormUrlEncoded
@POST("/pet/{petId}") @POST("/pet/{petId}")
Void updatePetWithForm( Void updatePetWithForm(
@Path("petId") String petId, @Field("name") String name, @Field("status") String status @Path("petId") String petId, @Field("name") String name, @Field("status") String status
); );
@ -164,15 +165,15 @@ public interface PetApi {
* @param petId ID of pet that needs to be updated * @param petId ID of pet that needs to be updated
* @param name Updated name of the pet * @param name Updated name of the pet
* @param status Updated status of the pet * @param status Updated status of the pet
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@FormUrlEncoded @FormUrlEncoded
@POST("/pet/{petId}") @POST("/pet/{petId}")
void updatePetWithForm( void updatePetWithForm(
@Path("petId") String petId, @Field("name") String name, @Field("status") String status, Callback<Void> cb @Path("petId") String petId, @Field("name") String name, @Field("status") String status, Callback<Void> cb
); );
/** /**
* Deletes a pet * Deletes a pet
@ -183,7 +184,7 @@ public interface PetApi {
* @return Void * @return Void
*/ */
@DELETE("/pet/{petId}") @DELETE("/pet/{petId}")
Void deletePet( Void deletePet(
@Path("petId") Long petId, @Header("api_key") String apiKey @Path("petId") Long petId, @Header("api_key") String apiKey
); );
@ -193,14 +194,14 @@ public interface PetApi {
* Async method * Async method
* @param petId Pet id to delete * @param petId Pet id to delete
* @param apiKey * @param apiKey
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@DELETE("/pet/{petId}") @DELETE("/pet/{petId}")
void deletePet( void deletePet(
@Path("petId") Long petId, @Header("api_key") String apiKey, Callback<Void> cb @Path("petId") Long petId, @Header("api_key") String apiKey, Callback<Void> cb
); );
/** /**
* uploads an image * uploads an image
@ -213,7 +214,7 @@ public interface PetApi {
*/ */
@Multipart @Multipart
@POST("/pet/{petId}/uploadImage") @POST("/pet/{petId}/uploadImage")
Void uploadFile( Void uploadFile(
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file
); );
@ -224,14 +225,14 @@ public interface PetApi {
* @param petId ID of pet to update * @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server * @param additionalMetadata Additional data to pass to server
* @param file file to upload * @param file file to upload
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@Multipart @Multipart
@POST("/pet/{petId}/uploadImage") @POST("/pet/{petId}/uploadImage")
void uploadFile( void uploadFile(
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback<Void> cb @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback<Void> cb
); );
} }

View File

@ -1,15 +1,16 @@
package io.swagger.client.api; package io.swagger.client.api;
import io.swagger.client.model.*; import io.swagger.client.CollectionFormats.*;
import retrofit.Callback; import retrofit.Callback;
import retrofit.http.*; import retrofit.http.*;
import retrofit.mime.*; import retrofit.mime.*;
import java.util.*;
import java.util.Map; import java.util.Map;
import io.swagger.client.model.Order; import io.swagger.client.model.Order;
import java.util.*;
public interface StoreApi { public interface StoreApi {
/** /**
@ -19,21 +20,21 @@ public interface StoreApi {
* @return Map<String, Integer> * @return Map<String, Integer>
*/ */
@GET("/store/inventory") @GET("/store/inventory")
Map<String, Integer> getInventory(); Map<String, Integer> getInventory();
/** /**
* Returns pet inventories by status * Returns pet inventories by status
* Async method * Async method
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@GET("/store/inventory") @GET("/store/inventory")
void getInventory( void getInventory(
Callback<Map<String, Integer>> cb Callback<Map<String, Integer>> cb
); );
/** /**
* Place an order for a pet * Place an order for a pet
@ -43,7 +44,7 @@ public interface StoreApi {
* @return Order * @return Order
*/ */
@POST("/store/order") @POST("/store/order")
Order placeOrder( Order placeOrder(
@Body Order body @Body Order body
); );
@ -52,14 +53,14 @@ public interface StoreApi {
* Place an order for a pet * Place an order for a pet
* Async method * Async method
* @param body order placed for purchasing the pet * @param body order placed for purchasing the pet
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@POST("/store/order") @POST("/store/order")
void placeOrder( void placeOrder(
@Body Order body, Callback<Order> cb @Body Order body, Callback<Order> cb
); );
/** /**
* Find purchase order by ID * Find purchase order by ID
@ -69,7 +70,7 @@ public interface StoreApi {
* @return Order * @return Order
*/ */
@GET("/store/order/{orderId}") @GET("/store/order/{orderId}")
Order getOrderById( Order getOrderById(
@Path("orderId") String orderId @Path("orderId") String orderId
); );
@ -78,14 +79,14 @@ public interface StoreApi {
* Find purchase order by ID * Find purchase order by ID
* Async method * Async method
* @param orderId ID of pet that needs to be fetched * @param orderId ID of pet that needs to be fetched
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@GET("/store/order/{orderId}") @GET("/store/order/{orderId}")
void getOrderById( void getOrderById(
@Path("orderId") String orderId, Callback<Order> cb @Path("orderId") String orderId, Callback<Order> cb
); );
/** /**
* Delete purchase order by ID * Delete purchase order by ID
@ -95,7 +96,7 @@ public interface StoreApi {
* @return Void * @return Void
*/ */
@DELETE("/store/order/{orderId}") @DELETE("/store/order/{orderId}")
Void deleteOrder( Void deleteOrder(
@Path("orderId") String orderId @Path("orderId") String orderId
); );
@ -104,13 +105,13 @@ public interface StoreApi {
* Delete purchase order by ID * Delete purchase order by ID
* Async method * Async method
* @param orderId ID of the order that needs to be deleted * @param orderId ID of the order that needs to be deleted
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@DELETE("/store/order/{orderId}") @DELETE("/store/order/{orderId}")
void deleteOrder( void deleteOrder(
@Path("orderId") String orderId, Callback<Void> cb @Path("orderId") String orderId, Callback<Void> cb
); );
} }

View File

@ -1,15 +1,16 @@
package io.swagger.client.api; package io.swagger.client.api;
import io.swagger.client.model.*; import io.swagger.client.CollectionFormats.*;
import retrofit.Callback; import retrofit.Callback;
import retrofit.http.*; import retrofit.http.*;
import retrofit.mime.*; import retrofit.mime.*;
import java.util.*;
import io.swagger.client.model.User; import io.swagger.client.model.User;
import java.util.*; import java.util.*;
import java.util.*;
public interface UserApi { public interface UserApi {
/** /**
@ -20,7 +21,7 @@ public interface UserApi {
* @return Void * @return Void
*/ */
@POST("/user") @POST("/user")
Void createUser( Void createUser(
@Body User body @Body User body
); );
@ -29,14 +30,14 @@ public interface UserApi {
* Create user * Create user
* Async method * Async method
* @param body Created user object * @param body Created user object
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@POST("/user") @POST("/user")
void createUser( void createUser(
@Body User body, Callback<Void> cb @Body User body, Callback<Void> cb
); );
/** /**
* Creates list of users with given input array * Creates list of users with given input array
@ -46,7 +47,7 @@ public interface UserApi {
* @return Void * @return Void
*/ */
@POST("/user/createWithArray") @POST("/user/createWithArray")
Void createUsersWithArrayInput( Void createUsersWithArrayInput(
@Body List<User> body @Body List<User> body
); );
@ -55,14 +56,14 @@ public interface UserApi {
* Creates list of users with given input array * Creates list of users with given input array
* Async method * Async method
* @param body List of user object * @param body List of user object
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@POST("/user/createWithArray") @POST("/user/createWithArray")
void createUsersWithArrayInput( void createUsersWithArrayInput(
@Body List<User> body, Callback<Void> cb @Body List<User> body, Callback<Void> cb
); );
/** /**
* Creates list of users with given input array * Creates list of users with given input array
@ -72,7 +73,7 @@ public interface UserApi {
* @return Void * @return Void
*/ */
@POST("/user/createWithList") @POST("/user/createWithList")
Void createUsersWithListInput( Void createUsersWithListInput(
@Body List<User> body @Body List<User> body
); );
@ -81,14 +82,14 @@ public interface UserApi {
* Creates list of users with given input array * Creates list of users with given input array
* Async method * Async method
* @param body List of user object * @param body List of user object
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@POST("/user/createWithList") @POST("/user/createWithList")
void createUsersWithListInput( void createUsersWithListInput(
@Body List<User> body, Callback<Void> cb @Body List<User> body, Callback<Void> cb
); );
/** /**
* Logs user into the system * Logs user into the system
@ -99,7 +100,7 @@ public interface UserApi {
* @return String * @return String
*/ */
@GET("/user/login") @GET("/user/login")
String loginUser( String loginUser(
@Query("username") String username, @Query("password") String password @Query("username") String username, @Query("password") String password
); );
@ -109,14 +110,14 @@ public interface UserApi {
* Async method * Async method
* @param username The user name for login * @param username The user name for login
* @param password The password for login in clear text * @param password The password for login in clear text
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@GET("/user/login") @GET("/user/login")
void loginUser( void loginUser(
@Query("username") String username, @Query("password") String password, Callback<String> cb @Query("username") String username, @Query("password") String password, Callback<String> cb
); );
/** /**
* Logs out current logged in user session * Logs out current logged in user session
@ -125,21 +126,21 @@ public interface UserApi {
* @return Void * @return Void
*/ */
@GET("/user/logout") @GET("/user/logout")
Void logoutUser(); Void logoutUser();
/** /**
* Logs out current logged in user session * Logs out current logged in user session
* Async method * Async method
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@GET("/user/logout") @GET("/user/logout")
void logoutUser( void logoutUser(
Callback<Void> cb Callback<Void> cb
); );
/** /**
* Get user by user name * Get user by user name
@ -149,7 +150,7 @@ public interface UserApi {
* @return User * @return User
*/ */
@GET("/user/{username}") @GET("/user/{username}")
User getUserByName( User getUserByName(
@Path("username") String username @Path("username") String username
); );
@ -158,14 +159,14 @@ public interface UserApi {
* Get user by user name * Get user by user name
* Async method * Async method
* @param username The name that needs to be fetched. Use user1 for testing. * @param username The name that needs to be fetched. Use user1 for testing.
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@GET("/user/{username}") @GET("/user/{username}")
void getUserByName( void getUserByName(
@Path("username") String username, Callback<User> cb @Path("username") String username, Callback<User> cb
); );
/** /**
* Updated user * Updated user
@ -176,7 +177,7 @@ public interface UserApi {
* @return Void * @return Void
*/ */
@PUT("/user/{username}") @PUT("/user/{username}")
Void updateUser( Void updateUser(
@Path("username") String username, @Body User body @Path("username") String username, @Body User body
); );
@ -186,14 +187,14 @@ public interface UserApi {
* Async method * Async method
* @param username name that need to be deleted * @param username name that need to be deleted
* @param body Updated user object * @param body Updated user object
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@PUT("/user/{username}") @PUT("/user/{username}")
void updateUser( void updateUser(
@Path("username") String username, @Body User body, Callback<Void> cb @Path("username") String username, @Body User body, Callback<Void> cb
); );
/** /**
* Delete user * Delete user
@ -203,7 +204,7 @@ public interface UserApi {
* @return Void * @return Void
*/ */
@DELETE("/user/{username}") @DELETE("/user/{username}")
Void deleteUser( Void deleteUser(
@Path("username") String username @Path("username") String username
); );
@ -212,13 +213,13 @@ public interface UserApi {
* Delete user * Delete user
* Async method * Async method
* @param username The name that needs to be deleted * @param username The name that needs to be deleted
* @param cb callback method * @param cb callback method
* @return void * @return void
*/ */
@DELETE("/user/{username}") @DELETE("/user/{username}")
void deleteUser( void deleteUser(
@Path("username") String username, Callback<Void> cb @Path("username") String username, Callback<Void> cb
); );
} }

View File

@ -237,7 +237,7 @@ module Petstore
post_body = nil post_body = nil
auth_names = ['petstore_auth', 'api_key'] auth_names = ['api_key']
result = @api_client.call_api(:GET, path, result = @api_client.call_api(:GET, path,
:header_params => header_params, :header_params => header_params,
:query_params => query_params, :query_params => query_params,

View File

@ -138,7 +138,7 @@ module Petstore
end end
def base_url def base_url
url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}" url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '')
URI.encode(url) URI.encode(url)
end end

View File

@ -0,0 +1,25 @@
require 'spec_helper'
describe Petstore::Configuration do
let(:config) { Petstore::Configuration.instance }
before(:each) do
Petstore.configure do |c|
c.host = 'petstore.swagger.io'
c.base_path = 'v2'
end
end
describe '#base_url' do
it 'should have the default value' do
config.base_url.should == 'http://petstore.swagger.io/v2'
end
it 'should remove trailing slashes' do
[nil, '', '/', '//'].each do |base_path|
config.base_path = base_path
config.base_url.should == 'http://petstore.swagger.io'
end
end
end
end