Merge branch 'master' into vagrant_new

This commit is contained in:
GU Yu (Byron) 2016-01-22 16:12:06 +08:00
commit 66799bc695
175 changed files with 5557 additions and 2666 deletions

6
.gitignore vendored
View File

@ -48,6 +48,7 @@ atlassian-ide-plugin.xml
packages/ packages/
.pub .pub
.packages .packages
.vagrant/
samples/client/petstore/php/SwaggerClient-php/composer.lock samples/client/petstore/php/SwaggerClient-php/composer.lock
samples/client/petstore/php/SwaggerClient-php/vendor/ samples/client/petstore/php/SwaggerClient-php/vendor/
@ -59,6 +60,7 @@ samples/client/petstore/perl/deep_module_test/
samples/client/petstore/python/.projectile samples/client/petstore/python/.projectile
samples/client/petstore/python/.venv/ samples/client/petstore/python/.venv/
samples/client/petstore/python/dev-requirements.txt.log
.settings .settings
@ -67,4 +69,6 @@ samples/client/petstore/python/.venv/
*.pm~ *.pm~
*.xml~ *.xml~
*.t~ *.t~
.vagrant/
samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/
samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/

View File

@ -31,6 +31,7 @@ For a list of variables available in the template, please refer to this [page](h
Code change should conform to the programming style guide of the respective langauages: Code change should conform to the programming style guide of the respective langauages:
- C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx
- Java: https://google.github.io/styleguide/javaguide.html - Java: https://google.github.io/styleguide/javaguide.html
- JavaScript - https://github.com/airbnb/javascript
- ObjC: https://github.com/NYTimes/objective-c-style-guide - ObjC: https://github.com/NYTimes/objective-c-style-guide
- PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md - PHP: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
- Python: https://www.python.org/dev/peps/pep-0008/ - Python: https://www.python.org/dev/peps/pep-0008/

View File

@ -237,16 +237,15 @@ This will write, in the folder `output/myLibrary`, all the files you need to get
You would then compile your library in the `output/myLibrary` folder with `mvn package` and execute the codegen like such: You would then compile your library in the `output/myLibrary` folder with `mvn package` and execute the codegen like such:
``` ```
java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar:modules/swagger-codegen-cli/target/swagger-codegen-cli.jar io.swagger.codegen.Codegen java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar:modules/swagger-codegen-cli/target/swagger-codegen-cli.jar io.swagger.codegen.SwaggerCodegen
``` ```
Note the `myClientCodegen` is an option now, and you can use the usual arguments for generating your library: Note the `myClientCodegen` is an option now, and you can use the usual arguments for generating your library:
``` ```
java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar:modules/swagger-codegen-cli/target/swagger-codegen-cli.jar \ java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar:modules/swagger-codegen-cli/target/swagger-codegen-cli.jar \
io.swagger.codegen.Codegen generate -l myClientCodegen\ io.swagger.codegen.SwaggerCodegen generate -l myClientCodegen\
-i http://petstore.swagger.io/v2/swagger.json \ -i http://petstore.swagger.io/v2/swagger.json \
-o myClient -o myClient
``` ```

View File

@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead. # if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/silex -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l silex -o samples/server/petstore/silex" ags="$@ generate -t modules/swagger-codegen/src/main/resources/silex -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l silex-PHP -o samples/server/petstore/silex"
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

0
bin/slim-petstore-server.sh Normal file → Executable file
View File

View File

@ -19,10 +19,14 @@ public interface CodegenConfig {
Map<String, Object> additionalProperties(); Map<String, Object> additionalProperties();
String testPackage();
String apiPackage(); String apiPackage();
String apiFileFolder(); String apiFileFolder();
String apiTestFileFolder();
String fileSuffix(); String fileSuffix();
String outputFolder(); String outputFolder();
@ -33,6 +37,8 @@ public interface CodegenConfig {
String modelFileFolder(); String modelFileFolder();
String modelTestFileFolder();
String modelPackage(); String modelPackage();
String toApiName(String name); String toApiName(String name);
@ -87,6 +93,10 @@ public interface CodegenConfig {
Map<String, String> modelTemplateFiles(); Map<String, String> modelTemplateFiles();
Map<String, String> apiTestTemplateFiles();
Map<String, String> modelTestTemplateFiles();
Set<String> languageSpecificPrimitives(); Set<String> languageSpecificPrimitives();
void preprocessSwagger(Swagger swagger); void preprocessSwagger(Swagger swagger);
@ -97,6 +107,10 @@ public interface CodegenConfig {
String toModelFilename(String name); String toModelFilename(String name);
String toApiTestFilename(String name);
String toModelTestFilename(String name);
String toModelImport(String name); String toModelImport(String name);
String toApiImport(String name); String toApiImport(String name);
@ -115,6 +129,8 @@ public interface CodegenConfig {
String apiFilename(String templateName, String tag); String apiFilename(String templateName, String tag);
String apiTestFilename(String templateName, String tag);
boolean shouldOverwrite(String filename); boolean shouldOverwrite(String filename);
boolean isSkipOverwrite(); boolean isSkipOverwrite();

View File

@ -63,8 +63,11 @@ public class DefaultCodegen {
protected Set<String> languageSpecificPrimitives = new HashSet<String>(); protected Set<String> languageSpecificPrimitives = new HashSet<String>();
protected Map<String, String> importMapping = new HashMap<String, String>(); protected Map<String, String> importMapping = new HashMap<String, String>();
protected String modelPackage = "", apiPackage = "", fileSuffix; protected String modelPackage = "", apiPackage = "", fileSuffix;
protected String testPackage = "";
protected Map<String, String> apiTemplateFiles = new HashMap<String, String>(); protected Map<String, String> apiTemplateFiles = new HashMap<String, String>();
protected Map<String, String> modelTemplateFiles = new HashMap<String, String>(); protected Map<String, String> modelTemplateFiles = new HashMap<String, String>();
protected Map<String, String> apiTestTemplateFiles = new HashMap<String, String>();
protected Map<String, String> modelTestTemplateFiles = new HashMap<String, String>();
protected String templateDir; protected String templateDir;
protected String embeddedTemplateDir; protected String embeddedTemplateDir;
protected Map<String, Object> additionalProperties = new HashMap<String, Object>(); protected Map<String, Object> additionalProperties = new HashMap<String, Object>();
@ -170,6 +173,10 @@ public class DefaultCodegen {
return importMapping; return importMapping;
} }
public String testPackage() {
return testPackage;
}
public String modelPackage() { public String modelPackage() {
return modelPackage; return modelPackage;
} }
@ -194,6 +201,14 @@ public class DefaultCodegen {
} }
} }
public Map<String, String> apiTestTemplateFiles() {
return apiTestTemplateFiles;
}
public Map<String, String> modelTestTemplateFiles() {
return modelTestTemplateFiles;
}
public Map<String, String> apiTemplateFiles() { public Map<String, String> apiTemplateFiles() {
return apiTemplateFiles; return apiTemplateFiles;
} }
@ -210,6 +225,14 @@ public class DefaultCodegen {
return outputFolder + "/" + modelPackage().replace('.', '/'); return outputFolder + "/" + modelPackage().replace('.', '/');
} }
public String apiTestFileFolder() {
return outputFolder + "/" + testPackage().replace('.', '/');
}
public String modelTestFileFolder() {
return outputFolder + "/" + testPackage().replace('.', '/');
}
public Map<String, Object> additionalProperties() { public Map<String, Object> additionalProperties() {
return additionalProperties; return additionalProperties;
} }
@ -260,6 +283,16 @@ public class DefaultCodegen {
return toApiName(name); return toApiName(name);
} }
/**
* Return the file name of the Api Test
*
* @param name the file name of the Api
* @return the file name of the Api
*/
public String toApiTestFilename(String name) {
return toApiName(name) + "Test";
}
/** /**
* Return the variable name in the Api * Return the variable name in the Api
* *
@ -280,6 +313,16 @@ public class DefaultCodegen {
return initialCaps(name); return initialCaps(name);
} }
/**
* Return the capitalized file name of the model test
*
* @param name the model name
* @return the file name of the model
*/
public String toModelTestFilename(String name) {
return initialCaps(name) + "Test";
}
/** /**
* Return the operation ID (method name) * Return the operation ID (method name)
* *
@ -2028,6 +2071,19 @@ public class DefaultCodegen {
return apiFileFolder() + '/' + toApiFilename(tag) + suffix; return apiFileFolder() + '/' + toApiFilename(tag) + suffix;
} }
/**
* Return the full path and API test file
*
* @param templateName template name
* @param tag tag
*
* @return the API test file name with full path
*/
public String apiTestFilename(String templateName, String tag) {
String suffix = apiTestTemplateFiles().get(templateName);
return apiTestFileFolder() + '/' + toApiTestFilename(tag) + suffix;
}
public boolean shouldOverwrite(String filename) { public boolean shouldOverwrite(String filename) {
return !(skipOverwrite && new File(filename).exists()); return !(skipOverwrite && new File(filename).exists());
} }

View File

@ -211,6 +211,28 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
writeToFile(filename, tmpl.execute(models)); writeToFile(filename, tmpl.execute(models));
files.add(new File(filename)); files.add(new File(filename));
} }
// to generate model test files
for (String templateName : config.modelTestTemplateFiles().keySet()) {
String suffix = config.modelTestTemplateFiles().get(templateName);
String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix;
if (!config.shouldOverwrite(filename)) {
continue;
}
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(filename, tmpl.execute(models));
files.add(new File(filename));
}
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Could not generate model '" + name + "'", e); throw new RuntimeException("Could not generate model '" + name + "'", e);
} }
@ -288,6 +310,30 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
writeToFile(filename, tmpl.execute(operation)); writeToFile(filename, tmpl.execute(operation));
files.add(new File(filename)); files.add(new File(filename));
} }
// to generate api test files
for (String templateName : config.apiTestTemplateFiles().keySet()) {
String filename = config.apiTestFilename(templateName, tag);
if (!config.shouldOverwrite(filename) && new File(filename).exists()) {
continue;
}
String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler()
.withLoader(new Mustache.TemplateLoader() {
@Override
public Reader getTemplate(String name) {
return getTemplateReader(getFullTemplateFile(config, name + ".mustache"));
}
})
.defaultValue("")
.compile(template);
writeToFile(filename, tmpl.execute(operation));
files.add(new File(filename));
}
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Could not generate api file for '" + tag + "'", e); throw new RuntimeException("Could not generate api file for '" + tag + "'", e);
} }

View File

@ -52,7 +52,9 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp
typeMapping.put("integer", "number"); typeMapping.put("integer", "number");
typeMapping.put("Map", "any"); typeMapping.put("Map", "any");
typeMapping.put("DateTime", "Date"); typeMapping.put("DateTime", "Date");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "string");
} }
@Override @Override

View File

@ -76,6 +76,9 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("Date", "DateTime"); typeMapping.put("Date", "DateTime");
typeMapping.put("date", "DateTime"); typeMapping.put("date", "DateTime");
typeMapping.put("File", "MultipartFile"); typeMapping.put("File", "MultipartFile");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "String");
cliOptions.add(new CliOption(BROWSER_CLIENT, "Is the client browser based")); cliOptions.add(new CliOption(BROWSER_CLIENT, "Is the client browser based"));
cliOptions.add(new CliOption(PUB_NAME, "Name in generated pubspec")); cliOptions.add(new CliOption(PUB_NAME, "Name in generated pubspec"));

View File

@ -63,6 +63,9 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig
typeMapping.put("DateTime", "Date"); typeMapping.put("DateTime", "Date");
typeMapping.put("object", "Object"); typeMapping.put("object", "Object");
typeMapping.put("file", "File"); typeMapping.put("file", "File");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "String");
importMapping = new HashMap<String, String>(); importMapping = new HashMap<String, String>();
importMapping.put("File", "flash.filesystem.File"); importMapping.put("File", "flash.filesystem.File");

View File

@ -35,6 +35,7 @@ public class JavaInflectorServerCodegen extends JavaClientCodegen implements Cod
languageSpecificPrimitives = new HashSet<String>( languageSpecificPrimitives = new HashSet<String>(
Arrays.asList( Arrays.asList(
"byte[]",
"String", "String",
"boolean", "boolean",
"Boolean", "Boolean",

View File

@ -133,6 +133,8 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
typeMapping.put("double", "Number"); typeMapping.put("double", "Number");
typeMapping.put("number", "Number"); typeMapping.put("number", "Number");
typeMapping.put("DateTime", "Date"); typeMapping.put("DateTime", "Date");
// binary not supported in JavaScript client right now, using String as a workaround
typeMapping.put("binary", "String");
importMapping.clear(); importMapping.clear();
} }
@ -205,6 +207,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js")); supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", sourceFolder, "ApiClient.js"));
} }
@Override @Override

View File

@ -72,6 +72,9 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("array", "ARRAY"); typeMapping.put("array", "ARRAY");
typeMapping.put("map", "HASH"); typeMapping.put("map", "HASH");
typeMapping.put("object", "object"); typeMapping.put("object", "object");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "string");
cliOptions.clear(); cliOptions.clear();
cliOptions.add(new CliOption(MODULE_NAME, "Perl module name (convention: CamelCase or Long::Module).").defaultValue("SwaggerClient")); cliOptions.add(new CliOption(MODULE_NAME, "Perl module name (convention: CamelCase or Long::Module).").defaultValue("SwaggerClient"));

View File

@ -41,9 +41,12 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
outputFolder = "generated-code" + File.separator + "php"; outputFolder = "generated-code" + File.separator + "php";
modelTemplateFiles.put("model.mustache", ".php"); modelTemplateFiles.put("model.mustache", ".php");
apiTemplateFiles.put("api.mustache", ".php"); apiTemplateFiles.put("api.mustache", ".php");
modelTestTemplateFiles.put("model_test.mustache", ".php");
apiTestTemplateFiles.put("api_test.mustache", ".php");
embeddedTemplateDir = templateDir = "php"; embeddedTemplateDir = templateDir = "php";
apiPackage = invokerPackage + "\\Api"; apiPackage = invokerPackage + "\\Api";
modelPackage = invokerPackage + "\\Model"; modelPackage = invokerPackage + "\\Model";
testPackage = invokerPackage + "\\Tests";
reservedWords = new HashSet<String>( reservedWords = new HashSet<String>(
Arrays.asList( Arrays.asList(
@ -236,6 +239,16 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
return (outputFolder + "/" + toPackagePath(modelPackage, srcBasePath)); return (outputFolder + "/" + toPackagePath(modelPackage, srcBasePath));
} }
@Override
public String apiTestFileFolder() {
return (outputFolder + "/" + toPackagePath(testPackage, srcBasePath));
}
@Override
public String modelTestFileFolder() {
return (outputFolder + "/" + toPackagePath(testPackage, srcBasePath));
}
@Override @Override
public String getTypeDeclaration(Property p) { public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) { if (p instanceof ArrayProperty) {
@ -364,6 +377,12 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
return toModelName(name); return toModelName(name);
} }
@Override
public String toModelTestFilename(String name) {
// should be the same as the model name
return toModelName(name) + "Test";
}
@Override @Override
public String toOperationId(String operationId) { public String toOperationId(String operationId) {
// throw exception if method name is empty // throw exception if method name is empty

View File

@ -51,6 +51,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig
typeMapping.put("DateTime", "datetime"); typeMapping.put("DateTime", "datetime");
typeMapping.put("object", "object"); typeMapping.put("object", "object");
typeMapping.put("file", "file"); typeMapping.put("file", "file");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "str");
// from https://docs.python.org/release/2.5.4/ref/keywords.html // from https://docs.python.org/release/2.5.4/ref/keywords.html
reservedWords = new HashSet<String>( reservedWords = new HashSet<String>(

View File

@ -121,6 +121,9 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig {
typeMapping.put("map", "QMap"); typeMapping.put("map", "QMap");
typeMapping.put("file", "SWGHttpRequestInputFileElement"); typeMapping.put("file", "SWGHttpRequestInputFileElement");
typeMapping.put("object", PREFIX + "Object"); typeMapping.put("object", PREFIX + "Object");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "QString");
importMapping = new HashMap<String, String>(); importMapping = new HashMap<String, String>();

View File

@ -96,6 +96,9 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig
typeMapping.put("double", "Double"); typeMapping.put("double", "Double");
typeMapping.put("object", "Any"); typeMapping.put("object", "Any");
typeMapping.put("file", "File"); typeMapping.put("file", "File");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "String");
languageSpecificPrimitives = new HashSet<String>( languageSpecificPrimitives = new HashSet<String>(
Arrays.asList( Arrays.asList(

View File

@ -67,6 +67,9 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
typeMapping.put("integer", "Int"); typeMapping.put("integer", "Int");
typeMapping.put("long", "Long"); typeMapping.put("long", "Long");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "String");
additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appName", "Swagger Sample");
additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appName", "Swagger Sample");

View File

@ -81,6 +81,9 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig
typeMapping.put("array", "array"); typeMapping.put("array", "array");
typeMapping.put("list", "array"); typeMapping.put("list", "array");
typeMapping.put("object", "object"); typeMapping.put("object", "object");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "string");
supportingFiles.add(new SupportingFile("README.mustache", packagePath.replace('/', File.separatorChar), "README.md")); supportingFiles.add(new SupportingFile("README.mustache", packagePath.replace('/', File.separatorChar), "README.md"));
supportingFiles.add(new SupportingFile("composer.json", packagePath.replace('/', File.separatorChar), "composer.json")); supportingFiles.add(new SupportingFile("composer.json", packagePath.replace('/', File.separatorChar), "composer.json"));

View File

@ -60,6 +60,9 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi
typeMapping.put("String", "string"); typeMapping.put("String", "string");
typeMapping.put("List", "array"); typeMapping.put("List", "array");
typeMapping.put("map", "map"); typeMapping.put("map", "map");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "string");
// remove modelPackage and apiPackage added by default // remove modelPackage and apiPackage added by default
cliOptions.clear(); cliOptions.clear();

View File

@ -83,6 +83,9 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege
typeMapping.put("array", "array"); typeMapping.put("array", "array");
typeMapping.put("list", "array"); typeMapping.put("list", "array");
typeMapping.put("object", "object"); typeMapping.put("object", "object");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "string");
supportingFiles.add(new SupportingFile("README.mustache", packagePath.replace('/', File.separatorChar), "README.md")); supportingFiles.add(new SupportingFile("README.mustache", packagePath.replace('/', File.separatorChar), "README.md"));
supportingFiles.add(new SupportingFile("composer.json", packagePath.replace('/', File.separatorChar), "composer.json")); supportingFiles.add(new SupportingFile("composer.json", packagePath.replace('/', File.separatorChar), "composer.json"));

View File

@ -34,6 +34,7 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen
languageSpecificPrimitives = new HashSet<String>( languageSpecificPrimitives = new HashSet<String>(
Arrays.asList( Arrays.asList(
"byte[]",
"String", "String",
"boolean", "boolean",
"Boolean", "Boolean",

View File

@ -120,6 +120,9 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("double", "Double"); typeMapping.put("double", "Double");
typeMapping.put("object", "String"); typeMapping.put("object", "String");
typeMapping.put("file", "NSURL"); typeMapping.put("file", "NSURL");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "String");
importMapping = new HashMap<String, String>(); importMapping = new HashMap<String, String>();

View File

@ -76,6 +76,9 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
typeMapping.put("map", "HashMap"); typeMapping.put("map", "HashMap");
typeMapping.put("number", "Long"); typeMapping.put("number", "Long");
typeMapping.put("object", PREFIX + "Object"); typeMapping.put("object", PREFIX + "Object");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "String");
importMapping = new HashMap<String, String>(); importMapping = new HashMap<String, String>();

View File

@ -452,34 +452,51 @@ public class ApiClient {
} }
} }
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException { /**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param path The sub path
* @param queryParams The query parameters
* @return The full URL
*/
private String buildUrl(String path, List<Pair> queryParams) {
final StringBuilder url = new StringBuilder();
url.append(basePath).append(path);
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return url.toString();
}
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
if (body != null && !formParams.isEmpty()) { if (body != null && !formParams.isEmpty()) {
throw new ApiException(500, "Cannot have body and form params"); throw new ApiException(500, "Cannot have body and form params");
} }
updateParamsForAuth(authNames, queryParams, headerParams); updateParamsForAuth(authNames, queryParams, headerParams);
StringBuilder b = new StringBuilder(); final String url = buildUrl(path, queryParams);
b.append("?");
if (queryParams != null){
for (Pair queryParam : queryParams){
if (!queryParam.getName().isEmpty()) {
b.append(escapeString(queryParam.getName()));
b.append("=");
b.append(escapeString(queryParam.getValue()));
b.append("&");
}
}
}
String querystring = b.substring(0, b.length() - 1);
Builder builder; Builder builder;
if (accept == null) if (accept == null) {
builder = httpClient.resource(basePath + path + querystring).getRequestBuilder(); builder = httpClient.resource(url).getRequestBuilder();
else } else {
builder = httpClient.resource(basePath + path + querystring).accept(accept); builder = httpClient.resource(url).accept(accept);
}
for (String key : headerParams.keySet()) { for (String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key)); builder = builder.header(key, headerParams.get(key));

View File

@ -495,7 +495,9 @@ public class ApiClient {
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException { public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams); updateParamsForAuth(authNames, queryParams, headerParams);
WebTarget target = httpClient.target(this.basePath).path(path); // Not using `.target(this.basePath).path(path)` below,
// to support (constant) query string in `path`, e.g. "/posts?draft=1"
WebTarget target = httpClient.target(this.basePath + path);
if (queryParams != null) { if (queryParams != null) {
for (Pair queryParam : queryParams) { for (Pair queryParam : queryParams) {

View File

@ -657,8 +657,8 @@ public class ApiClient {
} }
/** /**
* Deserialize response body to Java object, according to the Content-Type * Deserialize response body to Java object, according to the return type and
* response header. * the Content-Type response header.
* *
* @param response HTTP response * @param response HTTP response
* @param returnType The type of the Java object * @param returnType The type of the Java object
@ -667,12 +667,21 @@ public class ApiClient {
* or the Content-Type of the response is not supported. * or the Content-Type of the response is not supported.
*/ */
public <T> T deserialize(Response response, Type returnType) throws ApiException { public <T> T deserialize(Response response, Type returnType) throws ApiException {
if (response == null || returnType == null) if (response == null || returnType == null) {
return null; return null;
}
if ("byte[]".equals(returnType.toString())) {
// Handle binary response (byte array).
try {
return (T) response.body().bytes();
} catch (IOException e) {
throw new ApiException(e);
}
} else if (returnType.equals(File.class)) {
// Handle file downloading. // Handle file downloading.
if (returnType.equals(File.class))
return (T) downloadFileFromResponse(response); return (T) downloadFileFromResponse(response);
}
String respBody; String respBody;
try { try {
@ -684,8 +693,9 @@ public class ApiClient {
throw new ApiException(e); throw new ApiException(e);
} }
if (respBody == null || "".equals(respBody)) if (respBody == null || "".equals(respBody)) {
return null; return null;
}
String contentType = response.headers().get("Content-Type"); String contentType = response.headers().get("Content-Type");
if (contentType == null) { if (contentType == null) {
@ -707,20 +717,29 @@ public class ApiClient {
} }
/** /**
* Serialize the given Java object into request body string, according to the * Serialize the given Java object into request body according to the object's
* request Content-Type. * class and the request Content-Type.
* *
* @param obj The Java object * @param obj The Java object
* @param contentType The request Content-Type * @param contentType The request Content-Type
* @return The serialized string * @return The serialized request body
* @throws ApiException If fail to serialize the given object * @throws ApiException If fail to serialize the given object
*/ */
public String serialize(Object obj, String contentType) throws ApiException { public RequestBody serialize(Object obj, String contentType) throws ApiException {
if (isJsonMime(contentType)) { if (obj instanceof byte[]) {
if (obj != null) // Binary (byte array) body parameter support.
return json.serialize(obj); return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
else } else if (obj instanceof File) {
return null; // File body parameter support.
return RequestBody.create(MediaType.parse(contentType), (File) obj);
} else if (isJsonMime(contentType)) {
String content;
if (obj != null) {
content = json.serialize(obj);
} else {
content = null;
}
return RequestBody.create(MediaType.parse(contentType), content);
} else { } else {
throw new ApiException("Content type \"" + contentType + "\" is not supported"); throw new ApiException("Content type \"" + contentType + "\" is not supported");
} }
@ -909,7 +928,7 @@ public class ApiClient {
reqBody = RequestBody.create(MediaType.parse(contentType), ""); reqBody = RequestBody.create(MediaType.parse(contentType), "");
} }
} else { } else {
reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); reqBody = serialize(body, contentType);
} }
Request request = null; Request request = null;
@ -932,20 +951,27 @@ public class ApiClient {
* @return The full URL * @return The full URL
*/ */
public String buildUrl(String path, List<Pair> queryParams) { public String buildUrl(String path, List<Pair> queryParams) {
StringBuilder query = new StringBuilder(); final StringBuilder url = new StringBuilder();
if (queryParams != null) { url.append(basePath).append(path);
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) { for (Pair param : queryParams) {
if (param.getValue() != null) { if (param.getValue() != null) {
if (query.toString().length() == 0) if (prefix != null) {
query.append("?"); url.append(prefix);
else prefix = null;
query.append("&"); } else {
url.append("&");
}
String value = parameterToString(param.getValue()); String value = parameterToString(param.getValue());
query.append(escapeString(param.getName())).append("=").append(escapeString(value)); url.append(escapeString(param.getName())).append("=").append(escapeString(value));
} }
} }
} }
return basePath + path + query.toString();
return url.toString();
} }
/** /**

View File

@ -0,0 +1,151 @@
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['superagent'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('superagent'));
} else {
// Browser globals (root is window)
if (!root.{{moduleName}}) {
root.{{moduleName}} = {};
}
root.{{moduleName}}.ApiClient = factory(root.superagent);
}
}(this, function(superagent) {
'use strict';
var ApiClient = function ApiClient() {
this.basePath = '{{basePath}}'.replace(/\/+$/, '');
};
ApiClient.prototype.paramToString = function paramToString(param) {
if (param == null) {
// return empty string for null and undefined
return '';
} else {
return param.toString();
}
};
/**
* Build full URL by appending the given path to base path and replacing
* path parameter placeholders with parameter values.
* NOTE: query parameters are not handled here.
*/
ApiClient.prototype.buildUrl = function buildUrl(path, pathParams) {
if (!path.match(/^\//)) {
path = '/' + path;
}
var url = this.basePath + path;
var _this = this;
url = url.replace(/\{([\w-]+)\}/g, function(fullMatch, key) {
var value;
if (pathParams.hasOwnProperty(key)) {
value = _this.paramToString(pathParams[key]);
} else {
value = fullMatch;
}
return encodeURIComponent(value);
});
return url;
};
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
*/
ApiClient.prototype.isJsonMime = function isJsonMime(mime) {
return Boolean(mime != null && mime.match(/^application\/json(;.*)?$/i));
};
/**
* Choose a MIME from the given MIMEs with JSON preferred,
* i.e. return JSON if included, otherwise return the first one.
*/
ApiClient.prototype.jsonPreferredMime = function jsonPreferredMime(mimes) {
var len = mimes.length;
for (var i = 0; i < len; i++) {
if (this.isJsonMime(mimes[i])) {
return mimes[i];
}
}
return mimes[0];
};
/**
* Normalize parameters values:
* remove nils,
* keep files and arrays,
* format to string with `paramToString` for other cases.
*/
ApiClient.prototype.normalizeParams = function normalizeParams(params) {
var newParams = {};
for (var key in params) {
if (params.hasOwnProperty(key) && params[key] != null) {
var value = params[key];
if (value instanceof Blob || Array.isArray(value)) {
newParams[key] = value;
} else {
newParams[key] = this.paramToString(value);
}
}
}
return newParams;
};
ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams,
queryParams, headerParams, formParams, bodyParam, contentTypes, accepts,
callback) {
var url = this.buildUrl(path, pathParams);
var request = superagent(httpMethod, url);
// set query parameters
request.query(this.normalizeParams(queryParams));
// set header parameters
request.set(this.normalizeParams(headerParams));
var contentType = this.jsonPreferredMime(contentTypes) || 'application/json';
request.type(contentType);
if (contentType === 'application/x-www-form-urlencoded') {
request.send(this.normalizeParams(formParams));
} else if (contentType == 'multipart/form-data') {
var _formParams = this.normalizeParams(formParams);
for (var key in _formParams) {
if (_formParams.hasOwnProperty(key)) {
if (_formParams[key] instanceof Blob) {
// file field
request.attach(key, _formParams[key]);
} else {
request.field(key, _formParams[key]);
}
}
}
} else if (bodyParam) {
request.send(bodyParam);
}
var accept = this.jsonPreferredMime(accepts);
if (accept) {
request.accept(accept);
}
request.end(function(error, response) {
if (callback) {
var data = response && response.body;
callback(error, data, response);
}
});
return request;
};
ApiClient.default = new ApiClient();
return ApiClient;
}));

View File

@ -1,18 +1,23 @@
// require files in Node.js environment (function(root, factory) {
var ${{#imports}}, {{import}}{{/imports}}; if (typeof define === 'function' && define.amd) {
if (typeof module === 'object' && module.exports) { // AMD. Register as an anonymous module.
$ = require('jquery');{{#imports}} define(['../ApiClient'{{#imports}}, '../model/{{import}}'{{/imports}}], factory);
{{import}} = require('../model/{{import}}.js');{{/imports}} } else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'){{#imports}}, require('../model/{{import}}'){{/imports}});
} else {
// Browser globals (root is window)
if (!root.{{moduleName}}) {
root.{{moduleName}} = {};
} }
root.{{moduleName}}.{{classname}} = factory(root.{{moduleName}}.ApiClient{{#imports}}, root.{{moduleName}}.{{import}}{{/imports}});
// export module for AMD
if ( typeof define === "function" && define.amd ) {
define(['jquery'{{#imports}}, '{{import}}'{{/imports}}], function(${{#imports}}, {{import}}{{/imports}}) {
return {{classname}};
});
} }
}(this, function(ApiClient{{#imports}}, {{import}}{{/imports}}) {
'use strict';
var {{classname}} = function {{classname}}(apiClient) {
this.apiClient = apiClient || ApiClient.default;
var {{classname}} = function {{classname}}() {
var self = this; var self = this;
{{#operations}} {{#operations}}
{{#operation}} {{#operation}}
@ -20,106 +25,62 @@ var {{classname}} = function {{classname}}() {
* {{summary}} * {{summary}}
* {{notes}} * {{notes}}
{{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}} {{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}}
{{/allParams}} * @param {function} callback the callback function {{/allParams}} * @param {function} callback the callback function, accepting three arguments: error, data, response{{#returnType}}
* @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} * data is of type: {{{returnType}}}{{/returnType}}
*/ */
self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) { self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) {
var {{localVariablePrefix}}postBody = {{#bodyParam}}{{^isBinary}}JSON.stringify({{paramName}}){{/isBinary}}{{#isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; var postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
var {{localVariablePrefix}}postBinaryBody = {{#bodyParam}}{{#isBinary}}{{paramName}}{{/isBinary}}{{^isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}} {{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set // verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) { if ({{paramName}} == null) {
//throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); throw "Missing the required parameter '{{paramName}}' when calling {{nickname}}";
var errorRequiredMsg = "Missing the required parameter '{{paramName}}' when calling {{nickname}}";
throw errorRequiredMsg;
} }
{{/required}}{{/allParams}} {{/required}}{{/allParams}}
// create path and map variables
var basePath = '{{basePath}}';
// if basePath ends with a /, remove it as path starts with a leading /
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
}
var {{localVariablePrefix}}path = basePath + replaceAll(replaceAll("{{{path}}}", "\\{format\\}","json"){{#pathParams}} {{=< >=}}
, "\\{" + "{{baseName}}" + "\\}", encodeURIComponent({{{paramName}}}.toString()){{/pathParams}}); var pathParams = {<#pathParams>
'<baseName>': <paramName><#hasMore>,</hasMore></pathParams>
};
var queryParams = {<#queryParams>
'<baseName>': <paramName><#hasMore>,</hasMore></queryParams>
};
var headerParams = {<#headerParams>
'<baseName>': <paramName><#hasMore>,</hasMore></headerParams>
};
var formParams = {<#formParams>
'<baseName>': <paramName><#hasMore>,</hasMore></formParams>
};
var queryParams = {}; var contentTypes = [<#consumes>'<mediaType>'<#hasMore>, </hasMore></consumes>];
var headerParams = {}; var accepts = [<#produces>'<mediaType>'<#hasMore>, </hasMore></produces>];
var formParams = {};
{{#queryParams}} var handleResponse = null;
queryParams.{{baseName}} = {{paramName}};
{{/queryParams}}
{{#headerParams}}if ({{paramName}} != null)
{{localVariablePrefix}}headerParams.put("{{baseName}}", {{paramName}});
{{/headerParams}}
{{#formParams}}if ({{paramName}} != null)
{{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}});
{{/formParams}}
path += createQueryString(queryParams);
var options = {type: "{{httpMethod}}", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) { if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error'; handleResponse = function(error, data, response) {<#returnType><#returnTypeIsPrimitive>
callback(null, textStatus, jqXHR, error); callback(error, data, response);</returnTypeIsPrimitive><^returnTypeIsPrimitive><#isListContainer>
// TODO: support deserializing array of models
callback(error, data, response);</isListContainer><^isListContainer>
if (!error && data) {
var result = new <&returnType>();
result.constructFromObject(data);
callback(error, result, response);
} else {
callback(error, data, response);
}</isListContainer></returnTypeIsPrimitive></returnType><^returnType>
callback(error, data, response);</returnType>
};
} }
});
request.done(function(response, textStatus, jqXHR){ return this.apiClient.callApi(
{{#returnType}} '<&path>', '<httpMethod>',
/** pathParams, queryParams, headerParams, formParams, postBody,
* @returns {{{returnType}}} contentTypes, accepts, handleResponse
*/ );
{{#returnTypeIsPrimitive}}var myResponse = response;{{/returnTypeIsPrimitive}} <={{ }}=>
{{^returnTypeIsPrimitive}}var myResponse = new {{{returnType}}}();
myResponse.constructFromObject(response);{{/returnTypeIsPrimitive}}
if (callback) {
callback(myResponse, textStatus, jqXHR);
}
{{/returnType}}{{^returnType}}
if (callback) {
callback(response, textStatus, jqXHR);
}
{{/returnType}}
});
return request;
} }
{{/operation}} {{/operation}}
{{/operations}} {{/operations}}
};
function replaceAll (haystack, needle, replace) { return {{classname}};
var result= haystack; }));
if (needle !=null && replace!=null) {
result= haystack.replace(new RegExp(needle, 'g'), replace);
}
return result;
}
function createQueryString (queryParams) {
var queryString ='';
var i = 0;
for (var queryParamName in queryParams) {
if (i==0) {
queryString += '?' ;
} else {
queryString += '&' ;
}
queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]);
i++;
}
return queryString;
}
}
// export module for Node.js
if (typeof module === 'object' && module.exports) {
module.exports = {{classname}};
}

View File

@ -1,10 +1,17 @@
if (typeof module === 'object' && module.exports) { (function(factory) {
var {{moduleName}} = {}; if (typeof define === 'function' && define.amd) {
{{#models}} // AMD. Register as an anonymous module.
{{moduleName}}.{{importPath}} = require('./model/{{importPath}}.js'); define(['./ApiClient'{{#models}}, './model/{{importPath}}'{{/models}}{{#apiInfo}}{{#apis}}, './api/{{importPath}}'{{/apis}}{{/apiInfo}}], factory);
{{/models}} } else if (typeof module === 'object' && module.exports) {
{{#apiInfo}}{{#apis}} // CommonJS-like environments that support module.exports, like Node.
{{moduleName}}.{{importPath}} = require('./api/{{importPath}}.js'); module.exports = factory(require('./ApiClient'){{#models}}, require('./model/{{importPath}}'){{/models}}{{#apiInfo}}{{#apis}}, require('./api/{{importPath}}'){{/apis}}{{/apiInfo}});
{{/apis}}{{/apiInfo}}
module.exports = {{moduleName}};
} }
}(function(ApiClient{{#models}}, {{importPath}}{{/models}}{{#apiInfo}}{{#apis}}, {{importPath}}{{/apis}}{{/apiInfo}}) {
'use strict';
return {
ApiClient: ApiClient{{#models}},
{{importPath}}: {{importPath}}{{/models}}{{#apiInfo}}{{#apis}},
{{importPath}}: {{importPath}}{{/apis}}{{/apiInfo}}
};
}));

View File

@ -1,23 +1,24 @@
// require files in Node.js environment (function(root, factory) {
{{#imports}} if (typeof define === 'function' && define.amd) {
var {{import}};{{/imports}} // AMD. Register as an anonymous module.
if (typeof module === 'object' && module.exports) { define([undefined{{#imports}}, './{{import}}'{{/imports}}], factory);
{{#imports}} } else if (typeof module === 'object' && module.exports) {
{{import}} = require('./{{import}}.js');{{/imports}} // CommonJS-like environments that support module.exports, like Node.
module.exports = factory(undefined{{#imports}}, require('./{{import}}'){{/imports}});
} else {
// Browser globals (root is window)
if (!root.{{moduleName}}) {
root.{{moduleName}} = {};
} }
factory(root.{{moduleName}}{{#imports}}, root.{{moduleName}}.{{import}}{{/imports}});
}
}(this, function(module{{#imports}}, {{import}}{{/imports}}) {
'use strict';
{{#models}}{{#model}} {{#models}}{{#model}}
{{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} {{#vars}}{{#isEnum}}{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}}
{{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}} {{>enumClass}}{{/items}}*/{{/items.isEnum}}{{/vars}}
//export module
if ( typeof define === "function" && define.amd ) {
define('{{classname}}', ['jquery'{{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}'{{datatypeWithEnum}}'{{/isPrimitiveType}}{{/vars}}],
function(${{#vars}}{{^isPrimitiveType}}{{^-last}}, {{/-last}}{{datatypeWithEnum}}{{/isPrimitiveType}}{{/vars}}) {
return {{classname}};
});
}
{{#description}}/** {{#description}}/**
* {{description}} * {{description}}
**/{{/description}} **/{{/description}}
@ -66,10 +67,13 @@ var {{classname}} = function {{classname}}({{#mandatory}}{{this}}{{^-last}}, {{/
self.toJson = function () { self.toJson = function () {
return JSON.stringify(self); return JSON.stringify(self);
} }
};
if (module) {
module.{{classname}} = {{classname}};
} }
if (typeof module === 'object' && module.exports) { return {{classname}};
module.exports = {{classname}};
}
{{/model}} {{/model}}
{{/models}} {{/models}}
}));

View File

@ -8,13 +8,10 @@
"test": "./node_modules/mocha/bin/mocha --recursive" "test": "./node_modules/mocha/bin/mocha --recursive"
}, },
"dependencies": { "dependencies": {
"jquery": "~2.1.4" "superagent": "^1.6.1"
}, },
"devDependencies": { "devDependencies": {
"mocha": "~2.3.4", "mocha": "~2.3.4",
"expect.js": "~0.3.1", "expect.js": "~0.3.1"
"mockrequire": "~0.0.5",
"domino": "~1.0.20",
"xmlhttprequest": "~1.8.0"
} }
} }

View File

@ -17,9 +17,12 @@ import com.android.volley.VolleyError;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.MultipartEntityBuilder;
import java.util.Map; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.io.File; import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
{{#operations}} {{#operations}}
public class {{classname}} { public class {{classname}} {
@ -48,6 +51,88 @@ public class {{classname}} {
* {{notes}} * {{notes}}
{{#allParams}} * @param {{paramName}} {{description}} {{#allParams}} * @param {{paramName}} {{description}}
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws TimeoutException, ExecutionException, InterruptedException, ApiException {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
VolleyError error = new VolleyError("Missing the required parameter '{{paramName}}' when calling {{nickname}}",
new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"));
}
{{/required}}{{/allParams}}
// create path and map variables
String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
{{#queryParams}}
queryParams.addAll(ApiInvoker.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));
{{/queryParams}}
{{#headerParams}}
headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
{{/headerParams}}
String[] contentTypes = {
{{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}}
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
{{#formParams}}{{#notFile}}
if ({{paramName}} != null) {
builder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8);
}
{{/notFile}}{{#isFile}}
if ({{paramName}} != null) {
builder.addBinaryBody("{{baseName}}", {{paramName}});
}
{{/isFile}}{{/formParams}}
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
{{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}}
{{/formParams}}
}
String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
try {
String response = apiInvoker.invokeAPI (basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType, authNames);
if(response != null){
return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
} else {
return {{#returnType}}null{{/returnType}};
}
} catch (ApiException ex) {
throw ex;
} catch (InterruptedException ex) {
throw ex;
} catch (ExecutionException ex) {
if(ex.getCause() instanceof VolleyError) {
throw new ApiException(((VolleyError) ex.getCause()).networkResponse.statusCode, ((VolleyError) ex.getCause()).getMessage());
}
throw ex;
} catch (TimeoutException ex) {
throw ex;
}
}
/**
* {{summary}}
* {{notes}}
{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}}
*/ */
public void {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}, {{/hasMore}}{{/allParams}}final Response.Listener<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}String{{/returnType}}> responseListener, final Response.ErrorListener errorListener) { public void {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}, {{/hasMore}}{{/allParams}}final Response.Listener<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}String{{/returnType}}> responseListener, final Response.ErrorListener errorListener) {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};

View File

@ -1,10 +1,16 @@
package {{invokerPackage}}; package {{invokerPackage}};
import android.content.Context; import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue; import com.android.volley.RequestQueue;
import com.android.volley.Response; import com.android.volley.Response;
import com.android.volley.toolbox.Volley; import com.android.volley.ResponseDelivery;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.HttpStack;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.NoCache;
import com.android.volley.toolbox.RequestFuture;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
import org.apache.http.Consts; import org.apache.http.Consts;
@ -22,6 +28,9 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import {{invokerPackage}}.auth.Authentication; import {{invokerPackage}}.auth.Authentication;
import {{invokerPackage}}.auth.ApiKeyAuth; import {{invokerPackage}}.auth.ApiKeyAuth;
@ -36,11 +45,12 @@ public class ApiInvoker {
private static ApiInvoker INSTANCE; private static ApiInvoker INSTANCE;
private Map<String, String> defaultHeaderMap = new HashMap<String, String>(); private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Context context;
private RequestQueue mRequestQueue; private RequestQueue mRequestQueue;
private Map<String, Authentication> authentications; private Map<String, Authentication> authentications;
private int connectionTimeout;
/** Content type "text/plain" with UTF-8 encoding. */ /** Content type "text/plain" with UTF-8 encoding. */
public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8); public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8);
@ -165,8 +175,16 @@ public class ApiInvoker {
return params; return params;
} }
public static void initializeInstance(Context context) { public static void initializeInstance() {
INSTANCE = new ApiInvoker(context); initializeInstance(null);
}
public static void initializeInstance(Cache cache) {
initializeInstance(cache, null, 0, null, 30);
}
public static void initializeInstance(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) {
INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout);
setUserAgent("Android-Volley-Swagger"); setUserAgent("Android-Volley-Swagger");
// Setup authentications (key: authentication name, value: authentication). // Setup authentications (key: authentication name, value: authentication).
@ -178,17 +196,27 @@ public class ApiInvoker {
{{#isBasic}} {{#isBasic}}
INSTANCE.authentications.put("{{name}}", new HttpBasicAuth()); INSTANCE.authentications.put("{{name}}", new HttpBasicAuth());
{{/isBasic}} {{/isBasic}}
{{#isOAuth}}
INSTANCE.authentications.put("{{name}}", new OAuth());
{{/isOAuth}}
{{/authMethods}} {{/authMethods}}
// Prevent the authentications from being modified. // Prevent the authentications from being modified.
INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications); INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications);
} }
private ApiInvoker(Context context) {
this.context = context; private ApiInvoker(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) {
initConnectionManager(); if(cache == null) cache = new NoCache();
if(network == null) {
HttpStack stack = new HurlStack();
network = new BasicNetwork(stack);
} }
public ApiInvoker() { if(delivery == null) {
initConnectionManager(); initConnectionRequest(cache, network);
} else {
initConnectionRequest(cache, network, threadPoolSize, delivery);
}
this.connectionTimeout = connectionTimeout;
} }
public static ApiInvoker getInstance() { public static ApiInvoker getInstance() {
@ -304,6 +332,14 @@ public class ApiInvoker {
throw new RuntimeException("No API key authentication configured!"); throw new RuntimeException("No API key authentication configured!");
} }
public void setConnectionTimeout(int connectionTimeout){
this.connectionTimeout = connectionTimeout;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
/** /**
* Update query and header parameters based on authentication settings. * Update query and header parameters based on authentication settings.
* *
@ -317,7 +353,21 @@ public class ApiInvoker {
} }
} }
public String invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames) throws ApiException, InterruptedException, ExecutionException, TimeoutException {
RequestFuture<String> future = RequestFuture.newFuture();
Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future);
if(request != null) {
mRequestQueue.add(request);
return future.get(connectionTimeout, TimeUnit.SECONDS);
} else return "no data";
}
public void invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException { public void invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException {
Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener);
if (request != null) mRequestQueue.add(request);
}
public Request<String> createRequest(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException {
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
b.append("?"); b.append("?");
@ -374,13 +424,13 @@ public class ApiInvoker {
} }
formParamStr = formParamBuilder.toString(); formParamStr = formParamBuilder.toString();
} }
Request request = null;
if ("GET".equals(method)) { if ("GET".equals(method)) {
GetRequest request = new GetRequest(url, headers, null, stringRequest, errorListener); request = new GetRequest(url, headers, null, stringRequest, errorListener);
mRequestQueue.add(request);
} }
else if ("POST".equals(method)) { else if ("POST".equals(method)) {
PostRequest request = null; request = null;
if (formParamStr != null) { if (formParamStr != null) {
request = new PostRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); request = new PostRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) { } else if (body != null) {
@ -389,11 +439,12 @@ public class ApiInvoker {
} else { } else {
request = new PostRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); request = new PostRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
} }
} else {
request = new PostRequest(url, headers, null, null, stringRequest, errorListener);
} }
if(request != null) mRequestQueue.add(request);
} }
else if ("PUT".equals(method)) { else if ("PUT".equals(method)) {
PutRequest request = null; request = null;
if (formParamStr != null) { if (formParamStr != null) {
request = new PutRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); request = new PutRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) { } else if (body != null) {
@ -402,11 +453,12 @@ public class ApiInvoker {
} else { } else {
request = new PutRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); request = new PutRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
} }
} else {
request = new PutRequest(url, headers, null, null, stringRequest, errorListener);
} }
if(request != null) mRequestQueue.add(request);
} }
else if ("DELETE".equals(method)) { else if ("DELETE".equals(method)) {
DeleteRequest request = null; request = null;
if (formParamStr != null) { if (formParamStr != null) {
request = new DeleteRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); request = new DeleteRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) { } else if (body != null) {
@ -415,11 +467,12 @@ public class ApiInvoker {
} else { } else {
request = new DeleteRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); request = new DeleteRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
} }
} else {
request = new DeleteRequest(url, headers, null, null, stringRequest, errorListener);
} }
if(request != null) mRequestQueue.add(request);
} }
else if ("PATCH".equals(method)) { else if ("PATCH".equals(method)) {
PatchRequest request = null; request = null;
if (formParamStr != null) { if (formParamStr != null) {
request = new PatchRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener); request = new PatchRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) { } else if (body != null) {
@ -428,12 +481,24 @@ public class ApiInvoker {
} else { } else {
request = new PatchRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener); request = new PatchRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
} }
} else {
request = new PatchRequest(url, headers, null, null, stringRequest, errorListener);
} }
if(request != null) mRequestQueue.add(request);
} }
return request;
} }
private void initConnectionManager() { private void initConnectionRequest(Cache cache, Network network) {
mRequestQueue = Volley.newRequestQueue(context); mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
}
private void initConnectionRequest(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) {
mRequestQueue = new RequestQueue(cache, network, threadPoolSize, delivery);
mRequestQueue.start();
}
public void stopQueue() {
mRequestQueue.stop();
} }
} }

View File

@ -44,6 +44,9 @@ public class ApiKeyAuth implements Authentication {
@Override @Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) { public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
String value; String value;
if (apiKey == null) {
return;
}
if (apiKeyPrefix != null) { if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey; value = apiKeyPrefix + " " + apiKey;
} else { } else {

View File

@ -0,0 +1,13 @@
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
import java.util.Map;
import java.util.List;
public class OAuth implements Authentication {
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
// TODO stub
}
}

View File

@ -49,6 +49,10 @@ android {
} }
} }
} }
testOptions {
unitTests.returnDefaultValues = true
}
} }
@ -58,6 +62,8 @@ ext {
httpclient_version = "4.3.3" httpclient_version = "4.3.3"
volley_version = "1.0.19" volley_version = "1.0.19"
junit_version = "4.8.1" junit_version = "4.8.1"
robolectric_version = "3.0"
concurrent_unit_version = "0.4.2"
} }
dependencies { dependencies {
@ -67,6 +73,8 @@ dependencies {
compile "org.apache.httpcomponents:httpmime:$httpclient_version" compile "org.apache.httpcomponents:httpmime:$httpclient_version"
compile "com.mcxiaoke.volley:library:${volley_version}@aar" compile "com.mcxiaoke.volley:library:${volley_version}@aar"
testCompile "junit:junit:$junit_version" testCompile "junit:junit:$junit_version"
testCompile "org.robolectric:robolectric:${robolectric_version}"
testCompile "net.jodah:concurrentunit:${concurrentunitVersion}"
} }
afterEvaluate { afterEvaluate {

View File

@ -61,7 +61,8 @@ namespace {{packageName}}.Client
/// Gets or sets the default API client for making HTTP calls. /// Gets or sets the default API client for making HTTP calls.
/// </summary> /// </summary>
/// <value>The default API client.</value> /// <value>The default API client.</value>
public static ApiClient Default = new ApiClient(Configuration.Default); [Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")]
public static ApiClient Default;
/// <summary> /// <summary>
/// Gets or sets the Configuration. /// Gets or sets the Configuration.

View File

@ -37,10 +37,7 @@ namespace {{packageName}}.Client
int timeout = 100000 int timeout = 100000
) )
{ {
if (apiClient == null) setApiClientUsingDefault(apiClient);
ApiClient = ApiClient.Default;
else
ApiClient = apiClient;
Username = username; Username = username;
Password = password; Password = password;
@ -64,10 +61,7 @@ namespace {{packageName}}.Client
/// <param name="apiClient">Api client.</param> /// <param name="apiClient">Api client.</param>
public Configuration(ApiClient apiClient) public Configuration(ApiClient apiClient)
{ {
if (apiClient == null) setApiClientUsingDefault(apiClient);
ApiClient = ApiClient.Default;
else
ApiClient = apiClient;
} }
/// <summary> /// <summary>
@ -103,6 +97,29 @@ namespace {{packageName}}.Client
/// <value>The API client.</value> /// <value>The API client.</value>
public ApiClient ApiClient; public ApiClient ApiClient;
/// <summary>
/// Set the ApiClient using Default or ApiClient instance
/// </summary>
/// <param name="apiClient">An instance of ApiClient
/// <returns></returns>
public void setApiClientUsingDefault (ApiClient apiClient = null)
{
if (apiClient == null)
{
if (Default != null && Default.ApiClient == null)
Default.ApiClient = new ApiClient();
ApiClient = Default != null ? Default.ApiClient : new ApiClient();
}
else
{
if (Default != null && Default.ApiClient == null)
Default.ApiClient = apiClient;
ApiClient = apiClient;
}
}
private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>(); private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>();
/// <summary> /// <summary>

View File

@ -1,11 +1,10 @@
## Frameworks supported ## Frameworks supported
- .NET 3.5 or later - .NET 4.0 or later
- Windows Phone 7.1 (Mango) - Windows Phone 7.1 (Mango)
## Dependencies ## Dependencies
- [RestSharp] (https://www.nuget.org/packages/RestSharp) - [RestSharp] (https://www.nuget.org/packages/RestSharp) - 105.1.0 or later
- [Json.NET] (https://www.nuget.org/packages/Newtonsoft.Json/) - [Json.NET] (https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later
NOTE: The DLLs included in the package may not be the latest version. We recommned using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: NOTE: The DLLs included in the package may not be the latest version. We recommned using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages:
``` ```

View File

@ -150,7 +150,7 @@ class ApiClient
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);
} elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model } elseif ((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(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($postData));
} }
$url = $this->config->getHost() . $resourcePath; $url = $this->config->getHost() . $resourcePath;

View File

@ -46,13 +46,13 @@ class ObjectSerializer
{ {
/** /**
* Build a JSON POST object * Serialize data
* *
* @param mixed $data the data to serialize * @param mixed $data the data to serialize
* *
* @return string serialized form of $data * @return string serialized form of $data
*/ */
public function sanitizeForSerialization($data) public static function sanitizeForSerialization($data)
{ {
if (is_scalar($data) || null === $data) { if (is_scalar($data) || null === $data) {
$sanitized = $data; $sanitized = $data;
@ -60,7 +60,7 @@ class ObjectSerializer
$sanitized = $data->format(\DateTime::ISO8601); $sanitized = $data->format(\DateTime::ISO8601);
} elseif (is_array($data)) { } elseif (is_array($data)) {
foreach ($data as $property => $value) { foreach ($data as $property => $value) {
$data[$property] = $this->sanitizeForSerialization($value); $data[$property] = self::sanitizeForSerialization($value);
} }
$sanitized = $data; $sanitized = $data;
} elseif (is_object($data)) { } elseif (is_object($data)) {
@ -68,10 +68,10 @@ class ObjectSerializer
foreach (array_keys($data::$swaggerTypes) as $property) { foreach (array_keys($data::$swaggerTypes) as $property) {
$getter = $data::$getters[$property]; $getter = $data::$getters[$property];
if ($data->$getter() !== null) { if ($data->$getter() !== null) {
$values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$getter()); $values[$data::$attributeMap[$property]] = self::sanitizeForSerialization($data->$getter());
} }
} }
$sanitized = $values; $sanitized = (object)$values;
} else { } else {
$sanitized = (string)$data; $sanitized = (string)$data;
} }
@ -220,7 +220,7 @@ class ObjectSerializer
* *
* @return object an instance of $class * @return object an instance of $class
*/ */
public function deserialize($data, $class, $httpHeaders=null) public static function deserialize($data, $class, $httpHeaders=null)
{ {
if (null === $data) { if (null === $data) {
$deserialized = null; $deserialized = null;
@ -231,14 +231,14 @@ class ObjectSerializer
$subClass_array = explode(',', $inner, 2); $subClass_array = explode(',', $inner, 2);
$subClass = $subClass_array[1]; $subClass = $subClass_array[1];
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
$deserialized[$key] = $this->deserialize($value, $subClass); $deserialized[$key] = self::deserialize($value, $subClass);
} }
} }
} elseif (strcasecmp(substr($class, -2), '[]') == 0) { } elseif (strcasecmp(substr($class, -2), '[]') == 0) {
$subClass = substr($class, 0, -2); $subClass = substr($class, 0, -2);
$values = array(); $values = array();
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
$values[] = $this->deserialize($value, $subClass); $values[] = self::deserialize($value, $subClass);
} }
$deserialized = $values; $deserialized = $values;
} elseif ($class === 'ByteArray') { // byte array } elseif ($class === 'ByteArray') { // byte array
@ -270,7 +270,7 @@ class ObjectSerializer
$propertyValue = $data->{$instance::$attributeMap[$property]}; $propertyValue = $data->{$instance::$attributeMap[$property]};
if (isset($propertyValue)) { if (isset($propertyValue)) {
$instance->$propertySetter($this->deserialize($propertyValue, $type)); $instance->$propertySetter(self::deserialize($propertyValue, $type));
} }
} }
$deserialized = $instance; $deserialized = $instance;

View File

@ -223,14 +223,14 @@ use \{{invokerPackage}}\ObjectSerializer;
return array(null, $statusCode, $httpHeader); return array(null, $statusCode, $httpHeader);
} }
return array($this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader), $statusCode, $httpHeader); return array(\{{invokerPackage}}\ObjectSerializer::deserialize($response, '{{returnType}}', $httpHeader), $statusCode, $httpHeader);
{{/returnType}}{{^returnType}} {{/returnType}}{{^returnType}}
return array(null, $statusCode, $httpHeader); return array(null, $statusCode, $httpHeader);
{{/returnType}} {{/returnType}}
} catch (ApiException $e) { } catch (ApiException $e) {
switch ($e->getCode()) { {{#responses}}{{#dataType}} switch ($e->getCode()) { {{#responses}}{{#dataType}}
{{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}}
$data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); $data = \{{invokerPackage}}\ObjectSerializer::deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders());
$e->setResponseObject($data); $e->setResponseObject($data);
break;{{/dataType}}{{/responses}} break;{{/dataType}}{{/responses}}
} }

View File

@ -0,0 +1,79 @@
<?php
/**
* {{classname}}Test
* PHP version 5
*
* @category Class
* @package {{invokerPackage}}
* @author http://github.com/swagger-api/swagger-codegen
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Copyright 2016 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace {{apiPackage}};
use \{{invokerPackage}}\Configuration;
use \{{invokerPackage}}\ApiClient;
use \{{invokerPackage}}\ApiException;
use \{{invokerPackage}}\ObjectSerializer;
/**
* {{classname}}Test Class Doc Comment
*
* @category Class
* @package {{invokerPackage}}
* @author http://github.com/swagger-api/swagger-codegen
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
* @link https://github.com/swagger-api/swagger-codegen
*/
{{#operations}}class {{classname}}Test extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running each test case
*/
public static function setUpBeforeClass() {
}
/**
* Clean up after running each test case
*/
public static function tearDownAfterClass() {
}
{{#operation}}
/**
* Test case for {{{operationId}}}
*
* {{{summary}}}
*
*/
public function test_{{operationId}}() {
}
{{/operation}}
}
{{/operations}}

View File

@ -176,9 +176,9 @@ class {{classname}} implements ArrayAccess
public function __toString() public function __toString()
{ {
if (defined('JSON_PRETTY_PRINT')) { if (defined('JSON_PRETTY_PRINT')) {
return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT);
} else { } else {
return json_encode(get_object_vars($this)); return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this));
} }
} }
} }

View File

@ -0,0 +1,74 @@
<?php
{{#models}}
{{#model}}
/**
* {{classname}}Test
*
* PHP version 5
*
* @category Class
* @package {{invokerPackage}}
* @author http://github.com/swagger-api/swagger-codegen
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Copyright 2016 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
namespace {{modelPackage}};
/**
* {{classname}}Test Class Doc Comment
*
* @category Class
* @description {{description}}
* @package {{invokerPackage}}
* @author http://github.com/swagger-api/swagger-codegen
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
* @link https://github.com/swagger-api/swagger-codegen
*/
class {{classname}}Test extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running each test case
*/
public static function setUpBeforeClass() {
}
/**
* Clean up after running each test case
*/
public static function tearDownAfterClass() {
}
/**
* Test {{classname}}
*/
public function test{{classname}}() {
}
}
{{/model}}
{{/models}}

View File

@ -438,6 +438,7 @@
<module>samples/client/petstore/android/default</module> <module>samples/client/petstore/android/default</module>
<module>samples/client/petstore/clojure</module> <module>samples/client/petstore/clojure</module>
<module>samples/client/petstore/java/default</module> <module>samples/client/petstore/java/default</module>
<module>samples/client/petstore/java/feign</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/java/retrofit</module>

View File

@ -0,0 +1,394 @@
package es.shyri.swagger.android.volley.petstore.full;
import com.android.volley.ExecutorDelivery;
import com.android.volley.Network;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.HttpStack;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.NoCache;
import net.jodah.concurrentunit.Waiter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import io.swagger.client.ApiException;
import io.swagger.client.ApiInvoker;
import io.swagger.client.api.PetApi;
import io.swagger.client.model.Category;
import io.swagger.client.model.Pet;
import static com.ibm.icu.impl.Assert.fail;
import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(RobolectricTestRunner.class)
public class PetApiTest {
PetApi api = null;
@Before
public void setup() {
HttpStack stack = new HurlStack();
Network network = new BasicNetwork(stack);
ApiInvoker.initializeInstance(new NoCache(), network, 4, new ExecutorDelivery(Executors.newSingleThreadExecutor()), 30);
api = new PetApi();
}
@Test
public void testCreateAndGetPet() throws Exception {
final Waiter waiter = new Waiter();
final Pet pet = createRandomPet();
api.addPet(pet, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
api.getPetById(pet.getId(), new Response.Listener<Pet>() {
@Override
public void onResponse(Pet response) {
Pet fetched = response;
waiter.assertNotNull(fetched);
waiter.assertEquals(pet.getId(), fetched.getId());
waiter.assertNotNull(fetched.getCategory());
waiter.assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
}
@Test
public void testUpdatePet() throws Exception {
final Waiter waiter = new Waiter();
final Pet pet = createRandomPet();
pet.setName("programmer");
api.updatePet(pet, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
api.getPetById(pet.getId(), new Response.Listener<Pet>() {
@Override
public void onResponse(Pet fetched) {
waiter.assertNotNull(fetched);
waiter.assertEquals(pet.getId(), fetched.getId());
waiter.assertNotNull(fetched.getCategory());
waiter.assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
}
@Test
public void testFindPetsByStatus() throws Exception {
final Waiter waiter = new Waiter();
final Pet pet = createRandomPet();
pet.setName("programmer");
pet.setStatus(Pet.StatusEnum.available);
api.updatePet(pet, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
api.findPetsByStatus(Arrays.asList(new String[]{"available"}), new Response.Listener<List<Pet>>() {
@Override
public void onResponse(List<Pet> pets) {
waiter.assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
waiter.assertTrue(found);
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
}
@Test
public void testUpdatePetWithForm() throws Exception {
final Waiter waiter = new Waiter();
final Pet pet = createRandomPet();
pet.setName("frank");
api.addPet(pet, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
final Pet[] fetched = new Pet[1];
api.getPetById(pet.getId(), new Response.Listener<Pet>() {
@Override
public void onResponse(Pet petResponse) {
fetched[0] = petResponse;
waiter.assertEquals("frank", fetched[0].getName());
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
api.updatePetWithForm(String.valueOf(fetched[0].getId()), "furt", null, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
api.getPetById(fetched[0].getId(), new Response.Listener<Pet>() {
@Override
public void onResponse(Pet updated) {
waiter.assertEquals("furt", updated.getName());
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
}
@Test
public void testDeletePet() throws Exception {
final Waiter waiter = new Waiter();
Pet pet = createRandomPet();
api.addPet(pet, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
final Pet[] fetched = new Pet[1];
api.getPetById(pet.getId(), new Response.Listener<Pet>() {
@Override
public void onResponse(Pet response) {
fetched[0] = response;
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
api.deletePet(fetched[0].getId(), "special-key", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
api.getPetById(fetched[0].getId(), new Response.Listener<Pet>() {
@Override
public void onResponse(Pet response) {
waiter.fail("expected an error");
waiter.resume();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
waiter.assertEquals(404, error.networkResponse.statusCode);
waiter.resume();
}
});
waiter.await();
}
@Test
public void testUploadFile() throws Exception {
final Waiter waiter = new Waiter();
Pet pet = createRandomPet();
api.addPet(pet, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
File file = new File("hello.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello world!");
writer.close();
api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath()), new Response.Listener<String>() {
@Override
public void onResponse(String response) {
waiter.resume();
}
}, createErrorListener(waiter));
waiter.await();
}
@Test
public void testCreateAndGetPetSync() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testUpdatePetSync() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
api.updatePet(pet);
Pet fetched = api.getPetById(pet.getId());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testFindPetsByStatusSync() throws Exception {
Pet pet = createRandomPet();
pet.setName("programmer");
pet.setStatus(Pet.StatusEnum.available);
api.updatePet(pet);
List<Pet> pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"}));
assertNotNull(pets);
boolean found = false;
for (Pet fetched : pets) {
if (fetched.getId().equals(pet.getId())) {
found = true;
break;
}
}
assertTrue(found);
}
@Test
public void testUpdatePetWithFormSync() throws Exception {
Pet pet = createRandomPet();
pet.setName("frank");
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
assertEquals("frank", fetched.getName());
api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null);
Pet updated = api.getPetById(fetched.getId());
assertEquals("furt", updated.getName());
}
@Test
public void testDeletePetSync() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
Pet fetched = api.getPetById(pet.getId());
api.deletePet(fetched.getId(), null);
try {
fetched = api.getPetById(fetched.getId());
fail("expected an error");
} catch (ApiException e) {
assertEquals(404, e.getCode());
}
}
@Test
public void testUploadFileSync() throws Exception {
Pet pet = createRandomPet();
api.addPet(pet);
File file = new File("hello.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello world!");
writer.close();
api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath()));
}
private Pet createRandomPet() {
Pet pet = new Pet();
pet.setId(System.currentTimeMillis());
pet.setName("gorilla");
Category category = new Category();
category.setName("really-happy");
pet.setCategory(category);
pet.setStatus(Pet.StatusEnum.available);
List<String> photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"});
pet.setPhotoUrls(photos);
return pet;
}
private Response.ErrorListener createErrorListener(final Waiter waiter) {
return new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
waiter.fail(error.getMessage());
waiter.resume();
}
};
}
}

View File

@ -1,11 +1,10 @@
## Frameworks supported ## Frameworks supported
- .NET 3.5 or later - .NET 4.0 or later
- Windows Phone 7.1 (Mango) - Windows Phone 7.1 (Mango)
## Dependencies ## Dependencies
- [RestSharp] (https://www.nuget.org/packages/RestSharp) - [RestSharp] (https://www.nuget.org/packages/RestSharp) - 105.1.0 or later
- [Json.NET] (https://www.nuget.org/packages/Newtonsoft.Json/) - [Json.NET] (https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later
NOTE: The DLLs included in the package may not be the latest version. We recommned using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: NOTE: The DLLs included in the package may not be the latest version. We recommned using [NuGet] (https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages:
``` ```

View File

@ -61,7 +61,8 @@ namespace IO.Swagger.Client
/// Gets or sets the default API client for making HTTP calls. /// Gets or sets the default API client for making HTTP calls.
/// </summary> /// </summary>
/// <value>The default API client.</value> /// <value>The default API client.</value>
public static ApiClient Default = new ApiClient(Configuration.Default); [Obsolete("ApiClient.Default is deprecated, please use 'Configuration.Default.ApiClient' instead.")]
public static ApiClient Default;
/// <summary> /// <summary>
/// Gets or sets the Configuration. /// Gets or sets the Configuration.

View File

@ -37,10 +37,7 @@ namespace IO.Swagger.Client
int timeout = 100000 int timeout = 100000
) )
{ {
if (apiClient == null) setApiClientUsingDefault(apiClient);
ApiClient = ApiClient.Default;
else
ApiClient = apiClient;
Username = username; Username = username;
Password = password; Password = password;
@ -64,10 +61,7 @@ namespace IO.Swagger.Client
/// <param name="apiClient">Api client.</param> /// <param name="apiClient">Api client.</param>
public Configuration(ApiClient apiClient) public Configuration(ApiClient apiClient)
{ {
if (apiClient == null) setApiClientUsingDefault(apiClient);
ApiClient = ApiClient.Default;
else
ApiClient = apiClient;
} }
/// <summary> /// <summary>
@ -103,6 +97,29 @@ namespace IO.Swagger.Client
/// <value>The API client.</value> /// <value>The API client.</value>
public ApiClient ApiClient; public ApiClient ApiClient;
/// <summary>
/// Set the ApiClient using Default or ApiClient instance
/// </summary>
/// <param name="apiClient">An instance of ApiClient
/// <returns></returns>
public void setApiClientUsingDefault (ApiClient apiClient = null)
{
if (apiClient == null)
{
if (Default != null && Default.ApiClient == null)
Default.ApiClient = new ApiClient();
ApiClient = Default != null ? Default.ApiClient : new ApiClient();
}
else
{
if (Default != null && Default.ApiClient == null)
Default.ApiClient = apiClient;
ApiClient = apiClient;
}
}
private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>(); private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>();
/// <summary> /// <summary>

View File

@ -1,29 +1,14 @@
<Properties StartupItem="SwaggerClientTest.csproj"> <Properties StartupItem="SwaggerClientTest.csproj">
<MonoDevelop.Ide.Workspace ActiveConfiguration="Debug" /> <MonoDevelop.Ide.Workspace ActiveConfiguration="Debug" />
<MonoDevelop.Ide.Workbench ActiveDocument="Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs"> <MonoDevelop.Ide.Workbench ActiveDocument="TestApiClient.cs">
<Files> <Files>
<File FileName="TestPet.cs" Line="182" Column="4" /> <File FileName="TestPet.cs" Line="1" Column="1" />
<File FileName="TestConfiguration.cs" Line="1" Column="1" /> <File FileName="TestConfiguration.cs" Line="1" Column="1" />
<File FileName="Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs" Line="1" Column="1" /> <File FileName="Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs" Line="1" Column="1" />
<File FileName="Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs" Line="1" Column="1" /> <File FileName="Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs" Line="64" Column="50" />
<File FileName="TestApiClient.cs" Line="1" Column="1" /> <File FileName="TestApiClient.cs" Line="1" Column="1" />
<File FileName="Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs" Line="1" Column="1" /> <File FileName="Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs" Line="1" Column="1" />
</Files> </Files>
<Pads>
<Pad Id="MonoDevelop.NUnit.TestPad">
<State name="__root__">
<Node name="SwaggerClientTest" expanded="True">
<Node name="SwaggerClientTest" expanded="True">
<Node name="SwaggerClientTest" expanded="True">
<Node name="TestApiClient" expanded="True">
<Node name="TestApiClient" expanded="True" />
</Node>
</Node>
</Node>
</Node>
</State>
</Pad>
</Pads>
</MonoDevelop.Ide.Workbench> </MonoDevelop.Ide.Workbench>
<MonoDevelop.Ide.DebuggingService.Breakpoints> <MonoDevelop.Ide.DebuggingService.Breakpoints>
<BreakpointStore /> <BreakpointStore />

View File

@ -2,6 +2,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using IO.Swagger.Client; using IO.Swagger.Client;
using IO.Swagger.Api;
namespace SwaggerClientTest.TestApiClient namespace SwaggerClientTest.TestApiClient
{ {
@ -111,6 +112,34 @@ namespace SwaggerClientTest.TestApiClient
Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename(".\\sun.gif")); Assert.AreEqual("sun.gif", ApiClient.SanitizeFilename(".\\sun.gif"));
} }
[Test ()]
public void TestApiClientInstance ()
{
PetApi p1 = new PetApi ();
PetApi p2 = new PetApi ();
Configuration c1 = new Configuration (); // using default ApiClient
PetApi p3 = new PetApi (c1);
ApiClient a1 = new ApiClient();
Configuration c2 = new Configuration (a1); // using "a1" as the ApiClient
PetApi p4 = new PetApi (c2);
// ensure both using the same default ApiClient
Assert.AreSame(p1.Configuration.ApiClient, p2.Configuration.ApiClient);
Assert.AreSame(p1.Configuration.ApiClient, Configuration.Default.ApiClient);
// ensure both using the same default ApiClient
Assert.AreSame(p3.Configuration.ApiClient, c1.ApiClient);
Assert.AreSame(p3.Configuration.ApiClient, Configuration.Default.ApiClient);
// ensure it's not using the default ApiClient
Assert.AreSame(p4.Configuration.ApiClient, c2.ApiClient);
Assert.AreNotSame(p4.Configuration.ApiClient, Configuration.Default.ApiClient);
}
} }
} }

View File

@ -1,18 +1,9 @@
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.swagger-logo.png /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.swagger-logo.png
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll
/Users/williamcheng/Code/tmp/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.swagger-logo.png
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll
/Users/williamcheng/Code/wing328/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll

View File

@ -41,7 +41,7 @@ import io.swagger.client.auth.HttpBasicAuth;
import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.ApiKeyAuth;
import io.swagger.client.auth.OAuth; import io.swagger.client.auth.OAuth;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-08T18:50:38.131+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class ApiClient { public class ApiClient {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>(); private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private String basePath = "http://petstore.swagger.io/v2"; private String basePath = "http://petstore.swagger.io/v2";
@ -451,34 +451,51 @@ public class ApiClient {
} }
} }
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException { /**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param path The sub path
* @param queryParams The query parameters
* @return The full URL
*/
private String buildUrl(String path, List<Pair> queryParams) {
final StringBuilder url = new StringBuilder();
url.append(basePath).append(path);
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return url.toString();
}
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
if (body != null && !formParams.isEmpty()) { if (body != null && !formParams.isEmpty()) {
throw new ApiException(500, "Cannot have body and form params"); throw new ApiException(500, "Cannot have body and form params");
} }
updateParamsForAuth(authNames, queryParams, headerParams); updateParamsForAuth(authNames, queryParams, headerParams);
StringBuilder b = new StringBuilder(); final String url = buildUrl(path, queryParams);
b.append("?");
if (queryParams != null){
for (Pair queryParam : queryParams){
if (!queryParam.getName().isEmpty()) {
b.append(escapeString(queryParam.getName()));
b.append("=");
b.append(escapeString(queryParam.getValue()));
b.append("&");
}
}
}
String querystring = b.substring(0, b.length() - 1);
Builder builder; Builder builder;
if (accept == null) if (accept == null) {
builder = httpClient.resource(basePath + path + querystring).getRequestBuilder(); builder = httpClient.resource(url).getRequestBuilder();
else } else {
builder = httpClient.resource(basePath + path + querystring).accept(accept); builder = httpClient.resource(url).accept(accept);
}
for (String key : headerParams.keySet()) { for (String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key)); builder = builder.header(key, headerParams.get(key));

View File

@ -12,7 +12,7 @@ import java.io.File;
import java.util.*; import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class PetApi { public class PetApi {
private ApiClient apiClient; private ApiClient apiClient;
@ -395,6 +395,93 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" }; String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return byte[]
*/
public byte[] getPetByIdWithByteArray(Long petId) throws ApiException {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetByIdWithByteArray");
}
// create path and map variables
String path = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "api_key" };
GenericType<byte[]> returnType = new GenericType<byte[]>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param body Pet object in the form of byte array
* @return void
*/
public void addPetUsingByteArray(byte[] body) throws ApiException {
Object postBody = body;
// create path and map variables
String path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json", "application/xml"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
} }

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class Category { public class Category {
private Long id = null; private Long id = null;
@ -45,7 +45,7 @@ public class Category {
@Override @Override
public boolean equals(Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@ -53,8 +53,10 @@ public class Category {
return false; return false;
} }
Category category = (Category) o; Category category = (Category) o;
return Objects.equals(id, category.id) &&
Objects.equals(name, category.name); return true && Objects.equals(id, category.id) &&
Objects.equals(name, category.name)
;
} }
@Override @Override
@ -77,7 +79,7 @@ public class Category {
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*/ */
private String toIndentedString(Object o) { private String toIndentedString(java.lang.Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
} }

View File

@ -11,7 +11,7 @@ import java.util.Date;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class Order { public class Order {
private Long id = null; private Long id = null;
@ -123,7 +123,7 @@ public class Order {
@Override @Override
public boolean equals(Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@ -131,12 +131,14 @@ public class Order {
return false; return false;
} }
Order order = (Order) o; Order order = (Order) o;
return Objects.equals(id, order.id) &&
return true && Objects.equals(id, order.id) &&
Objects.equals(petId, order.petId) && Objects.equals(petId, order.petId) &&
Objects.equals(quantity, order.quantity) && Objects.equals(quantity, order.quantity) &&
Objects.equals(shipDate, order.shipDate) && Objects.equals(shipDate, order.shipDate) &&
Objects.equals(status, order.status) && Objects.equals(status, order.status) &&
Objects.equals(complete, order.complete); Objects.equals(complete, order.complete)
;
} }
@Override @Override
@ -163,7 +165,7 @@ public class Order {
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*/ */
private String toIndentedString(Object o) { private String toIndentedString(java.lang.Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
} }

View File

@ -13,7 +13,7 @@ import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class Pet { public class Pet {
private Long id = null; private Long id = null;
@ -125,7 +125,7 @@ public class Pet {
@Override @Override
public boolean equals(Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@ -133,12 +133,14 @@ public class Pet {
return false; return false;
} }
Pet pet = (Pet) o; Pet pet = (Pet) o;
return Objects.equals(id, pet.id) &&
return true && Objects.equals(id, pet.id) &&
Objects.equals(category, pet.category) && Objects.equals(category, pet.category) &&
Objects.equals(name, pet.name) && Objects.equals(name, pet.name) &&
Objects.equals(photoUrls, pet.photoUrls) && Objects.equals(photoUrls, pet.photoUrls) &&
Objects.equals(tags, pet.tags) && Objects.equals(tags, pet.tags) &&
Objects.equals(status, pet.status); Objects.equals(status, pet.status)
;
} }
@Override @Override
@ -165,7 +167,7 @@ public class Pet {
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*/ */
private String toIndentedString(Object o) { private String toIndentedString(java.lang.Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
} }

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class Tag { public class Tag {
private Long id = null; private Long id = null;
@ -45,7 +45,7 @@ public class Tag {
@Override @Override
public boolean equals(Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@ -53,8 +53,10 @@ public class Tag {
return false; return false;
} }
Tag tag = (Tag) o; Tag tag = (Tag) o;
return Objects.equals(id, tag.id) &&
Objects.equals(name, tag.name); return true && Objects.equals(id, tag.id) &&
Objects.equals(name, tag.name)
;
} }
@Override @Override
@ -77,7 +79,7 @@ public class Tag {
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*/ */
private String toIndentedString(Object o) { private String toIndentedString(java.lang.Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
} }

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class User { public class User {
private Long id = null; private Long id = null;
@ -130,7 +130,7 @@ public class User {
@Override @Override
public boolean equals(Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@ -138,14 +138,16 @@ public class User {
return false; return false;
} }
User user = (User) o; User user = (User) o;
return Objects.equals(id, user.id) &&
return true && Objects.equals(id, user.id) &&
Objects.equals(username, user.username) && Objects.equals(username, user.username) &&
Objects.equals(firstName, user.firstName) && Objects.equals(firstName, user.firstName) &&
Objects.equals(lastName, user.lastName) && Objects.equals(lastName, user.lastName) &&
Objects.equals(email, user.email) && Objects.equals(email, user.email) &&
Objects.equals(password, user.password) && Objects.equals(password, user.password) &&
Objects.equals(phone, user.phone) && Objects.equals(phone, user.phone) &&
Objects.equals(userStatus, user.userStatus); Objects.equals(userStatus, user.userStatus)
;
} }
@Override @Override
@ -174,7 +176,7 @@ public class User {
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*/ */
private String toIndentedString(Object o) { private String toIndentedString(java.lang.Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
} }

View File

@ -0,0 +1,17 @@
package io.swagger;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class TestUtils {
private static final AtomicLong atomicId = createAtomicId();
public static long nextId() {
return atomicId.getAndIncrement();
}
private static AtomicLong createAtomicId() {
int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000;
return new AtomicLong((long) baseId);
}
}

View File

@ -1,9 +1,12 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.client.ApiClient; import com.fasterxml.jackson.annotation.*;
import io.swagger.client.ApiException; import com.fasterxml.jackson.databind.*;
import io.swagger.client.Configuration; import com.fasterxml.jackson.datatype.joda.*;
import io.swagger.TestUtils;
import io.swagger.client.*;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.auth.*; import io.swagger.client.auth.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -19,7 +22,8 @@ import org.junit.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
public class PetApiTest { public class PetApiTest {
PetApi api = null; private PetApi api;
private ObjectMapper mapper;
@Before @Before
public void setup() { public void setup() {
@ -68,6 +72,20 @@ public class PetApiTest {
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
} }
@Test
public void testCreateAndGetPetWithByteArray() throws Exception {
Pet pet = createRandomPet();
byte[] bytes = serializeJson(pet).getBytes();
api.addPetUsingByteArray(bytes);
byte[] fetchedBytes = api.getPetByIdWithByteArray(pet.getId());
Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class);
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test @Test
public void testUpdatePet() throws Exception { public void testUpdatePet() throws Exception {
Pet pet = createRandomPet(); Pet pet = createRandomPet();
@ -203,7 +221,7 @@ public class PetApiTest {
private Pet createRandomPet() { private Pet createRandomPet() {
Pet pet = new Pet(); Pet pet = new Pet();
pet.setId(System.currentTimeMillis()); pet.setId(TestUtils.nextId());
pet.setName("gorilla"); pet.setName("gorilla");
Category category = new Category(); Category category = new Category();
@ -216,4 +234,37 @@ public class PetApiTest {
return pet; return pet;
} }
private String serializeJson(Object o) {
if (mapper == null) {
mapper = createObjectMapper();
}
try {
return mapper.writeValueAsString(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private <T> T deserializeJson(String json, Class<T> klass) {
if (mapper == null) {
mapper = createObjectMapper();
}
try {
return mapper.readValue(json, klass);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.registerModule(new JodaModule());
return mapper;
}
} }

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiException; import io.swagger.client.ApiException;
import io.swagger.client.*; import io.swagger.client.*;
@ -63,7 +65,7 @@ public class StoreApiTest {
private Order createOrder() { private Order createOrder() {
Order order = new Order(); Order order = new Order();
order.setId(new Long(System.currentTimeMillis())); order.setId(TestUtils.nextId());
order.setPetId(new Long(200)); order.setPetId(new Long(200));
order.setQuantity(new Integer(13)); order.setQuantity(new Integer(13));
order.setShipDate(new java.util.Date()); order.setShipDate(new java.util.Date());

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.auth.*; import io.swagger.client.auth.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -33,9 +35,9 @@ public class UserApiTest {
@Test @Test
public void testCreateUsersWithArray() throws Exception { public void testCreateUsersWithArray() throws Exception {
User user1 = createUser(); User user1 = createUser();
user1.setUsername("abc123"); user1.setUsername("user" + user1.getId());
User user2 = createUser(); User user2 = createUser();
user2.setUsername("123abc"); user2.setUsername("user" + user2.getId());
api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2}));
@ -46,9 +48,9 @@ public class UserApiTest {
@Test @Test
public void testCreateUsersWithList() throws Exception { public void testCreateUsersWithList() throws Exception {
User user1 = createUser(); User user1 = createUser();
user1.setUsername("abc123"); user1.setUsername("user" + user1.getId());
User user2 = createUser(); User user2 = createUser();
user2.setUsername("123abc"); user2.setUsername("user" + user2.getId());
api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2}));
@ -72,7 +74,7 @@ public class UserApiTest {
private User createUser() { private User createUser() {
User user = new User(); User user = new User();
user.setId(System.currentTimeMillis()); user.setId(TestUtils.nextId());
user.setUsername("fred" + user.getId()); user.setUsername("fred" + user.getId());
user.setFirstName("Fred"); user.setFirstName("Fred");
user.setLastName("Meyer"); user.setLastName("Meyer");

View File

@ -0,0 +1 @@
Hello world!

View File

@ -0,0 +1,17 @@
package io.swagger;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class TestUtils {
private static final AtomicLong atomicId = createAtomicId();
public static long nextId() {
return atomicId.getAndIncrement();
}
private static AtomicLong createAtomicId() {
int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000;
return new AtomicLong((long) baseId);
}
}

View File

@ -1,7 +1,8 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.client.ApiClient; import io.swagger.TestUtils;
import io.swagger.client.ApiClient;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -183,7 +184,7 @@ public class PetApiTest {
private Pet createRandomPet() { private Pet createRandomPet() {
Pet pet = new Pet(); Pet pet = new Pet();
pet.setId(System.currentTimeMillis()); pet.setId(TestUtils.nextId());
pet.setName("gorilla"); pet.setName("gorilla");
Category category = new Category(); Category category = new Category();

View File

@ -1,5 +1,9 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import feign.FeignException;
import io.swagger.TestUtils;
import io.swagger.client.*; import io.swagger.client.*;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -44,15 +48,19 @@ public class StoreApiTest {
Order fetched = api.getOrderById(order.getId().toString()); Order fetched = api.getOrderById(order.getId().toString());
assertEquals(fetched.getId(), order.getId()); assertEquals(fetched.getId(), order.getId());
api.deleteOrder(String.valueOf(order.getId())); api.deleteOrder(order.getId().toString());
try {
api.getOrderById(order.getId().toString()); api.getOrderById(order.getId().toString());
// fail("expected an error"); fail("expected an error");
} catch (FeignException e) {
assertTrue(e.getMessage().startsWith("status 404 "));
}
} }
private Order createOrder() { private Order createOrder() {
Order order = new Order(); Order order = new Order();
order.setId(new Long(System.currentTimeMillis())); order.setId(TestUtils.nextId());
order.setPetId(new Long(200)); order.setPetId(new Long(200));
order.setQuantity(new Integer(13)); order.setQuantity(new Integer(13));
order.setShipDate(new java.util.Date()); order.setShipDate(new java.util.Date());

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiClient; import io.swagger.client.ApiClient;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -32,9 +34,9 @@ public class UserApiTest {
@Test @Test
public void testCreateUsersWithArray() throws Exception { public void testCreateUsersWithArray() throws Exception {
User user1 = createUser(); User user1 = createUser();
user1.setUsername("abc123"); user1.setUsername("user" + user1.getId());
User user2 = createUser(); User user2 = createUser();
user2.setUsername("123abc"); user2.setUsername("user" + user2.getId());
api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2}));
@ -45,9 +47,9 @@ public class UserApiTest {
@Test @Test
public void testCreateUsersWithList() throws Exception { public void testCreateUsersWithList() throws Exception {
User user1 = createUser(); User user1 = createUser();
user1.setUsername("abc123"); user1.setUsername("user" + user1.getId());
User user2 = createUser(); User user2 = createUser();
user2.setUsername("123abc"); user2.setUsername("user" + user2.getId());
api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2}));
@ -73,7 +75,7 @@ public class UserApiTest {
private User createUser() { private User createUser() {
User user = new User(); User user = new User();
user.setId(System.currentTimeMillis()); user.setId(TestUtils.nextId());
user.setUsername("fred" + user.getId()); user.setUsername("fred" + user.getId());
user.setFirstName("Fred"); user.setFirstName("Fred");
user.setLastName("Meyer"); user.setLastName("Meyer");

View File

@ -43,7 +43,7 @@ import io.swagger.client.auth.HttpBasicAuth;
import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.ApiKeyAuth;
import io.swagger.client.auth.OAuth; import io.swagger.client.auth.OAuth;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-08T18:51:26.068+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class ApiClient { public class ApiClient {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>(); private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private String basePath = "http://petstore.swagger.io/v2"; private String basePath = "http://petstore.swagger.io/v2";
@ -494,7 +494,9 @@ public class ApiClient {
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException { public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams); updateParamsForAuth(authNames, queryParams, headerParams);
WebTarget target = httpClient.target(this.basePath).path(path); // Not using `.target(this.basePath).path(path)` below,
// to support (constant) query string in `path`, e.g. "/posts?draft=1"
WebTarget target = httpClient.target(this.basePath + path);
if (queryParams != null) { if (queryParams != null) {
for (Pair queryParam : queryParams) { for (Pair queryParam : queryParams) {

View File

@ -12,7 +12,7 @@ import java.io.File;
import java.util.*; import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class PetApi { public class PetApi {
private ApiClient apiClient; private ApiClient apiClient;
@ -395,6 +395,93 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" }; String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return byte[]
*/
public byte[] getPetByIdWithByteArray(Long petId) throws ApiException {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetByIdWithByteArray");
}
// create path and map variables
String path = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "api_key" };
GenericType<byte[]> returnType = new GenericType<byte[]>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param body Pet object in the form of byte array
* @return void
*/
public void addPetUsingByteArray(byte[] body) throws ApiException {
Object postBody = body;
// create path and map variables
String path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json", "application/xml"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
} }

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class Category { public class Category {
private Long id = null; private Long id = null;
@ -45,7 +45,7 @@ public class Category {
@Override @Override
public boolean equals(Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@ -53,8 +53,10 @@ public class Category {
return false; return false;
} }
Category category = (Category) o; Category category = (Category) o;
return Objects.equals(id, category.id) &&
Objects.equals(name, category.name); return true && Objects.equals(id, category.id) &&
Objects.equals(name, category.name)
;
} }
@Override @Override
@ -77,7 +79,7 @@ public class Category {
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*/ */
private String toIndentedString(Object o) { private String toIndentedString(java.lang.Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
} }

View File

@ -11,7 +11,7 @@ import java.util.Date;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class Order { public class Order {
private Long id = null; private Long id = null;
@ -123,7 +123,7 @@ public class Order {
@Override @Override
public boolean equals(Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@ -131,12 +131,14 @@ public class Order {
return false; return false;
} }
Order order = (Order) o; Order order = (Order) o;
return Objects.equals(id, order.id) &&
return true && Objects.equals(id, order.id) &&
Objects.equals(petId, order.petId) && Objects.equals(petId, order.petId) &&
Objects.equals(quantity, order.quantity) && Objects.equals(quantity, order.quantity) &&
Objects.equals(shipDate, order.shipDate) && Objects.equals(shipDate, order.shipDate) &&
Objects.equals(status, order.status) && Objects.equals(status, order.status) &&
Objects.equals(complete, order.complete); Objects.equals(complete, order.complete)
;
} }
@Override @Override
@ -163,7 +165,7 @@ public class Order {
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*/ */
private String toIndentedString(Object o) { private String toIndentedString(java.lang.Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
} }

View File

@ -13,7 +13,7 @@ import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class Pet { public class Pet {
private Long id = null; private Long id = null;
@ -125,7 +125,7 @@ public class Pet {
@Override @Override
public boolean equals(Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@ -133,12 +133,14 @@ public class Pet {
return false; return false;
} }
Pet pet = (Pet) o; Pet pet = (Pet) o;
return Objects.equals(id, pet.id) &&
return true && Objects.equals(id, pet.id) &&
Objects.equals(category, pet.category) && Objects.equals(category, pet.category) &&
Objects.equals(name, pet.name) && Objects.equals(name, pet.name) &&
Objects.equals(photoUrls, pet.photoUrls) && Objects.equals(photoUrls, pet.photoUrls) &&
Objects.equals(tags, pet.tags) && Objects.equals(tags, pet.tags) &&
Objects.equals(status, pet.status); Objects.equals(status, pet.status)
;
} }
@Override @Override
@ -165,7 +167,7 @@ public class Pet {
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*/ */
private String toIndentedString(Object o) { private String toIndentedString(java.lang.Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
} }

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class Tag { public class Tag {
private Long id = null; private Long id = null;
@ -45,7 +45,7 @@ public class Tag {
@Override @Override
public boolean equals(Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@ -53,8 +53,10 @@ public class Tag {
return false; return false;
} }
Tag tag = (Tag) o; Tag tag = (Tag) o;
return Objects.equals(id, tag.id) &&
Objects.equals(name, tag.name); return true && Objects.equals(id, tag.id) &&
Objects.equals(name, tag.name)
;
} }
@Override @Override
@ -77,7 +79,7 @@ public class Tag {
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*/ */
private String toIndentedString(Object o) { private String toIndentedString(java.lang.Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
} }

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class User { public class User {
private Long id = null; private Long id = null;
@ -130,7 +130,7 @@ public class User {
@Override @Override
public boolean equals(Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
@ -138,14 +138,16 @@ public class User {
return false; return false;
} }
User user = (User) o; User user = (User) o;
return Objects.equals(id, user.id) &&
return true && Objects.equals(id, user.id) &&
Objects.equals(username, user.username) && Objects.equals(username, user.username) &&
Objects.equals(firstName, user.firstName) && Objects.equals(firstName, user.firstName) &&
Objects.equals(lastName, user.lastName) && Objects.equals(lastName, user.lastName) &&
Objects.equals(email, user.email) && Objects.equals(email, user.email) &&
Objects.equals(password, user.password) && Objects.equals(password, user.password) &&
Objects.equals(phone, user.phone) && Objects.equals(phone, user.phone) &&
Objects.equals(userStatus, user.userStatus); Objects.equals(userStatus, user.userStatus)
;
} }
@Override @Override
@ -174,7 +176,7 @@ public class User {
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*/ */
private String toIndentedString(Object o) { private String toIndentedString(java.lang.Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
} }

View File

@ -0,0 +1,17 @@
package io.swagger;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class TestUtils {
private static final AtomicLong atomicId = createAtomicId();
public static long nextId() {
return atomicId.getAndIncrement();
}
private static AtomicLong createAtomicId() {
int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000;
return new AtomicLong((long) baseId);
}
}

View File

@ -1,9 +1,10 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.client.ApiClient; import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.client.ApiException;
import io.swagger.client.Configuration;
import io.swagger.TestUtils;
import io.swagger.client.*;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.auth.*; import io.swagger.client.auth.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -68,6 +69,20 @@ public class PetApiTest {
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
} }
@Test
public void testCreateAndGetPetWithByteArray() throws Exception {
Pet pet = createRandomPet();
byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes();
api.addPetUsingByteArray(bytes);
byte[] fetchedBytes = api.getPetByIdWithByteArray(pet.getId());
Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class, api.getApiClient());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test @Test
public void testUpdatePet() throws Exception { public void testUpdatePet() throws Exception {
Pet pet = createRandomPet(); Pet pet = createRandomPet();
@ -203,7 +218,7 @@ public class PetApiTest {
private Pet createRandomPet() { private Pet createRandomPet() {
Pet pet = new Pet(); Pet pet = new Pet();
pet.setId(System.currentTimeMillis()); pet.setId(TestUtils.nextId());
pet.setName("gorilla"); pet.setName("gorilla");
Category category = new Category(); Category category = new Category();
@ -216,4 +231,22 @@ public class PetApiTest {
return pet; return pet;
} }
private String serializeJson(Object o, ApiClient apiClient) {
ObjectMapper mapper = apiClient.getJSON().getContext(null);
try {
return mapper.writeValueAsString(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private <T> T deserializeJson(String json, Class<T> klass, ApiClient apiClient) {
ObjectMapper mapper = apiClient.getJSON().getContext(null);
try {
return mapper.readValue(json, klass);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} }

View File

@ -1,6 +1,6 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.client.ApiException; import io.swagger.TestUtils;
import io.swagger.client.*; import io.swagger.client.*;
import io.swagger.client.api.*; import io.swagger.client.api.*;
@ -63,7 +63,7 @@ public class StoreApiTest {
private Order createOrder() { private Order createOrder() {
Order order = new Order(); Order order = new Order();
order.setId(new Long(System.currentTimeMillis())); order.setId(TestUtils.nextId());
order.setPetId(new Long(200)); order.setPetId(new Long(200));
order.setQuantity(new Integer(13)); order.setQuantity(new Integer(13));
order.setShipDate(new java.util.Date()); order.setShipDate(new java.util.Date());

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.auth.*; import io.swagger.client.auth.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -33,9 +35,9 @@ public class UserApiTest {
@Test @Test
public void testCreateUsersWithArray() throws Exception { public void testCreateUsersWithArray() throws Exception {
User user1 = createUser(); User user1 = createUser();
user1.setUsername("abc123"); user1.setUsername("user" + user1.getId());
User user2 = createUser(); User user2 = createUser();
user2.setUsername("123abc"); user2.setUsername("user" + user2.getId());
api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2}));
@ -46,9 +48,9 @@ public class UserApiTest {
@Test @Test
public void testCreateUsersWithList() throws Exception { public void testCreateUsersWithList() throws Exception {
User user1 = createUser(); User user1 = createUser();
user1.setUsername("abc123"); user1.setUsername("user" + user1.getId());
User user2 = createUser(); User user2 = createUser();
user2.setUsername("123abc"); user2.setUsername("user" + user2.getId());
api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2}));
@ -72,7 +74,7 @@ public class UserApiTest {
private User createUser() { private User createUser() {
User user = new User(); User user = new User();
user.setId(System.currentTimeMillis()); user.setId(TestUtils.nextId());
user.setUsername("fred" + user.getId()); user.setUsername("fred" + user.getId());
user.setFirstName("Fred"); user.setFirstName("Fred");
user.setLastName("Meyer"); user.setLastName("Meyer");

View File

@ -656,8 +656,8 @@ public class ApiClient {
} }
/** /**
* Deserialize response body to Java object, according to the Content-Type * Deserialize response body to Java object, according to the return type and
* response header. * the Content-Type response header.
* *
* @param response HTTP response * @param response HTTP response
* @param returnType The type of the Java object * @param returnType The type of the Java object
@ -666,12 +666,21 @@ public class ApiClient {
* or the Content-Type of the response is not supported. * or the Content-Type of the response is not supported.
*/ */
public <T> T deserialize(Response response, Type returnType) throws ApiException { public <T> T deserialize(Response response, Type returnType) throws ApiException {
if (response == null || returnType == null) if (response == null || returnType == null) {
return null; return null;
}
if ("byte[]".equals(returnType.toString())) {
// Handle binary response (byte array).
try {
return (T) response.body().bytes();
} catch (IOException e) {
throw new ApiException(e);
}
} else if (returnType.equals(File.class)) {
// Handle file downloading. // Handle file downloading.
if (returnType.equals(File.class))
return (T) downloadFileFromResponse(response); return (T) downloadFileFromResponse(response);
}
String respBody; String respBody;
try { try {
@ -683,8 +692,9 @@ public class ApiClient {
throw new ApiException(e); throw new ApiException(e);
} }
if (respBody == null || "".equals(respBody)) if (respBody == null || "".equals(respBody)) {
return null; return null;
}
String contentType = response.headers().get("Content-Type"); String contentType = response.headers().get("Content-Type");
if (contentType == null) { if (contentType == null) {
@ -706,20 +716,29 @@ public class ApiClient {
} }
/** /**
* Serialize the given Java object into request body string, according to the * Serialize the given Java object into request body according to the object's
* request Content-Type. * class and the request Content-Type.
* *
* @param obj The Java object * @param obj The Java object
* @param contentType The request Content-Type * @param contentType The request Content-Type
* @return The serialized string * @return The serialized request body
* @throws ApiException If fail to serialize the given object * @throws ApiException If fail to serialize the given object
*/ */
public String serialize(Object obj, String contentType) throws ApiException { public RequestBody serialize(Object obj, String contentType) throws ApiException {
if (isJsonMime(contentType)) { if (obj instanceof byte[]) {
if (obj != null) // Binary (byte array) body parameter support.
return json.serialize(obj); return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
else } else if (obj instanceof File) {
return null; // File body parameter support.
return RequestBody.create(MediaType.parse(contentType), (File) obj);
} else if (isJsonMime(contentType)) {
String content;
if (obj != null) {
content = json.serialize(obj);
} else {
content = null;
}
return RequestBody.create(MediaType.parse(contentType), content);
} else { } else {
throw new ApiException("Content type \"" + contentType + "\" is not supported"); throw new ApiException("Content type \"" + contentType + "\" is not supported");
} }
@ -908,7 +927,7 @@ public class ApiClient {
reqBody = RequestBody.create(MediaType.parse(contentType), ""); reqBody = RequestBody.create(MediaType.parse(contentType), "");
} }
} else { } else {
reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); reqBody = serialize(body, contentType);
} }
Request request = null; Request request = null;
@ -931,20 +950,27 @@ public class ApiClient {
* @return The full URL * @return The full URL
*/ */
public String buildUrl(String path, List<Pair> queryParams) { public String buildUrl(String path, List<Pair> queryParams) {
StringBuilder query = new StringBuilder(); final StringBuilder url = new StringBuilder();
if (queryParams != null) { url.append(basePath).append(path);
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) { for (Pair param : queryParams) {
if (param.getValue() != null) { if (param.getValue() != null) {
if (query.toString().length() == 0) if (prefix != null) {
query.append("?"); url.append(prefix);
else prefix = null;
query.append("&"); } else {
url.append("&");
}
String value = parameterToString(param.getValue()); String value = parameterToString(param.getValue());
query.append(escapeString(param.getName())).append("=").append(escapeString(value)); url.append(escapeString(param.getName())).append("=").append(escapeString(value));
} }
} }
} }
return basePath + path + query.toString();
return url.toString();
} }
/** /**

View File

@ -892,4 +892,210 @@ public class PetApi {
return call; return call;
} }
/* Build call for getPetByIdWithByteArray */
private Call getPetByIdWithByteArrayCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw new ApiException("Missing the required parameter 'petId' when calling getPetByIdWithByteArray(Async)");
}
// create path and map variables
String path = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
if (accept != null) headerParams.put("Accept", accept);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
headerParams.put("Content-Type", contentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] authNames = new String[] { "api_key" };
return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener);
}
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return byte[]
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public byte[] getPetByIdWithByteArray(Long petId) throws ApiException {
ApiResponse<byte[]> resp = getPetByIdWithByteArrayWithHttpInfo(petId);
return resp.getData();
}
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return ApiResponse<byte[]>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<byte[]> getPetByIdWithByteArrayWithHttpInfo(Long petId) throws ApiException {
Call call = getPetByIdWithByteArrayCall(petId, null, null);
Type returnType = new TypeToken<byte[]>(){}.getType();
return apiClient.execute(call, returnType);
}
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39; (asynchronously)
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public Call getPetByIdWithByteArrayAsync(Long petId, final ApiCallback<byte[]> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
Call call = getPetByIdWithByteArrayCall(petId, progressListener, progressRequestListener);
Type returnType = new TypeToken<byte[]>(){}.getType();
apiClient.executeAsync(call, returnType, callback);
return call;
}
/* Build call for addPetUsingByteArray */
private Call addPetUsingByteArrayCall(byte[] body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object postBody = body;
// create path and map variables
String path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json");
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
if (accept != null) headerParams.put("Accept", accept);
final String[] contentTypes = {
"application/json", "application/xml"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
headerParams.put("Content-Type", contentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] authNames = new String[] { "petstore_auth" };
return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param body Pet object in the form of byte array
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void addPetUsingByteArray(byte[] body) throws ApiException {
addPetUsingByteArrayWithHttpInfo(body);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param body Pet object in the form of byte array
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> addPetUsingByteArrayWithHttpInfo(byte[] body) throws ApiException {
Call call = addPetUsingByteArrayCall(body, null, null);
return apiClient.execute(call);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store (asynchronously)
*
* @param body Pet object in the form of byte array
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public Call addPetUsingByteArrayAsync(byte[] body, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
Call call = addPetUsingByteArrayCall(body, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
} }

View File

@ -0,0 +1,17 @@
package io.swagger;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class TestUtils {
private static final AtomicLong atomicId = createAtomicId();
public static long nextId() {
return atomicId.getAndIncrement();
}
private static AtomicLong createAtomicId() {
int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000;
return new AtomicLong((long) baseId);
}
}

View File

@ -1,5 +1,9 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import com.google.gson.reflect.TypeToken;
import io.swagger.TestUtils;
import io.swagger.client.*; import io.swagger.client.*;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.auth.*; import io.swagger.client.auth.*;
@ -8,6 +12,7 @@ import io.swagger.client.model.*;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.lang.reflect.Type;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -67,6 +72,23 @@ public class PetApiTest {
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
} }
@Test
public void testCreateAndGetPetWithByteArray() throws Exception {
Pet pet = createRandomPet();
System.out.println(serializeJson(pet, api.getApiClient()));
byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes();
api.addPetUsingByteArray(bytes);
byte[] fetchedBytes = api.getPetByIdWithByteArray(pet.getId());
System.out.println(new String(fetchedBytes));
Type type = new TypeToken<Pet>(){}.getType();
Pet fetched = deserializeJson(new String(fetchedBytes), type, api.getApiClient());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test @Test
public void testCreateAndGetPetWithHttpInfo() throws Exception { public void testCreateAndGetPetWithHttpInfo() throws Exception {
Pet pet = createRandomPet(); Pet pet = createRandomPet();
@ -312,7 +334,7 @@ public class PetApiTest {
private Pet createRandomPet() { private Pet createRandomPet() {
Pet pet = new Pet(); Pet pet = new Pet();
pet.setId(System.currentTimeMillis()); pet.setId(TestUtils.nextId());
pet.setName("gorilla"); pet.setName("gorilla");
Category category = new Category(); Category category = new Category();
@ -325,4 +347,12 @@ public class PetApiTest {
return pet; return pet;
} }
private String serializeJson(Object o, ApiClient apiClient) {
return apiClient.getJSON().serialize(o);
}
private <T> T deserializeJson(String json, Type type, ApiClient apiClient) {
return (T) apiClient.getJSON().deserialize(json, type);
}
} }

View File

@ -1,5 +1,6 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiException; import io.swagger.client.ApiException;
import io.swagger.client.*; import io.swagger.client.*;
@ -67,7 +68,7 @@ public class StoreApiTest {
private Order createOrder() { private Order createOrder() {
Order order = new Order(); Order order = new Order();
order.setId(new Long(System.currentTimeMillis())); order.setId(TestUtils.nextId());
order.setPetId(new Long(200)); order.setPetId(new Long(200));
order.setQuantity(new Integer(13)); order.setQuantity(new Integer(13));
order.setShipDate(new java.util.Date()); order.setShipDate(new java.util.Date());

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.auth.*; import io.swagger.client.auth.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -33,9 +35,9 @@ public class UserApiTest {
@Test @Test
public void testCreateUsersWithArray() throws Exception { public void testCreateUsersWithArray() throws Exception {
User user1 = createUser(); User user1 = createUser();
user1.setUsername("abc123"); user1.setUsername("user" + user1.getId());
User user2 = createUser(); User user2 = createUser();
user2.setUsername("123abc"); user2.setUsername("user" + user2.getId());
api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2}));
@ -46,9 +48,9 @@ public class UserApiTest {
@Test @Test
public void testCreateUsersWithList() throws Exception { public void testCreateUsersWithList() throws Exception {
User user1 = createUser(); User user1 = createUser();
user1.setUsername("abc123"); user1.setUsername("user" + user1.getId());
User user2 = createUser(); User user2 = createUser();
user2.setUsername("123abc"); user2.setUsername("user" + user2.getId());
api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2}));
@ -72,7 +74,7 @@ public class UserApiTest {
private User createUser() { private User createUser() {
User user = new User(); User user = new User();
user.setId(System.currentTimeMillis()); user.setId(TestUtils.nextId());
user.setUsername("fred" + user.getId()); user.setUsername("fred" + user.getId());
user.setFirstName("Fred"); user.setFirstName("Fred");
user.setLastName("Meyer"); user.setLastName("Meyer");

View File

@ -0,0 +1 @@
Hello world!

View File

@ -0,0 +1,17 @@
package io.swagger;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class TestUtils {
private static final AtomicLong atomicId = createAtomicId();
public static long nextId() {
return atomicId.getAndIncrement();
}
private static AtomicLong createAtomicId() {
int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000;
return new AtomicLong((long) baseId);
}
}

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiClient; import io.swagger.client.ApiClient;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -172,7 +174,7 @@ public class PetApiTest {
private Pet createRandomPet() { private Pet createRandomPet() {
Pet pet = new Pet(); Pet pet = new Pet();
pet.setId(System.currentTimeMillis()); pet.setId(TestUtils.nextId());
pet.setName("gorilla"); pet.setName("gorilla");
Category category = new Category(); Category category = new Category();

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiClient; import io.swagger.client.ApiClient;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -56,7 +58,7 @@ public class StoreApiTest {
private Order createOrder() { private Order createOrder() {
Order order = new Order(); Order order = new Order();
order.setId(new Long(System.currentTimeMillis())); order.setId(new Long(TestUtils.nextId()));
order.setPetId(new Long(200)); order.setPetId(new Long(200));
order.setQuantity(new Integer(13)); order.setQuantity(new Integer(13));
order.setShipDate(new java.util.Date()); order.setShipDate(new java.util.Date());

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiClient; import io.swagger.client.ApiClient;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -31,9 +33,9 @@ public class UserApiTest {
@Test @Test
public void testCreateUsersWithArray() throws Exception { public void testCreateUsersWithArray() throws Exception {
User user1 = createUser(); User user1 = createUser();
user1.setUsername("abc123"); user1.setUsername("user" + user1.getId());
User user2 = createUser(); User user2 = createUser();
user2.setUsername("123abc"); user2.setUsername("user" + user2.getId());
api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2}));
@ -44,9 +46,9 @@ public class UserApiTest {
@Test @Test
public void testCreateUsersWithList() throws Exception { public void testCreateUsersWithList() throws Exception {
User user1 = createUser(); User user1 = createUser();
user1.setUsername("abc123"); user1.setUsername("user" + user1.getId());
User user2 = createUser(); User user2 = createUser();
user2.setUsername("123abc"); user2.setUsername("user" + user2.getId());
api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2}));
@ -70,7 +72,7 @@ public class UserApiTest {
private User createUser() { private User createUser() {
User user = new User(); User user = new User();
user.setId(System.currentTimeMillis()); user.setId(TestUtils.nextId());
user.setUsername("fred" + user.getId()); user.setUsername("fred" + user.getId());
user.setFirstName("Fred"); user.setFirstName("Fred");
user.setLastName("Meyer"); user.setLastName("Meyer");

View File

@ -0,0 +1 @@
Hello world!

View File

@ -0,0 +1,17 @@
package io.swagger;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class TestUtils {
private static final AtomicLong atomicId = createAtomicId();
public static long nextId() {
return atomicId.getAndIncrement();
}
private static AtomicLong createAtomicId() {
int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000;
return new AtomicLong((long) baseId);
}
}

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiClient; import io.swagger.client.ApiClient;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -171,7 +173,7 @@ public class PetApiTest {
private Pet createRandomPet() { private Pet createRandomPet() {
Pet pet = new Pet(); Pet pet = new Pet();
pet.setId(System.currentTimeMillis()); pet.setId(TestUtils.nextId());
pet.setName("gorilla"); pet.setName("gorilla");
Category category = new Category(); Category category = new Category();

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiClient; import io.swagger.client.ApiClient;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -52,7 +54,7 @@ public class StoreApiTest {
private Order createOrder() { private Order createOrder() {
Order order = new Order(); Order order = new Order();
order.setId(new Long(System.currentTimeMillis())); order.setId(new Long(TestUtils.nextId()));
order.setPetId(new Long(200)); order.setPetId(new Long(200));
order.setQuantity(new Integer(13)); order.setQuantity(new Integer(13));
order.setShipDate(new java.util.Date()); order.setShipDate(new java.util.Date());

Some files were not shown because too many files have changed in this diff Show More