mirror of
https://github.com/valitydev/openapi-generator.git
synced 2024-11-08 19:33:55 +00:00
Merge remote-tracking branch 'upstream/master' into cli-enhancements-2
This commit is contained in:
commit
44b5c22cd4
@ -264,6 +264,7 @@ CONFIG OPTIONS
|
||||
library template (sub-template) to use:
|
||||
<default> - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2
|
||||
jersey2 - HTTP client: Jersey client 2.6
|
||||
okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1
|
||||
```
|
||||
|
||||
Your config file for java can look like
|
||||
|
@ -25,6 +25,7 @@ cd $APP_DIR
|
||||
./bin/html-petstore.sh
|
||||
./bin/java-petstore.sh
|
||||
./bin/java-petstore-jersey2.sh
|
||||
./bin/java-petstore-okhttp-gson.sh
|
||||
./bin/jaxrs-petstore-server.sh
|
||||
./bin/nodejs-petstore-server.sh
|
||||
./bin/objc-petstore.sh
|
||||
|
4
bin/java-petstore-okhttp-gson.json
Normal file
4
bin/java-petstore-okhttp-gson.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"library": "okhttp-gson",
|
||||
"artifactId": "swagger-petstore-okhttp-gson"
|
||||
}
|
31
bin/java-petstore-okhttp-gson.sh
Executable file
31
bin/java-petstore-okhttp-gson.sh
Executable file
@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
|
||||
SCRIPT="$0"
|
||||
|
||||
while [ -h "$SCRIPT" ] ; do
|
||||
ls=`ls -ld "$SCRIPT"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
SCRIPT="$link"
|
||||
else
|
||||
SCRIPT=`dirname "$SCRIPT"`/"$link"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ ! -d "${APP_DIR}" ]; then
|
||||
APP_DIR=`dirname "$SCRIPT"`/..
|
||||
APP_DIR=`cd "${APP_DIR}"; pwd`
|
||||
fi
|
||||
|
||||
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
|
||||
|
||||
if [ ! -f "$executable" ]
|
||||
then
|
||||
mvn clean package
|
||||
fi
|
||||
|
||||
# if you've executed sbt assembly previously it will use that instead.
|
||||
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
|
||||
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson"
|
||||
|
||||
java $JAVA_OPTS -jar $executable $ags
|
@ -12,7 +12,7 @@ public class CodegenOperation {
|
||||
public final List<CodegenProperty> responseHeaders = new ArrayList<CodegenProperty>();
|
||||
public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive,
|
||||
returnSimpleType, subresourceOperation, isMapContainer, isListContainer,
|
||||
hasMore = Boolean.TRUE, isMultipart;
|
||||
hasMore = Boolean.TRUE, isMultipart, isResponseBinary = Boolean.FALSE;
|
||||
public String path, operationId, returnType, httpMethod, returnBaseType,
|
||||
returnContainer, summary, notes, baseName, defaultResponse;
|
||||
public List<Map<String, String>> consumes, produces;
|
||||
@ -29,6 +29,7 @@ public class CodegenOperation {
|
||||
public Set<String> imports = new HashSet<String>();
|
||||
public List<Map<String, String>> examples;
|
||||
public ExternalDocs externalDocs;
|
||||
public Map<String, Object> vendorExtensions;
|
||||
|
||||
private boolean nonempty(List<CodegenParameter> params)
|
||||
{
|
||||
|
@ -13,6 +13,7 @@ public class CodegenParameter {
|
||||
public boolean isEnum;
|
||||
public List<String> _enum;
|
||||
public Map<String, Object> allowableValues;
|
||||
public Map<String, Object> vendorExtensions;
|
||||
|
||||
/**
|
||||
* Determines whether this parameter is mandatory. If the parameter is in "path",
|
||||
@ -50,6 +51,7 @@ public class CodegenParameter {
|
||||
if (this.allowableValues != null) {
|
||||
output.allowableValues = new HashMap<String, Object>(this.allowableValues);
|
||||
}
|
||||
output.vendorExtensions = this.vendorExtensions;
|
||||
|
||||
return output;
|
||||
}
|
||||
|
@ -15,7 +15,7 @@ public class CodegenResponse {
|
||||
public Boolean primitiveType;
|
||||
public Boolean isMapContainer;
|
||||
public Boolean isListContainer;
|
||||
public Boolean isBinary;
|
||||
public Boolean isBinary = Boolean.FALSE;
|
||||
public Object schema;
|
||||
public String jsonSchema;
|
||||
|
||||
|
@ -85,6 +85,7 @@ public class DefaultCodegen {
|
||||
protected boolean supportsInheritance = false;
|
||||
protected Map<String, String> supportedLibraries = new LinkedHashMap<String, String>();
|
||||
protected String library = null;
|
||||
protected Boolean sortParamsByRequiredFlag = true;
|
||||
|
||||
public List<CliOption> cliOptions() {
|
||||
return cliOptions;
|
||||
@ -673,7 +674,102 @@ public class DefaultCodegen {
|
||||
property.allowableValues = allowableValues;
|
||||
}
|
||||
}
|
||||
if(p instanceof IntegerProperty) {
|
||||
IntegerProperty sp = (IntegerProperty) p;
|
||||
if(sp.getEnum() != null) {
|
||||
List<Integer> _enum = sp.getEnum();
|
||||
property._enum = new ArrayList<String>();
|
||||
for(Integer i : _enum) {
|
||||
property._enum.add(i.toString());
|
||||
}
|
||||
property.isEnum = true;
|
||||
|
||||
// legacy support
|
||||
Map<String, Object> allowableValues = new HashMap<String, Object>();
|
||||
allowableValues.put("values", _enum);
|
||||
property.allowableValues = allowableValues;
|
||||
}
|
||||
}
|
||||
if(p instanceof LongProperty) {
|
||||
LongProperty sp = (LongProperty) p;
|
||||
if(sp.getEnum() != null) {
|
||||
List<Long> _enum = sp.getEnum();
|
||||
property._enum = new ArrayList<String>();
|
||||
for(Long i : _enum) {
|
||||
property._enum.add(i.toString());
|
||||
}
|
||||
property.isEnum = true;
|
||||
|
||||
// legacy support
|
||||
Map<String, Object> allowableValues = new HashMap<String, Object>();
|
||||
allowableValues.put("values", _enum);
|
||||
property.allowableValues = allowableValues;
|
||||
}
|
||||
}
|
||||
if(p instanceof DoubleProperty) {
|
||||
DoubleProperty sp = (DoubleProperty) p;
|
||||
if(sp.getEnum() != null) {
|
||||
List<Double> _enum = sp.getEnum();
|
||||
property._enum = new ArrayList<String>();
|
||||
for(Double i : _enum) {
|
||||
property._enum.add(i.toString());
|
||||
}
|
||||
property.isEnum = true;
|
||||
|
||||
// legacy support
|
||||
Map<String, Object> allowableValues = new HashMap<String, Object>();
|
||||
allowableValues.put("values", _enum);
|
||||
property.allowableValues = allowableValues;
|
||||
}
|
||||
}
|
||||
if(p instanceof FloatProperty) {
|
||||
FloatProperty sp = (FloatProperty) p;
|
||||
if(sp.getEnum() != null) {
|
||||
List<Float> _enum = sp.getEnum();
|
||||
property._enum = new ArrayList<String>();
|
||||
for(Float i : _enum) {
|
||||
property._enum.add(i.toString());
|
||||
}
|
||||
property.isEnum = true;
|
||||
|
||||
// legacy support
|
||||
Map<String, Object> allowableValues = new HashMap<String, Object>();
|
||||
allowableValues.put("values", _enum);
|
||||
property.allowableValues = allowableValues;
|
||||
}
|
||||
}
|
||||
if(p instanceof DateProperty) {
|
||||
DateProperty sp = (DateProperty) p;
|
||||
if(sp.getEnum() != null) {
|
||||
List<String> _enum = sp.getEnum();
|
||||
property._enum = new ArrayList<String>();
|
||||
for(String i : _enum) {
|
||||
property._enum.add(i.toString());
|
||||
}
|
||||
property.isEnum = true;
|
||||
|
||||
// legacy support
|
||||
Map<String, Object> allowableValues = new HashMap<String, Object>();
|
||||
allowableValues.put("values", _enum);
|
||||
property.allowableValues = allowableValues;
|
||||
}
|
||||
}
|
||||
if(p instanceof DateTimeProperty) {
|
||||
DateTimeProperty sp = (DateTimeProperty) p;
|
||||
if(sp.getEnum() != null) {
|
||||
List<String> _enum = sp.getEnum();
|
||||
property._enum = new ArrayList<String>();
|
||||
for(String i : _enum) {
|
||||
property._enum.add(i.toString());
|
||||
}
|
||||
property.isEnum = true;
|
||||
|
||||
// legacy support
|
||||
Map<String, Object> allowableValues = new HashMap<String, Object>();
|
||||
allowableValues.put("values", _enum);
|
||||
property.allowableValues = allowableValues;
|
||||
}
|
||||
}
|
||||
property.datatype = getTypeDeclaration(p);
|
||||
|
||||
// this can cause issues for clients which don't support enums
|
||||
@ -685,28 +781,28 @@ public class DefaultCodegen {
|
||||
|
||||
property.baseType = getSwaggerType(p);
|
||||
|
||||
if (p instanceof ArrayProperty) {
|
||||
property.isContainer = true;
|
||||
property.containerType = "array";
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
CodegenProperty cp = fromProperty(property.name, ap.getItems());
|
||||
if (cp == null) {
|
||||
LOGGER.warn("skipping invalid property " + Json.pretty(p));
|
||||
} else {
|
||||
property.baseType = getSwaggerType(p);
|
||||
if (!languageSpecificPrimitives.contains(cp.baseType)) {
|
||||
property.complexType = cp.baseType;
|
||||
} else {
|
||||
property.isPrimitiveType = true;
|
||||
}
|
||||
property.items = cp;
|
||||
if (property.items.isEnum) {
|
||||
property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.baseType,
|
||||
property.items.datatypeWithEnum);
|
||||
property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum);
|
||||
}
|
||||
}
|
||||
} else if (p instanceof MapProperty) {
|
||||
if (p instanceof ArrayProperty) {
|
||||
property.isContainer = true;
|
||||
property.containerType = "array";
|
||||
ArrayProperty ap = (ArrayProperty) p;
|
||||
CodegenProperty cp = fromProperty(property.name, ap.getItems());
|
||||
if (cp == null) {
|
||||
LOGGER.warn("skipping invalid property " + Json.pretty(p));
|
||||
} else {
|
||||
property.baseType = getSwaggerType(p);
|
||||
if (!languageSpecificPrimitives.contains(cp.baseType)) {
|
||||
property.complexType = cp.baseType;
|
||||
} else {
|
||||
property.isPrimitiveType = true;
|
||||
}
|
||||
property.items = cp;
|
||||
if (property.items.isEnum) {
|
||||
property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.baseType,
|
||||
property.items.datatypeWithEnum);
|
||||
property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum);
|
||||
}
|
||||
}
|
||||
} else if (p instanceof MapProperty) {
|
||||
property.isContainer = true;
|
||||
property.containerType = "map";
|
||||
MapProperty ap = (MapProperty) p;
|
||||
@ -752,6 +848,7 @@ public class DefaultCodegen {
|
||||
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map<String, Model> definitions) {
|
||||
CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION);
|
||||
Set<String> imports = new HashSet<String>();
|
||||
op.vendorExtensions = operation.getVendorExtensions();
|
||||
|
||||
String operationId = operation.getOperationId();
|
||||
if (operationId == null) {
|
||||
@ -835,6 +932,9 @@ public class DefaultCodegen {
|
||||
}
|
||||
r.isDefault = response == methodResponse;
|
||||
op.responses.add(r);
|
||||
if (r.isBinary && r.isDefault){
|
||||
op.isResponseBinary = Boolean.TRUE;
|
||||
}
|
||||
}
|
||||
op.responses.get(op.responses.size() - 1).hasMore = false;
|
||||
|
||||
@ -928,16 +1028,19 @@ public class DefaultCodegen {
|
||||
op.bodyParam = bodyParam;
|
||||
op.httpMethod = httpMethod.toUpperCase();
|
||||
// move "required" parameters in front of "optional" parameters
|
||||
Collections.sort(allParams, new Comparator<CodegenParameter>() {
|
||||
@Override
|
||||
public int compare(CodegenParameter one, CodegenParameter another) {
|
||||
boolean oneRequired = one.required == null ? false : one.required;
|
||||
boolean anotherRequired = another.required == null ? false : another.required;
|
||||
if (oneRequired == anotherRequired) return 0;
|
||||
else if (oneRequired) return -1;
|
||||
else return 1;
|
||||
}
|
||||
});
|
||||
|
||||
if(sortParamsByRequiredFlag) {
|
||||
Collections.sort(allParams, new Comparator<CodegenParameter>() {
|
||||
@Override
|
||||
public int compare(CodegenParameter one, CodegenParameter another) {
|
||||
boolean oneRequired = one.required == null ? false : one.required;
|
||||
boolean anotherRequired = another.required == null ? false : another.required;
|
||||
if (oneRequired == anotherRequired) return 0;
|
||||
else if (oneRequired) return -1;
|
||||
else return 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
op.allParams = addHasMore(allParams);
|
||||
op.bodyParams = addHasMore(bodyParams);
|
||||
op.pathParams = addHasMore(pathParams);
|
||||
@ -1029,6 +1132,8 @@ public class DefaultCodegen {
|
||||
p.defaultValue = ((FormParameter) param).getDefaultValue();
|
||||
}
|
||||
|
||||
p.vendorExtensions = param.getVendorExtensions();
|
||||
|
||||
if (param instanceof SerializableParameter) {
|
||||
SerializableParameter qp = (SerializableParameter) param;
|
||||
Property property = null;
|
||||
|
@ -83,6 +83,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
supportedLibraries.put("<default>", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2");
|
||||
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6");
|
||||
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1");
|
||||
cliOptions.add(buildLibraryCliOption(supportedLibraries));
|
||||
}
|
||||
|
||||
@ -159,7 +160,19 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
|
||||
supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java"));
|
||||
supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java"));
|
||||
supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java"));
|
||||
|
||||
// library-specific files
|
||||
if ("okhttp-gson".equals(getLibrary())) {
|
||||
// the "okhttp-gson" library template requires "ApiCallback.mustache" for async call
|
||||
supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java"));
|
||||
// "build.gradle" is for development with Gradle
|
||||
supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle"));
|
||||
// "build.sbt" is for development with SBT
|
||||
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
|
||||
// and does not require "TypeRef.mustache"
|
||||
} else {
|
||||
supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java"));
|
||||
}
|
||||
|
||||
final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator);
|
||||
supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java"));
|
||||
@ -340,6 +353,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
continue;
|
||||
List<String> values = (List<String>) allowableValues.get("values");
|
||||
// put "enumVars" map into `allowableValues", including `name` and `value`
|
||||
if (values == null)
|
||||
continue;
|
||||
List<Map<String, String>> enumVars = new ArrayList<Map<String, String>>();
|
||||
for (String value : values) {
|
||||
Map<String, String> enumVar = new HashMap<String, String>();
|
||||
|
@ -39,4 +39,13 @@ public class StringUtil {
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the given object to string with each line indented by 4 spaces
|
||||
* (except the first line).
|
||||
*/
|
||||
public static String toIndentedString(Object o) {
|
||||
if (o == null) return "null";
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
|
@ -86,26 +86,23 @@ public class {{classname}} {
|
||||
final String {{localVariablePrefix}}contentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}contentTypes);
|
||||
|
||||
String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
|
||||
{{#responses}}
|
||||
{{#isDefault}}
|
||||
|
||||
{{#isBinary}}
|
||||
{{#isResponseBinary}}
|
||||
byte[] {{localVariablePrefix}}response = null;
|
||||
{{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeBinaryAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams,{{localVariablePrefix}} postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames);
|
||||
return {{localVariablePrefix}}response;
|
||||
{{/isBinary}}
|
||||
{{/isResponseBinary}}
|
||||
|
||||
{{^isBinary}}
|
||||
{{^isResponseBinary}}
|
||||
{{#returnType}}
|
||||
TypeRef {{localVariablePrefix}}returnType = new TypeRef<{{{returnType}}}>() {};
|
||||
return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType);
|
||||
{{/returnType}}{{^returnType}}
|
||||
{{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null);
|
||||
{{/returnType}}
|
||||
{{/isBinary}}
|
||||
{{/isResponseBinary}}
|
||||
|
||||
|
||||
{{/isDefault}}
|
||||
{{/responses}}
|
||||
}
|
||||
{{/operation}}
|
||||
}
|
||||
|
@ -6,20 +6,45 @@ import java.util.List;
|
||||
{{>generatedAnnotation}}
|
||||
public class ApiException extends Exception {
|
||||
private int code = 0;
|
||||
private String message = null;
|
||||
private Map<String, List<String>> responseHeaders = null;
|
||||
private String responseBody = null;
|
||||
|
||||
public ApiException() {}
|
||||
|
||||
public ApiException(int code, String message) {
|
||||
public ApiException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
|
||||
public ApiException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) {
|
||||
super(message, throwable);
|
||||
this.code = code;
|
||||
this.responseHeaders = responseHeaders;
|
||||
this.responseBody = responseBody;
|
||||
}
|
||||
|
||||
public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) {
|
||||
this(message, (Throwable) null, code, responseHeaders, responseBody);
|
||||
}
|
||||
|
||||
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) {
|
||||
this(message, throwable, code, responseHeaders, null);
|
||||
}
|
||||
|
||||
public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) {
|
||||
this((String) null, (Throwable) null, code, responseHeaders, responseBody);
|
||||
}
|
||||
|
||||
public ApiException(int code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
this(code, message);
|
||||
this.responseHeaders = responseHeaders;
|
||||
this.responseBody = responseBody;
|
||||
}
|
||||
@ -28,10 +53,6 @@ public class ApiException extends Exception {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the HTTP response headers.
|
||||
*/
|
||||
|
@ -3,7 +3,7 @@ public enum {{datatypeWithEnum}} {
|
||||
|
||||
private String value;
|
||||
|
||||
StatusEnum(String value) {
|
||||
{{datatypeWithEnum}}(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,22 @@
|
||||
package {{invokerPackage}};
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Callback for asynchronous API call.
|
||||
*
|
||||
* @param <T> The return type
|
||||
*/
|
||||
public interface ApiCallback<T> {
|
||||
/**
|
||||
* This is called when the API call fails.
|
||||
*/
|
||||
void onFailure(ApiException e);
|
||||
|
||||
/**
|
||||
* This is called when the API call succeeded.
|
||||
*
|
||||
* @param result The result deserialized from response
|
||||
*/
|
||||
void onSuccess(T result);
|
||||
}
|
@ -0,0 +1,762 @@
|
||||
package {{invokerPackage}};
|
||||
|
||||
import com.squareup.okhttp.Call;
|
||||
import com.squareup.okhttp.Callback;
|
||||
import com.squareup.okhttp.OkHttpClient;
|
||||
import com.squareup.okhttp.Request;
|
||||
import com.squareup.okhttp.Response;
|
||||
import com.squareup.okhttp.RequestBody;
|
||||
import com.squareup.okhttp.FormEncodingBuilder;
|
||||
import com.squareup.okhttp.MultipartBuilder;
|
||||
import com.squareup.okhttp.MediaType;
|
||||
import com.squareup.okhttp.Headers;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.net.URLConnection;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.text.ParseException;
|
||||
|
||||
import {{invokerPackage}}.auth.Authentication;
|
||||
import {{invokerPackage}}.auth.HttpBasicAuth;
|
||||
import {{invokerPackage}}.auth.ApiKeyAuth;
|
||||
import {{invokerPackage}}.auth.OAuth;
|
||||
|
||||
public class ApiClient {
|
||||
private String basePath = "{{basePath}}";
|
||||
private boolean lenientOnJson = false;
|
||||
private boolean debugging = false;
|
||||
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
|
||||
|
||||
private Map<String, Authentication> authentications;
|
||||
|
||||
private String dateFormat;
|
||||
private DateFormat dateFormatter;
|
||||
private int dateLength;
|
||||
|
||||
private String datetimeFormat;
|
||||
private DateFormat datetimeFormatter;
|
||||
|
||||
private OkHttpClient httpClient;
|
||||
private JSON json;
|
||||
|
||||
public ApiClient() {
|
||||
httpClient = new OkHttpClient();
|
||||
|
||||
json = new JSON(this);
|
||||
|
||||
// Use ISO 8601 format for date and datetime.
|
||||
// See https://en.wikipedia.org/wiki/ISO_8601
|
||||
setDateFormat("yyyy-MM-dd");
|
||||
setDatetimeFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
|
||||
|
||||
// Set default User-Agent.
|
||||
setUserAgent("Java-Swagger");
|
||||
|
||||
// Setup authentications (key: authentication name, value: authentication).
|
||||
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}
|
||||
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
|
||||
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
|
||||
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
|
||||
// Prevent the authentications from being modified.
|
||||
authentications = Collections.unmodifiableMap(authentications);
|
||||
}
|
||||
|
||||
public String getBasePath() {
|
||||
return basePath;
|
||||
}
|
||||
|
||||
public ApiClient setBasePath(String basePath) {
|
||||
this.basePath = basePath;
|
||||
return this;
|
||||
}
|
||||
|
||||
public OkHttpClient getHttpClient() {
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
public ApiClient setHttpClient(OkHttpClient httpClient) {
|
||||
this.httpClient = httpClient;
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSON getJSON() {
|
||||
return json;
|
||||
}
|
||||
|
||||
public ApiClient setJSON(JSON json) {
|
||||
this.json = json;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDateFormat() {
|
||||
return dateFormat;
|
||||
}
|
||||
|
||||
public ApiClient setDateFormat(String dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
|
||||
this.dateFormatter = new SimpleDateFormat(dateFormat);
|
||||
// Use UTC as the default time zone.
|
||||
this.dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
this.dateLength = this.dateFormatter.format(new Date()).length();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDatetimeFormat() {
|
||||
return datetimeFormat;
|
||||
}
|
||||
|
||||
public ApiClient setDatetimeFormat(String datetimeFormat) {
|
||||
this.datetimeFormat = datetimeFormat;
|
||||
|
||||
this.datetimeFormatter = new SimpleDateFormat(datetimeFormat);
|
||||
// Note: The datetime formatter uses the system's default time zone.
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the given date string into Date object.
|
||||
* The default <code>dateFormat</code> supports these ISO 8601 date formats:
|
||||
* 2015-08-16
|
||||
* 2015-8-16
|
||||
*/
|
||||
public Date parseDate(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
try {
|
||||
return dateFormatter.parse(str);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the given date-time string into Date object.
|
||||
* The default <code>datetimeFormat</code> supports these ISO 8601 datetime formats:
|
||||
* 2015-08-16T08:20:05Z
|
||||
* 2015-8-16T8:20:05Z
|
||||
* 2015-08-16T08:20:05+00:00
|
||||
* 2015-08-16T08:20:05+0000
|
||||
* 2015-08-16T08:20:05.376Z
|
||||
* 2015-08-16T08:20:05.376+00:00
|
||||
* 2015-08-16T08:20:05.376+00
|
||||
* Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of
|
||||
* these formats:
|
||||
* Z (same with +0000)
|
||||
* +08:00 (same with +0800)
|
||||
* -02 (same with -0200)
|
||||
* -0200
|
||||
* @see https://en.wikipedia.org/wiki/ISO_8601
|
||||
*/
|
||||
public Date parseDatetime(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
|
||||
if ("yyyy-MM-dd'T'HH:mm:ss.SSSZ".equals(datetimeFormat)) {
|
||||
/*
|
||||
* When the default datetime format is used, process the given string
|
||||
* to support various formats defined by ISO 8601.
|
||||
*/
|
||||
// normalize time zone
|
||||
// trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000
|
||||
str = str.replaceAll("[zZ]\\z", "+0000");
|
||||
// remove colon: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000
|
||||
str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2");
|
||||
// expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000
|
||||
str = str.replaceAll("([+-]\\d{2})\\z", "$100");
|
||||
// add milliseconds when missing
|
||||
// 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000
|
||||
str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2");
|
||||
}
|
||||
|
||||
try {
|
||||
return datetimeFormatter.parse(str);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public Date parseDateOrDatetime(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
else if (str.length() <= dateLength)
|
||||
return parseDate(str);
|
||||
else
|
||||
return parseDatetime(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given Date object into string.
|
||||
*/
|
||||
public String formatDate(Date date) {
|
||||
return dateFormatter.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given Date object into string.
|
||||
*/
|
||||
public String formatDatetime(Date date) {
|
||||
return datetimeFormatter.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get authentications (key: authentication name, value: authentication).
|
||||
*/
|
||||
public Map<String, Authentication> getAuthentications() {
|
||||
return authentications;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get authentication for the given name.
|
||||
*
|
||||
* @param authName The authentication name
|
||||
* @return The authentication, null if not found
|
||||
*/
|
||||
public Authentication getAuthentication(String authName) {
|
||||
return authentications.get(authName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set username for the first HTTP basic authentication.
|
||||
*/
|
||||
public void setUsername(String username) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof HttpBasicAuth) {
|
||||
((HttpBasicAuth) auth).setUsername(username);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set password for the first HTTP basic authentication.
|
||||
*/
|
||||
public void setPassword(String password) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof HttpBasicAuth) {
|
||||
((HttpBasicAuth) auth).setPassword(password);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set API key value for the first API key authentication.
|
||||
*/
|
||||
public void setApiKey(String apiKey) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof ApiKeyAuth) {
|
||||
((ApiKeyAuth) auth).setApiKey(apiKey);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No API key authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set API key prefix for the first API key authentication.
|
||||
*/
|
||||
public void setApiKeyPrefix(String apiKeyPrefix) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof ApiKeyAuth) {
|
||||
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No API key authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the User-Agent header's value (by adding to the default header map).
|
||||
*/
|
||||
public ApiClient setUserAgent(String userAgent) {
|
||||
addDefaultHeader("User-Agent", userAgent);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a default header.
|
||||
*
|
||||
* @param key The header's key
|
||||
* @param value The header's value
|
||||
*/
|
||||
public ApiClient addDefaultHeader(String key, String value) {
|
||||
defaultHeaderMap.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
|
||||
*/
|
||||
public boolean isLenientOnJson() {
|
||||
return lenientOnJson;
|
||||
}
|
||||
|
||||
public ApiClient setLenientOnJson(boolean lenient) {
|
||||
this.lenientOnJson = lenient;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that whether debugging is enabled for this API client.
|
||||
*/
|
||||
public boolean isDebugging() {
|
||||
return debugging;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable/disable debugging for this API client.
|
||||
*
|
||||
* @param debugging To enable (true) or disable (false) debugging
|
||||
*/
|
||||
public ApiClient setDebugging(boolean debugging) {
|
||||
this.debugging = debugging;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given parameter object into string.
|
||||
*/
|
||||
public String parameterToString(Object param) {
|
||||
if (param == null) {
|
||||
return "";
|
||||
} else if (param instanceof Date) {
|
||||
return formatDatetime((Date) param);
|
||||
} else if (param instanceof Collection) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
for (Object o : (Collection)param) {
|
||||
if (b.length() > 0) {
|
||||
b.append(",");
|
||||
}
|
||||
b.append(String.valueOf(o));
|
||||
}
|
||||
return b.toString();
|
||||
} else {
|
||||
return String.valueOf(param);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Format to {@code Pair} objects.
|
||||
*/
|
||||
public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
|
||||
List<Pair> params = new ArrayList<Pair>();
|
||||
|
||||
// preconditions
|
||||
if (name == null || name.isEmpty() || value == null) return params;
|
||||
|
||||
Collection valueCollection = null;
|
||||
if (value instanceof Collection) {
|
||||
valueCollection = (Collection) value;
|
||||
} else {
|
||||
params.add(new Pair(name, parameterToString(value)));
|
||||
return params;
|
||||
}
|
||||
|
||||
if (valueCollection.isEmpty()){
|
||||
return params;
|
||||
}
|
||||
|
||||
// get the collection format
|
||||
collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
|
||||
|
||||
// create the params based on the collection format
|
||||
if (collectionFormat.equals("multi")) {
|
||||
for (Object item : valueCollection) {
|
||||
params.add(new Pair(name, parameterToString(item)));
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
String delimiter = ",";
|
||||
|
||||
if (collectionFormat.equals("csv")) {
|
||||
delimiter = ",";
|
||||
} else if (collectionFormat.equals("ssv")) {
|
||||
delimiter = " ";
|
||||
} else if (collectionFormat.equals("tsv")) {
|
||||
delimiter = "\t";
|
||||
} else if (collectionFormat.equals("pipes")) {
|
||||
delimiter = "|";
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder() ;
|
||||
for (Object item : valueCollection) {
|
||||
sb.append(delimiter);
|
||||
sb.append(parameterToString(item));
|
||||
}
|
||||
|
||||
params.add(new Pair(name, sb.substring(1)));
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the Accept header's value from the given accepts array:
|
||||
* if JSON exists in the given array, use it;
|
||||
* otherwise use all of them (joining into a string)
|
||||
*
|
||||
* @param accepts The accepts array to select from
|
||||
* @return The Accept header to use. If the given array is empty,
|
||||
* null will be returned (not to set the Accept header explicitly).
|
||||
*/
|
||||
public String selectHeaderAccept(String[] accepts) {
|
||||
if (accepts.length == 0) return null;
|
||||
if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json";
|
||||
return StringUtil.join(accepts, ",");
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the Content-Type header's value from the given array:
|
||||
* if JSON exists in the given array, use it;
|
||||
* otherwise use the first one of the array.
|
||||
*
|
||||
* @param contentTypes The Content-Type array to select from
|
||||
* @return The Content-Type header to use. If the given array is empty,
|
||||
* JSON will be used.
|
||||
*/
|
||||
public String selectHeaderContentType(String[] contentTypes) {
|
||||
if (contentTypes.length == 0) return "application/json";
|
||||
if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json";
|
||||
return contentTypes[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape the given string to be used as URL query value.
|
||||
*/
|
||||
public String escapeString(String str) {
|
||||
try {
|
||||
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize response body to Java object, according the Content-Type
|
||||
* response header.
|
||||
*
|
||||
* @param response HTTP response
|
||||
* @param returnType The type of the Java object
|
||||
* @return The deserialized Java object
|
||||
*/
|
||||
public <T> T deserialize(Response response, Type returnType) throws ApiException {
|
||||
if (response == null || returnType == null)
|
||||
return null;
|
||||
|
||||
String respBody;
|
||||
try {
|
||||
if (response.body() != null)
|
||||
respBody = response.body().string();
|
||||
else
|
||||
respBody = null;
|
||||
} catch (IOException e) {
|
||||
throw new ApiException(e);
|
||||
}
|
||||
|
||||
if (respBody == null || "".equals(respBody))
|
||||
return null;
|
||||
|
||||
String contentType = response.headers().get("Content-Type");
|
||||
if (contentType == null) {
|
||||
// ensuring a default content type
|
||||
contentType = "application/json";
|
||||
}
|
||||
if (contentType.startsWith("application/json")) {
|
||||
return json.deserialize(respBody, returnType);
|
||||
} else {
|
||||
throw new ApiException(
|
||||
"Content type \"" + contentType + "\" is not supported",
|
||||
response.code(),
|
||||
response.headers().toMultimap(),
|
||||
respBody);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the given Java object into request body string, according to the
|
||||
* request Content-Type.
|
||||
*
|
||||
* @param obj The Java object
|
||||
* @param contentType The request Content-Type
|
||||
* @return The serialized string
|
||||
*/
|
||||
public String serialize(Object obj, String contentType) throws ApiException {
|
||||
if (contentType.startsWith("application/json")) {
|
||||
if (obj != null)
|
||||
return json.serialize(obj);
|
||||
else
|
||||
return null;
|
||||
} else {
|
||||
throw new ApiException("Content type \"" + contentType + "\" is not supported");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #execute(Call, Type)
|
||||
*/
|
||||
public <T> T execute(Call call) throws ApiException {
|
||||
return execute(call, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute HTTP call and deserialize the HTTP response body into the given return type.
|
||||
*
|
||||
* @param returnType The return type used to deserialize HTTP response body
|
||||
* @param <T> The return type corresponding to (same with) returnType
|
||||
* @return The Java object deserialized from response body. Returns null if returnType is null.
|
||||
*/
|
||||
public <T> T execute(Call call, Type returnType) throws ApiException {
|
||||
try {
|
||||
Response response = call.execute();
|
||||
return handleResponse(response, returnType);
|
||||
} catch (IOException e) {
|
||||
throw new ApiException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* #see executeAsync(Call, Type, ApiCallback)
|
||||
*/
|
||||
public <T> void executeAsync(Call call, ApiCallback<T> callback) throws ApiException {
|
||||
executeAsync(call, null, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute HTTP call asynchronously.
|
||||
*
|
||||
* @see #execute(Call, Type)
|
||||
* @param The callback to be executed when the API call finishes
|
||||
*/
|
||||
public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) {
|
||||
call.enqueue(new Callback() {
|
||||
@Override
|
||||
public void onFailure(Request request, IOException e) {
|
||||
callback.onFailure(new ApiException(e));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResponse(Response response) throws IOException {
|
||||
T result;
|
||||
try {
|
||||
result = (T) handleResponse(response, returnType);
|
||||
} catch (ApiException e) {
|
||||
callback.onFailure(e);
|
||||
return;
|
||||
}
|
||||
callback.onSuccess(result);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
|
||||
if (response.isSuccessful()) {
|
||||
if (returnType == null || response.code() == 204) {
|
||||
// returning null if the returnType is not defined,
|
||||
// or the status code is 204 (No Content)
|
||||
return null;
|
||||
} else {
|
||||
return deserialize(response, returnType);
|
||||
}
|
||||
} else {
|
||||
String respBody = null;
|
||||
if (response.body() != null) {
|
||||
try {
|
||||
respBody = response.body().string();
|
||||
} catch (IOException e) {
|
||||
throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
|
||||
}
|
||||
}
|
||||
throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build HTTP call with the given options.
|
||||
*
|
||||
* @param path The sub-path of the HTTP URL
|
||||
* @param method The request method, one of "GET", "HEAD", "POST", "PUT", "PATCH" and "DELETE"
|
||||
* @param queryParams The query parameters
|
||||
* @param body The request body object
|
||||
* @param headerParams The header parameters
|
||||
* @param formParams The form parameters
|
||||
* @param authNames The authentications to apply
|
||||
* @return The HTTP call
|
||||
*/
|
||||
public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames) throws ApiException {
|
||||
updateParamsForAuth(authNames, queryParams, headerParams);
|
||||
|
||||
final String url = buildUrl(path, queryParams);
|
||||
final Request.Builder reqBuilder = new Request.Builder().url(url);
|
||||
processHeaderParams(headerParams, reqBuilder);
|
||||
|
||||
String contentType = (String) headerParams.get("Content-Type");
|
||||
// ensuring a default content type
|
||||
if (contentType == null) contentType = "application/json";
|
||||
|
||||
RequestBody reqBody;
|
||||
if ("GET".equals(method) || "HEAD".equals(method)) {
|
||||
reqBody = null;
|
||||
} else if ("application/x-www-form-urlencoded".equals(contentType)) {
|
||||
reqBody = buildRequestBodyFormEncoding(formParams);
|
||||
} else if ("multipart/form-data".equals(contentType)) {
|
||||
reqBody = buildRequestBodyMultipart(formParams);
|
||||
} else if (body == null) {
|
||||
if ("DELETE".equals(method)) {
|
||||
// allow calling DELETE without sending a request body
|
||||
reqBody = null;
|
||||
} else {
|
||||
// use an empty request body (for POST, PUT and PATCH)
|
||||
reqBody = RequestBody.create(MediaType.parse(contentType), "");
|
||||
}
|
||||
} else {
|
||||
reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType));
|
||||
}
|
||||
|
||||
Request request;
|
||||
if ("GET".equals(method)) {
|
||||
request = reqBuilder.get().build();
|
||||
} else if ("HEAD".equals(method)) {
|
||||
request = reqBuilder.head().build();
|
||||
} else if ("POST".equals(method)) {
|
||||
request = reqBuilder.post(reqBody).build();
|
||||
} else if ("PUT".equals(method)) {
|
||||
request = reqBuilder.put(reqBody).build();
|
||||
} else if ("PATCH".equals(method)) {
|
||||
request = reqBuilder.patch(reqBody).build();
|
||||
} else if ("DELETE".equals(method)) {
|
||||
if (reqBody == null) {
|
||||
// calling DELETE without sending a request body
|
||||
request = reqBuilder.delete().build();
|
||||
} else {
|
||||
request = reqBuilder.delete(reqBody).build();
|
||||
}
|
||||
} else {
|
||||
throw new ApiException("unknown method type: " + method);
|
||||
}
|
||||
|
||||
return httpClient.newCall(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build full URL by concatenating base path, the given sub path and query parameters.
|
||||
*
|
||||
* @param path The sub path
|
||||
* @param queryParams The query parameters
|
||||
* @return The full URL
|
||||
*/
|
||||
public String buildUrl(String path, List<Pair> queryParams) {
|
||||
StringBuilder query = new StringBuilder();
|
||||
if (queryParams != null) {
|
||||
for (Pair param : queryParams) {
|
||||
if (param.getValue() != null) {
|
||||
if (query.toString().length() == 0)
|
||||
query.append("?");
|
||||
else
|
||||
query.append("&");
|
||||
String value = parameterToString(param.getValue());
|
||||
query.append(escapeString(param.getName())).append("=").append(escapeString(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
return basePath + path + query.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set header parameters to the request builder, including default headers.
|
||||
*/
|
||||
public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) {
|
||||
for (Entry<String, String> param : headerParams.entrySet()) {
|
||||
reqBuilder.header(param.getKey(), parameterToString(param.getValue()));
|
||||
}
|
||||
for (Entry<String, String> header : defaultHeaderMap.entrySet()) {
|
||||
if (!headerParams.containsKey(header.getKey())) {
|
||||
reqBuilder.header(header.getKey(), parameterToString(header.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update query and header parameters based on authentication settings.
|
||||
*
|
||||
* @param authNames The authentications to apply
|
||||
*/
|
||||
public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
|
||||
for (String authName : authNames) {
|
||||
Authentication auth = authentications.get(authName);
|
||||
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
|
||||
auth.applyToParams(queryParams, headerParams);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a form-encoding request body with the given form parameters.
|
||||
*/
|
||||
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
|
||||
FormEncodingBuilder formBuilder = new FormEncodingBuilder();
|
||||
for (Entry<String, Object> param : formParams.entrySet()) {
|
||||
formBuilder.add(param.getKey(), parameterToString(param.getValue()));
|
||||
}
|
||||
return formBuilder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a multipart (file uploading) request body with the given form parameters,
|
||||
* which could contain text fields and file fields.
|
||||
*/
|
||||
public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) {
|
||||
MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
|
||||
for (Entry<String, Object> param : formParams.entrySet()) {
|
||||
if (param.getValue() instanceof File) {
|
||||
File file = (File) param.getValue();
|
||||
Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\"");
|
||||
MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
|
||||
mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file));
|
||||
} else {
|
||||
Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"");
|
||||
mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue())));
|
||||
}
|
||||
}
|
||||
return mpBuilder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Guess Content-Type header from the given file (defaults to "application/octet-stream").
|
||||
*
|
||||
* @param file The given file
|
||||
* @return The Content-Type guessed
|
||||
*/
|
||||
public String guessContentTypeFromFile(File file) {
|
||||
String contentType = URLConnection.guessContentTypeFromName(file.getName());
|
||||
if (contentType == null) {
|
||||
return "application/octet-stream";
|
||||
} else {
|
||||
return contentType;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,102 @@
|
||||
package {{invokerPackage}};
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonDeserializer;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonNull;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.google.gson.JsonSerializationContext;
|
||||
import com.google.gson.JsonSerializer;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
|
||||
import java.io.StringReader;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Date;
|
||||
|
||||
public class JSON {
|
||||
private ApiClient apiClient;
|
||||
private Gson gson;
|
||||
|
||||
public JSON(ApiClient apiClient) {
|
||||
this.apiClient = apiClient;
|
||||
gson = new GsonBuilder()
|
||||
.serializeNulls()
|
||||
.registerTypeAdapter(Date.class, new DateAdapter(apiClient))
|
||||
.create();
|
||||
}
|
||||
|
||||
public Gson getGson() {
|
||||
return gson;
|
||||
}
|
||||
|
||||
public void setGson(Gson gson) {
|
||||
this.gson = gson;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the given Java object into JSON string.
|
||||
*/
|
||||
public String serialize(Object obj) {
|
||||
return gson.toJson(obj);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize the given JSON string to Java object.
|
||||
*
|
||||
* @param body The JSON string
|
||||
* @param returnType The type to deserialize inot
|
||||
* @return The deserialized Java object
|
||||
*/
|
||||
public <T> T deserialize(String body, Type returnType) {
|
||||
try {
|
||||
if (apiClient.isLenientOnJson()) {
|
||||
JsonReader jsonReader = new JsonReader(new StringReader(body));
|
||||
// see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
|
||||
jsonReader.setLenient(true);
|
||||
return gson.fromJson(jsonReader, returnType);
|
||||
} else {
|
||||
return gson.fromJson(body, returnType);
|
||||
}
|
||||
} catch (JsonParseException e) {
|
||||
// Fallback processing when failed to parse JSON form response body:
|
||||
// return the response body string directly for the String return type;
|
||||
// parse response body into date or datetime for the Date return type.
|
||||
if (returnType.equals(String.class))
|
||||
return (T) body;
|
||||
else if (returnType.equals(Date.class))
|
||||
return (T) apiClient.parseDateOrDatetime(body);
|
||||
else throw(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
|
||||
private final ApiClient apiClient;
|
||||
|
||||
public DateAdapter(ApiClient apiClient) {
|
||||
super();
|
||||
this.apiClient = apiClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
|
||||
if (src == null) {
|
||||
return JsonNull.INSTANCE;
|
||||
} else {
|
||||
return new JsonPrimitive(apiClient.formatDatetime(src));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException {
|
||||
String str = json.getAsJsonPrimitive().getAsString();
|
||||
try {
|
||||
return apiClient.parseDateOrDatetime(str);
|
||||
} catch (RuntimeException e) {
|
||||
throw new JsonParseException(e);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,116 @@
|
||||
package {{package}};
|
||||
|
||||
import {{invokerPackage}}.ApiCallback;
|
||||
import {{invokerPackage}}.ApiClient;
|
||||
import {{invokerPackage}}.ApiException;
|
||||
import {{invokerPackage}}.Configuration;
|
||||
import {{invokerPackage}}.Pair;
|
||||
|
||||
import {{modelPackage}}.*;
|
||||
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
|
||||
import com.squareup.okhttp.Call;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
{{#imports}}import {{import}};
|
||||
{{/imports}}
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
{{#operations}}
|
||||
public class {{classname}} {
|
||||
private ApiClient {{localVariablePrefix}}apiClient;
|
||||
|
||||
public {{classname}}() {
|
||||
this(Configuration.getDefaultApiClient());
|
||||
}
|
||||
|
||||
public {{classname}}(ApiClient apiClient) {
|
||||
this.{{localVariablePrefix}}apiClient = apiClient;
|
||||
}
|
||||
|
||||
public ApiClient getApiClient() {
|
||||
return {{localVariablePrefix}}apiClient;
|
||||
}
|
||||
|
||||
public void setApiClient(ApiClient apiClient) {
|
||||
this.{{localVariablePrefix}}apiClient = apiClient;
|
||||
}
|
||||
|
||||
{{#operation}}
|
||||
/* Build call for {{nickname}} */
|
||||
private Call {{nickname}}Call({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
|
||||
Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
|
||||
{{#allParams}}{{#required}}
|
||||
// verify the required parameter '{{paramName}}' is set
|
||||
if ({{paramName}} == null) {
|
||||
throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{nickname}}(Async)");
|
||||
}
|
||||
{{/required}}{{/allParams}}
|
||||
|
||||
// create path and map variables
|
||||
String {{localVariablePrefix}}path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}
|
||||
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
|
||||
|
||||
List<Pair> {{localVariablePrefix}}queryParams = new ArrayList<Pair>();{{#queryParams}}
|
||||
if ({{paramName}} != null)
|
||||
{{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}}
|
||||
|
||||
Map<String, String> {{localVariablePrefix}}headerParams = new HashMap<String, String>();{{#headerParams}}
|
||||
if ({{paramName}} != null)
|
||||
{{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}}
|
||||
|
||||
Map<String, Object> {{localVariablePrefix}}formParams = new HashMap<String, Object>();{{#formParams}}
|
||||
if ({{paramName}} != null)
|
||||
{{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}});{{/formParams}}
|
||||
|
||||
final String[] {{localVariablePrefix}}accepts = {
|
||||
{{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
|
||||
};
|
||||
final String {{localVariablePrefix}}accept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}accepts);
|
||||
if ({{localVariablePrefix}}accept != null) {{localVariablePrefix}}headerParams.put("Accept", {{localVariablePrefix}}accept);
|
||||
|
||||
final String[] {{localVariablePrefix}}contentTypes = {
|
||||
{{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
|
||||
};
|
||||
final String {{localVariablePrefix}}contentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}contentTypes);
|
||||
{{localVariablePrefix}}headerParams.put("Content-Type", {{localVariablePrefix}}contentType);
|
||||
|
||||
String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
|
||||
return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* {{summary}}
|
||||
* {{notes}}{{#allParams}}
|
||||
* @param {{paramName}} {{description}}{{/allParams}}{{#returnType}}
|
||||
* @return {{{returnType}}}{{/returnType}}
|
||||
*/
|
||||
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
|
||||
Call {{localVariablePrefix}}call = {{nickname}}Call({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
|
||||
{{#returnType}}Type {{localVariablePrefix}}returnType = new TypeToken<{{{returnType}}}>(){}.getType();
|
||||
return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}returnType);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}}
|
||||
}
|
||||
|
||||
/**
|
||||
* {{summary}} (asynchronously)
|
||||
* {{notes}}{{#allParams}}
|
||||
* @param {{paramName}} {{description}}{{/allParams}}
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call {{nickname}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException {
|
||||
Call {{localVariablePrefix}}call = {{nickname}}Call({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
|
||||
{{#returnType}}Type {{localVariablePrefix}}returnType = new TypeToken<{{{returnType}}}>(){}.getType();
|
||||
{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}returnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}}
|
||||
return {{localVariablePrefix}}call;
|
||||
}
|
||||
{{/operation}}
|
||||
}
|
||||
{{/operations}}
|
@ -0,0 +1,41 @@
|
||||
package {{invokerPackage}}.auth;
|
||||
|
||||
import {{invokerPackage}}.Pair;
|
||||
|
||||
import com.migcomponents.migbase64.Base64;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
public class HttpBasicAuth implements Authentication {
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
|
||||
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
|
||||
try {
|
||||
headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
apply plugin: 'java'
|
||||
apply plugin: 'maven'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile 'io.swagger:swagger-annotations:1.5.0'
|
||||
compile 'com.squareup.okhttp:okhttp:2.4.0'
|
||||
compile 'com.google.code.gson:gson:2.3.1'
|
||||
compile 'com.brsanthu:migbase64:2.2'
|
||||
testCompile 'junit:junit:4.8.1'
|
||||
}
|
||||
|
||||
group = '{{groupId}}'
|
||||
version = '{{artifactVersion}}'
|
||||
|
||||
install {
|
||||
repositories.mavenInstaller {
|
||||
pom.artifactId = '{{artifactId}}'
|
||||
}
|
||||
}
|
||||
|
||||
task execute(type:JavaExec) {
|
||||
main = System.getProperty('mainClass')
|
||||
classpath = sourceSets.main.runtimeClasspath
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
lazy val root = (project in file(".")).
|
||||
settings(
|
||||
organization := "{{groupId}}",
|
||||
name := "{{artifactId}}",
|
||||
version := "{{artifactVersion}}",
|
||||
scalaVersion := "2.11.4",
|
||||
scalacOptions ++= Seq("-feature"),
|
||||
javacOptions in compile ++= Seq("-Xlint:deprecation"),
|
||||
publishArtifact in (Compile, packageDoc) := false,
|
||||
resolvers += Resolver.mavenLocal,
|
||||
libraryDependencies ++= Seq(
|
||||
"io.swagger" % "swagger-annotations" % "1.5.0",
|
||||
"com.squareup.okhttp" % "okhttp" % "2.4.0",
|
||||
"com.google.code.gson" % "gson" % "2.3.1",
|
||||
"com.brsanthu" % "migbase64" % "2.2",
|
||||
"junit" % "junit" % "4.8.1" % "test"
|
||||
)
|
||||
)
|
@ -0,0 +1,17 @@
|
||||
public enum {{datatypeWithEnum}} {
|
||||
{{#allowableValues}}{{#enumVars}}@SerializedName("{{value}}")
|
||||
{{name}}("{{value}}"){{^-last}},
|
||||
|
||||
{{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}}
|
||||
|
||||
private String value;
|
||||
|
||||
StatusEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return value;
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
package {{package}};
|
||||
|
||||
import {{invokerPackage}}.StringUtil;
|
||||
{{#imports}}import {{import}};
|
||||
{{/imports}}
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
{{#serializableModel}}
|
||||
import java.io.Serializable;{{/serializableModel}}
|
||||
|
||||
import io.swagger.annotations.*;
|
||||
|
||||
{{#models}}
|
||||
|
||||
{{#model}}{{#description}}
|
||||
/**
|
||||
* {{description}}
|
||||
**/{{/description}}
|
||||
@ApiModel(description = "{{{description}}}")
|
||||
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} {
|
||||
{{#vars}}{{#isEnum}}
|
||||
|
||||
{{>libraries/okhttp-gson/enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}}
|
||||
|
||||
{{>libraries/okhttp-gson/enumClass}}{{/items}}{{/items.isEnum}}
|
||||
@SerializedName("{{baseName}}")
|
||||
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};
|
||||
{{/vars}}
|
||||
|
||||
{{#vars}}
|
||||
/**{{#description}}
|
||||
* {{{description}}}{{/description}}{{#minimum}}
|
||||
* minimum: {{minimum}}{{/minimum}}{{#maximum}}
|
||||
* maximum: {{maximum}}{{/maximum}}
|
||||
**/
|
||||
@ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}")
|
||||
public {{{datatypeWithEnum}}} {{getter}}() {
|
||||
return {{name}};
|
||||
}
|
||||
public void {{setter}}({{{datatypeWithEnum}}} {{name}}) {
|
||||
this.{{name}} = {{name}};
|
||||
}
|
||||
|
||||
{{/vars}}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class {{classname}} {\n");
|
||||
{{#parent}}sb.append(" ").append(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}}
|
||||
{{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n");
|
||||
{{/vars}}sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
{{/model}}
|
||||
{{/models}}
|
@ -0,0 +1,146 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>{{groupId}}</groupId>
|
||||
<artifactId>{{artifactId}}</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>{{artifactId}}</name>
|
||||
<version>{{artifactVersion}}</version>
|
||||
<scm>
|
||||
<connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection>
|
||||
<developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection>
|
||||
<url>https://github.com/swagger-api/swagger-codegen</url>
|
||||
</scm>
|
||||
<prerequisites>
|
||||
<maven>2.2.0</maven>
|
||||
</prerequisites>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.12</version>
|
||||
<configuration>
|
||||
<systemProperties>
|
||||
<property>
|
||||
<name>loggerPath</name>
|
||||
<value>conf/log4j.properties</value>
|
||||
</property>
|
||||
</systemProperties>
|
||||
<argLine>-Xms512m -Xmx1500m</argLine>
|
||||
<parallel>methods</parallel>
|
||||
<forkMode>pertest</forkMode>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/lib</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!-- attach test jar -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>2.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
<goal>test-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add_sources</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/main/java</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>add_test_sources</id>
|
||||
<phase>generate-test-sources</phase>
|
||||
<goals>
|
||||
<goal>add-test-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/test/java</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>2.3.2</version>
|
||||
<configuration>
|
||||
<source>1.6</source>
|
||||
<target>1.6</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
<version>${swagger-annotations-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>${okhttp-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.brsanthu</groupId>
|
||||
<artifactId>migbase64</artifactId>
|
||||
<version>2.2</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test dependencies -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit-version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<swagger-annotations-version>1.5.0</swagger-annotations-version>
|
||||
<okhttp-version>2.4.0</okhttp-version>
|
||||
<gson-version>2.3.1</gson-version>
|
||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
||||
<junit-version>4.8.1</junit-version>
|
||||
</properties>
|
||||
</project>
|
@ -1,5 +1,6 @@
|
||||
package {{package}};
|
||||
|
||||
import {{invokerPackage}}.StringUtil;
|
||||
{{#imports}}import {{import}};
|
||||
{{/imports}}
|
||||
|
||||
@ -45,9 +46,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class {{classname}} {\n");
|
||||
{{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}}
|
||||
{{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n");
|
||||
{{/vars}}sb.append("}\n");
|
||||
{{#parent}}sb.append(" ").append(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}}
|
||||
{{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n");
|
||||
{{/vars}}sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
17
pom.xml
17
pom.xml
@ -328,6 +328,18 @@
|
||||
<module>samples/client/petstore/java/jersey2</module>
|
||||
</modules>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>java-client-okhttp-gson</id>
|
||||
<activation>
|
||||
<property>
|
||||
<name>env</name>
|
||||
<value>java</value>
|
||||
</property>
|
||||
</activation>
|
||||
<modules>
|
||||
<module>samples/client/petstore/java/okhttp-gson</module>
|
||||
</modules>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>scala-client</id>
|
||||
<activation>
|
||||
@ -412,6 +424,7 @@
|
||||
<module>samples/client/petstore/android-java</module>
|
||||
<module>samples/client/petstore/java/default</module>
|
||||
<module>samples/client/petstore/java/jersey2</module>
|
||||
<module>samples/client/petstore/java/okhttp-gson</module>
|
||||
<module>samples/client/petstore/scala</module>
|
||||
<module>samples/server/petstore/spring-mvc</module>
|
||||
<!--module>samples/client/petstore/objc</module-->
|
||||
@ -502,10 +515,10 @@
|
||||
</repository>
|
||||
</repositories>
|
||||
<properties>
|
||||
<swagger-parser-version>1.0.10</swagger-parser-version>
|
||||
<swagger-parser-version>1.0.11-SNAPSHOT</swagger-parser-version>
|
||||
<scala-version>2.11.1</scala-version>
|
||||
<felix-version>2.3.4</felix-version>
|
||||
<swagger-core-version>1.5.3</swagger-core-version>
|
||||
<swagger-core-version>1.5.4-SNAPSHOT</swagger-core-version>
|
||||
<scala-test-version>2.1.4</scala-test-version>
|
||||
<commons-io-version>2.3</commons-io-version>
|
||||
<commons-cli-version>1.2</commons-cli-version>
|
||||
|
28
samples/client/petstore/java/okhttp-gson/build.gradle
Normal file
28
samples/client/petstore/java/okhttp-gson/build.gradle
Normal file
@ -0,0 +1,28 @@
|
||||
apply plugin: 'java'
|
||||
apply plugin: 'maven'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile 'io.swagger:swagger-annotations:1.5.0'
|
||||
compile 'com.squareup.okhttp:okhttp:2.4.0'
|
||||
compile 'com.google.code.gson:gson:2.3.1'
|
||||
compile 'com.brsanthu:migbase64:2.2'
|
||||
testCompile 'junit:junit:4.8.1'
|
||||
}
|
||||
|
||||
group = 'io.swagger'
|
||||
version = '1.0.0'
|
||||
|
||||
install {
|
||||
repositories.mavenInstaller {
|
||||
pom.artifactId = 'swagger-petstore-okhttp-gson'
|
||||
}
|
||||
}
|
||||
|
||||
task execute(type:JavaExec) {
|
||||
main = System.getProperty('mainClass')
|
||||
classpath = sourceSets.main.runtimeClasspath
|
||||
}
|
18
samples/client/petstore/java/okhttp-gson/build.sbt
Normal file
18
samples/client/petstore/java/okhttp-gson/build.sbt
Normal file
@ -0,0 +1,18 @@
|
||||
lazy val root = (project in file(".")).
|
||||
settings(
|
||||
organization := "io.swagger",
|
||||
name := "swagger-petstore-okhttp-gson",
|
||||
version := "1.0.0",
|
||||
scalaVersion := "2.11.4",
|
||||
scalacOptions ++= Seq("-feature"),
|
||||
javacOptions in compile ++= Seq("-Xlint:deprecation"),
|
||||
publishArtifact in (Compile, packageDoc) := false,
|
||||
resolvers += Resolver.mavenLocal,
|
||||
libraryDependencies ++= Seq(
|
||||
"io.swagger" % "swagger-annotations" % "1.5.0",
|
||||
"com.squareup.okhttp" % "okhttp" % "2.4.0",
|
||||
"com.google.code.gson" % "gson" % "2.3.1",
|
||||
"com.brsanthu" % "migbase64" % "2.2",
|
||||
"junit" % "junit" % "4.8.1" % "test"
|
||||
)
|
||||
)
|
1
samples/client/petstore/java/okhttp-gson/hello.txt
Normal file
1
samples/client/petstore/java/okhttp-gson/hello.txt
Normal file
@ -0,0 +1 @@
|
||||
Hello world!
|
146
samples/client/petstore/java/okhttp-gson/pom.xml
Normal file
146
samples/client/petstore/java/okhttp-gson/pom.xml
Normal file
@ -0,0 +1,146 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-petstore-okhttp-gson</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>swagger-petstore-okhttp-gson</name>
|
||||
<version>1.0.0</version>
|
||||
<scm>
|
||||
<connection>scm:git:git@github.com:swagger-api/swagger-mustache.git</connection>
|
||||
<developerConnection>scm:git:git@github.com:swagger-api/swagger-codegen.git</developerConnection>
|
||||
<url>https://github.com/swagger-api/swagger-codegen</url>
|
||||
</scm>
|
||||
<prerequisites>
|
||||
<maven>2.2.0</maven>
|
||||
</prerequisites>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.12</version>
|
||||
<configuration>
|
||||
<systemProperties>
|
||||
<property>
|
||||
<name>loggerPath</name>
|
||||
<value>conf/log4j.properties</value>
|
||||
</property>
|
||||
</systemProperties>
|
||||
<argLine>-Xms512m -Xmx1500m</argLine>
|
||||
<parallel>methods</parallel>
|
||||
<forkMode>pertest</forkMode>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/lib</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<!-- attach test jar -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>2.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
<goal>test-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>add_sources</id>
|
||||
<phase>generate-sources</phase>
|
||||
<goals>
|
||||
<goal>add-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/main/java</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>add_test_sources</id>
|
||||
<phase>generate-test-sources</phase>
|
||||
<goals>
|
||||
<goal>add-test-source</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/test/java</source>
|
||||
</sources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>2.3.2</version>
|
||||
<configuration>
|
||||
<source>1.6</source>
|
||||
<target>1.6</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
<version>${swagger-annotations-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp</groupId>
|
||||
<artifactId>okhttp</artifactId>
|
||||
<version>${okhttp-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>${gson-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.brsanthu</groupId>
|
||||
<artifactId>migbase64</artifactId>
|
||||
<version>2.2</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test dependencies -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit-version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<swagger-annotations-version>1.5.0</swagger-annotations-version>
|
||||
<okhttp-version>2.4.0</okhttp-version>
|
||||
<gson-version>2.3.1</gson-version>
|
||||
<maven-plugin-version>1.0.0</maven-plugin-version>
|
||||
<junit-version>4.8.1</junit-version>
|
||||
</properties>
|
||||
</project>
|
@ -0,0 +1,22 @@
|
||||
package io.swagger.client;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Callback for asynchronous API call.
|
||||
*
|
||||
* @param <T> The return type
|
||||
*/
|
||||
public interface ApiCallback<T> {
|
||||
/**
|
||||
* This is called when the API call fails.
|
||||
*/
|
||||
void onFailure(ApiException e);
|
||||
|
||||
/**
|
||||
* This is called when the API call succeeded.
|
||||
*
|
||||
* @param result The result deserialized from response
|
||||
*/
|
||||
void onSuccess(T result);
|
||||
}
|
@ -0,0 +1,761 @@
|
||||
package io.swagger.client;
|
||||
|
||||
import com.squareup.okhttp.Call;
|
||||
import com.squareup.okhttp.Callback;
|
||||
import com.squareup.okhttp.OkHttpClient;
|
||||
import com.squareup.okhttp.Request;
|
||||
import com.squareup.okhttp.Response;
|
||||
import com.squareup.okhttp.RequestBody;
|
||||
import com.squareup.okhttp.FormEncodingBuilder;
|
||||
import com.squareup.okhttp.MultipartBuilder;
|
||||
import com.squareup.okhttp.MediaType;
|
||||
import com.squareup.okhttp.Headers;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.net.URLConnection;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.text.ParseException;
|
||||
|
||||
import io.swagger.client.auth.Authentication;
|
||||
import io.swagger.client.auth.HttpBasicAuth;
|
||||
import io.swagger.client.auth.ApiKeyAuth;
|
||||
import io.swagger.client.auth.OAuth;
|
||||
|
||||
public class ApiClient {
|
||||
private String basePath = "http://petstore.swagger.io/v2";
|
||||
private boolean lenientOnJson = false;
|
||||
private boolean debugging = false;
|
||||
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
|
||||
|
||||
private Map<String, Authentication> authentications;
|
||||
|
||||
private String dateFormat;
|
||||
private DateFormat dateFormatter;
|
||||
private int dateLength;
|
||||
|
||||
private String datetimeFormat;
|
||||
private DateFormat datetimeFormatter;
|
||||
|
||||
private OkHttpClient httpClient;
|
||||
private JSON json;
|
||||
|
||||
public ApiClient() {
|
||||
httpClient = new OkHttpClient();
|
||||
|
||||
json = new JSON(this);
|
||||
|
||||
// Use ISO 8601 format for date and datetime.
|
||||
// See https://en.wikipedia.org/wiki/ISO_8601
|
||||
setDateFormat("yyyy-MM-dd");
|
||||
setDatetimeFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
|
||||
|
||||
// Set default User-Agent.
|
||||
setUserAgent("Java-Swagger");
|
||||
|
||||
// Setup authentications (key: authentication name, value: authentication).
|
||||
authentications = new HashMap<String, Authentication>();
|
||||
authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
|
||||
authentications.put("petstore_auth", new OAuth());
|
||||
// Prevent the authentications from being modified.
|
||||
authentications = Collections.unmodifiableMap(authentications);
|
||||
}
|
||||
|
||||
public String getBasePath() {
|
||||
return basePath;
|
||||
}
|
||||
|
||||
public ApiClient setBasePath(String basePath) {
|
||||
this.basePath = basePath;
|
||||
return this;
|
||||
}
|
||||
|
||||
public OkHttpClient getHttpClient() {
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
public ApiClient setHttpClient(OkHttpClient httpClient) {
|
||||
this.httpClient = httpClient;
|
||||
return this;
|
||||
}
|
||||
|
||||
public JSON getJSON() {
|
||||
return json;
|
||||
}
|
||||
|
||||
public ApiClient setJSON(JSON json) {
|
||||
this.json = json;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDateFormat() {
|
||||
return dateFormat;
|
||||
}
|
||||
|
||||
public ApiClient setDateFormat(String dateFormat) {
|
||||
this.dateFormat = dateFormat;
|
||||
|
||||
this.dateFormatter = new SimpleDateFormat(dateFormat);
|
||||
// Use UTC as the default time zone.
|
||||
this.dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
this.dateLength = this.dateFormatter.format(new Date()).length();
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDatetimeFormat() {
|
||||
return datetimeFormat;
|
||||
}
|
||||
|
||||
public ApiClient setDatetimeFormat(String datetimeFormat) {
|
||||
this.datetimeFormat = datetimeFormat;
|
||||
|
||||
this.datetimeFormatter = new SimpleDateFormat(datetimeFormat);
|
||||
// Note: The datetime formatter uses the system's default time zone.
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the given date string into Date object.
|
||||
* The default <code>dateFormat</code> supports these ISO 8601 date formats:
|
||||
* 2015-08-16
|
||||
* 2015-8-16
|
||||
*/
|
||||
public Date parseDate(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
try {
|
||||
return dateFormatter.parse(str);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the given date-time string into Date object.
|
||||
* The default <code>datetimeFormat</code> supports these ISO 8601 datetime formats:
|
||||
* 2015-08-16T08:20:05Z
|
||||
* 2015-8-16T8:20:05Z
|
||||
* 2015-08-16T08:20:05+00:00
|
||||
* 2015-08-16T08:20:05+0000
|
||||
* 2015-08-16T08:20:05.376Z
|
||||
* 2015-08-16T08:20:05.376+00:00
|
||||
* 2015-08-16T08:20:05.376+00
|
||||
* Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of
|
||||
* these formats:
|
||||
* Z (same with +0000)
|
||||
* +08:00 (same with +0800)
|
||||
* -02 (same with -0200)
|
||||
* -0200
|
||||
* @see https://en.wikipedia.org/wiki/ISO_8601
|
||||
*/
|
||||
public Date parseDatetime(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
|
||||
if ("yyyy-MM-dd'T'HH:mm:ss.SSSZ".equals(datetimeFormat)) {
|
||||
/*
|
||||
* When the default datetime format is used, process the given string
|
||||
* to support various formats defined by ISO 8601.
|
||||
*/
|
||||
// normalize time zone
|
||||
// trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000
|
||||
str = str.replaceAll("[zZ]\\z", "+0000");
|
||||
// remove colon: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000
|
||||
str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2");
|
||||
// expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000
|
||||
str = str.replaceAll("([+-]\\d{2})\\z", "$100");
|
||||
// add milliseconds when missing
|
||||
// 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000
|
||||
str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2");
|
||||
}
|
||||
|
||||
try {
|
||||
return datetimeFormatter.parse(str);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public Date parseDateOrDatetime(String str) {
|
||||
if (str == null)
|
||||
return null;
|
||||
else if (str.length() <= dateLength)
|
||||
return parseDate(str);
|
||||
else
|
||||
return parseDatetime(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given Date object into string.
|
||||
*/
|
||||
public String formatDate(Date date) {
|
||||
return dateFormatter.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given Date object into string.
|
||||
*/
|
||||
public String formatDatetime(Date date) {
|
||||
return datetimeFormatter.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get authentications (key: authentication name, value: authentication).
|
||||
*/
|
||||
public Map<String, Authentication> getAuthentications() {
|
||||
return authentications;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get authentication for the given name.
|
||||
*
|
||||
* @param authName The authentication name
|
||||
* @return The authentication, null if not found
|
||||
*/
|
||||
public Authentication getAuthentication(String authName) {
|
||||
return authentications.get(authName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set username for the first HTTP basic authentication.
|
||||
*/
|
||||
public void setUsername(String username) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof HttpBasicAuth) {
|
||||
((HttpBasicAuth) auth).setUsername(username);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set password for the first HTTP basic authentication.
|
||||
*/
|
||||
public void setPassword(String password) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof HttpBasicAuth) {
|
||||
((HttpBasicAuth) auth).setPassword(password);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No HTTP basic authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set API key value for the first API key authentication.
|
||||
*/
|
||||
public void setApiKey(String apiKey) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof ApiKeyAuth) {
|
||||
((ApiKeyAuth) auth).setApiKey(apiKey);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No API key authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to set API key prefix for the first API key authentication.
|
||||
*/
|
||||
public void setApiKeyPrefix(String apiKeyPrefix) {
|
||||
for (Authentication auth : authentications.values()) {
|
||||
if (auth instanceof ApiKeyAuth) {
|
||||
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No API key authentication configured!");
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the User-Agent header's value (by adding to the default header map).
|
||||
*/
|
||||
public ApiClient setUserAgent(String userAgent) {
|
||||
addDefaultHeader("User-Agent", userAgent);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a default header.
|
||||
*
|
||||
* @param key The header's key
|
||||
* @param value The header's value
|
||||
*/
|
||||
public ApiClient addDefaultHeader(String key, String value) {
|
||||
defaultHeaderMap.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
|
||||
*/
|
||||
public boolean isLenientOnJson() {
|
||||
return lenientOnJson;
|
||||
}
|
||||
|
||||
public ApiClient setLenientOnJson(boolean lenient) {
|
||||
this.lenientOnJson = lenient;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that whether debugging is enabled for this API client.
|
||||
*/
|
||||
public boolean isDebugging() {
|
||||
return debugging;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable/disable debugging for this API client.
|
||||
*
|
||||
* @param debugging To enable (true) or disable (false) debugging
|
||||
*/
|
||||
public ApiClient setDebugging(boolean debugging) {
|
||||
this.debugging = debugging;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given parameter object into string.
|
||||
*/
|
||||
public String parameterToString(Object param) {
|
||||
if (param == null) {
|
||||
return "";
|
||||
} else if (param instanceof Date) {
|
||||
return formatDatetime((Date) param);
|
||||
} else if (param instanceof Collection) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
for (Object o : (Collection)param) {
|
||||
if (b.length() > 0) {
|
||||
b.append(",");
|
||||
}
|
||||
b.append(String.valueOf(o));
|
||||
}
|
||||
return b.toString();
|
||||
} else {
|
||||
return String.valueOf(param);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Format to {@code Pair} objects.
|
||||
*/
|
||||
public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
|
||||
List<Pair> params = new ArrayList<Pair>();
|
||||
|
||||
// preconditions
|
||||
if (name == null || name.isEmpty() || value == null) return params;
|
||||
|
||||
Collection valueCollection = null;
|
||||
if (value instanceof Collection) {
|
||||
valueCollection = (Collection) value;
|
||||
} else {
|
||||
params.add(new Pair(name, parameterToString(value)));
|
||||
return params;
|
||||
}
|
||||
|
||||
if (valueCollection.isEmpty()){
|
||||
return params;
|
||||
}
|
||||
|
||||
// get the collection format
|
||||
collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
|
||||
|
||||
// create the params based on the collection format
|
||||
if (collectionFormat.equals("multi")) {
|
||||
for (Object item : valueCollection) {
|
||||
params.add(new Pair(name, parameterToString(item)));
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
String delimiter = ",";
|
||||
|
||||
if (collectionFormat.equals("csv")) {
|
||||
delimiter = ",";
|
||||
} else if (collectionFormat.equals("ssv")) {
|
||||
delimiter = " ";
|
||||
} else if (collectionFormat.equals("tsv")) {
|
||||
delimiter = "\t";
|
||||
} else if (collectionFormat.equals("pipes")) {
|
||||
delimiter = "|";
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder() ;
|
||||
for (Object item : valueCollection) {
|
||||
sb.append(delimiter);
|
||||
sb.append(parameterToString(item));
|
||||
}
|
||||
|
||||
params.add(new Pair(name, sb.substring(1)));
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the Accept header's value from the given accepts array:
|
||||
* if JSON exists in the given array, use it;
|
||||
* otherwise use all of them (joining into a string)
|
||||
*
|
||||
* @param accepts The accepts array to select from
|
||||
* @return The Accept header to use. If the given array is empty,
|
||||
* null will be returned (not to set the Accept header explicitly).
|
||||
*/
|
||||
public String selectHeaderAccept(String[] accepts) {
|
||||
if (accepts.length == 0) return null;
|
||||
if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json";
|
||||
return StringUtil.join(accepts, ",");
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the Content-Type header's value from the given array:
|
||||
* if JSON exists in the given array, use it;
|
||||
* otherwise use the first one of the array.
|
||||
*
|
||||
* @param contentTypes The Content-Type array to select from
|
||||
* @return The Content-Type header to use. If the given array is empty,
|
||||
* JSON will be used.
|
||||
*/
|
||||
public String selectHeaderContentType(String[] contentTypes) {
|
||||
if (contentTypes.length == 0) return "application/json";
|
||||
if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json";
|
||||
return contentTypes[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape the given string to be used as URL query value.
|
||||
*/
|
||||
public String escapeString(String str) {
|
||||
try {
|
||||
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize response body to Java object, according the Content-Type
|
||||
* response header.
|
||||
*
|
||||
* @param response HTTP response
|
||||
* @param returnType The type of the Java object
|
||||
* @return The deserialized Java object
|
||||
*/
|
||||
public <T> T deserialize(Response response, Type returnType) throws ApiException {
|
||||
if (response == null || returnType == null)
|
||||
return null;
|
||||
|
||||
String respBody;
|
||||
try {
|
||||
if (response.body() != null)
|
||||
respBody = response.body().string();
|
||||
else
|
||||
respBody = null;
|
||||
} catch (IOException e) {
|
||||
throw new ApiException(e);
|
||||
}
|
||||
|
||||
if (respBody == null || "".equals(respBody))
|
||||
return null;
|
||||
|
||||
String contentType = response.headers().get("Content-Type");
|
||||
if (contentType == null) {
|
||||
// ensuring a default content type
|
||||
contentType = "application/json";
|
||||
}
|
||||
if (contentType.startsWith("application/json")) {
|
||||
return json.deserialize(respBody, returnType);
|
||||
} else {
|
||||
throw new ApiException(
|
||||
"Content type \"" + contentType + "\" is not supported",
|
||||
response.code(),
|
||||
response.headers().toMultimap(),
|
||||
respBody);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the given Java object into request body string, according to the
|
||||
* request Content-Type.
|
||||
*
|
||||
* @param obj The Java object
|
||||
* @param contentType The request Content-Type
|
||||
* @return The serialized string
|
||||
*/
|
||||
public String serialize(Object obj, String contentType) throws ApiException {
|
||||
if (contentType.startsWith("application/json")) {
|
||||
if (obj != null)
|
||||
return json.serialize(obj);
|
||||
else
|
||||
return null;
|
||||
} else {
|
||||
throw new ApiException("Content type \"" + contentType + "\" is not supported");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see #execute(Call, Type)
|
||||
*/
|
||||
public <T> T execute(Call call) throws ApiException {
|
||||
return execute(call, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute HTTP call and deserialize the HTTP response body into the given return type.
|
||||
*
|
||||
* @param returnType The return type used to deserialize HTTP response body
|
||||
* @param <T> The return type corresponding to (same with) returnType
|
||||
* @return The Java object deserialized from response body. Returns null if returnType is null.
|
||||
*/
|
||||
public <T> T execute(Call call, Type returnType) throws ApiException {
|
||||
try {
|
||||
Response response = call.execute();
|
||||
return handleResponse(response, returnType);
|
||||
} catch (IOException e) {
|
||||
throw new ApiException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* #see executeAsync(Call, Type, ApiCallback)
|
||||
*/
|
||||
public <T> void executeAsync(Call call, ApiCallback<T> callback) throws ApiException {
|
||||
executeAsync(call, null, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute HTTP call asynchronously.
|
||||
*
|
||||
* @see #execute(Call, Type)
|
||||
* @param The callback to be executed when the API call finishes
|
||||
*/
|
||||
public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) {
|
||||
call.enqueue(new Callback() {
|
||||
@Override
|
||||
public void onFailure(Request request, IOException e) {
|
||||
callback.onFailure(new ApiException(e));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResponse(Response response) throws IOException {
|
||||
T result;
|
||||
try {
|
||||
result = (T) handleResponse(response, returnType);
|
||||
} catch (ApiException e) {
|
||||
callback.onFailure(e);
|
||||
return;
|
||||
}
|
||||
callback.onSuccess(result);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public <T> T handleResponse(Response response, Type returnType) throws ApiException {
|
||||
if (response.isSuccessful()) {
|
||||
if (returnType == null || response.code() == 204) {
|
||||
// returning null if the returnType is not defined,
|
||||
// or the status code is 204 (No Content)
|
||||
return null;
|
||||
} else {
|
||||
return deserialize(response, returnType);
|
||||
}
|
||||
} else {
|
||||
String respBody = null;
|
||||
if (response.body() != null) {
|
||||
try {
|
||||
respBody = response.body().string();
|
||||
} catch (IOException e) {
|
||||
throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
|
||||
}
|
||||
}
|
||||
throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build HTTP call with the given options.
|
||||
*
|
||||
* @param path The sub-path of the HTTP URL
|
||||
* @param method The request method, one of "GET", "HEAD", "POST", "PUT", "PATCH" and "DELETE"
|
||||
* @param queryParams The query parameters
|
||||
* @param body The request body object
|
||||
* @param headerParams The header parameters
|
||||
* @param formParams The form parameters
|
||||
* @param authNames The authentications to apply
|
||||
* @return The HTTP call
|
||||
*/
|
||||
public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames) throws ApiException {
|
||||
updateParamsForAuth(authNames, queryParams, headerParams);
|
||||
|
||||
final String url = buildUrl(path, queryParams);
|
||||
final Request.Builder reqBuilder = new Request.Builder().url(url);
|
||||
processHeaderParams(headerParams, reqBuilder);
|
||||
|
||||
String contentType = (String) headerParams.get("Content-Type");
|
||||
// ensuring a default content type
|
||||
if (contentType == null) contentType = "application/json";
|
||||
|
||||
RequestBody reqBody;
|
||||
if ("GET".equals(method) || "HEAD".equals(method)) {
|
||||
reqBody = null;
|
||||
} else if ("application/x-www-form-urlencoded".equals(contentType)) {
|
||||
reqBody = buildRequestBodyFormEncoding(formParams);
|
||||
} else if ("multipart/form-data".equals(contentType)) {
|
||||
reqBody = buildRequestBodyMultipart(formParams);
|
||||
} else if (body == null) {
|
||||
if ("DELETE".equals(method)) {
|
||||
// allow calling DELETE without sending a request body
|
||||
reqBody = null;
|
||||
} else {
|
||||
// use an empty request body (for POST, PUT and PATCH)
|
||||
reqBody = RequestBody.create(MediaType.parse(contentType), "");
|
||||
}
|
||||
} else {
|
||||
reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType));
|
||||
}
|
||||
|
||||
Request request;
|
||||
if ("GET".equals(method)) {
|
||||
request = reqBuilder.get().build();
|
||||
} else if ("HEAD".equals(method)) {
|
||||
request = reqBuilder.head().build();
|
||||
} else if ("POST".equals(method)) {
|
||||
request = reqBuilder.post(reqBody).build();
|
||||
} else if ("PUT".equals(method)) {
|
||||
request = reqBuilder.put(reqBody).build();
|
||||
} else if ("PATCH".equals(method)) {
|
||||
request = reqBuilder.patch(reqBody).build();
|
||||
} else if ("DELETE".equals(method)) {
|
||||
if (reqBody == null) {
|
||||
// calling DELETE without sending a request body
|
||||
request = reqBuilder.delete().build();
|
||||
} else {
|
||||
request = reqBuilder.delete(reqBody).build();
|
||||
}
|
||||
} else {
|
||||
throw new ApiException("unknown method type: " + method);
|
||||
}
|
||||
|
||||
return httpClient.newCall(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build full URL by concatenating base path, the given sub path and query parameters.
|
||||
*
|
||||
* @param path The sub path
|
||||
* @param queryParams The query parameters
|
||||
* @return The full URL
|
||||
*/
|
||||
public String buildUrl(String path, List<Pair> queryParams) {
|
||||
StringBuilder query = new StringBuilder();
|
||||
if (queryParams != null) {
|
||||
for (Pair param : queryParams) {
|
||||
if (param.getValue() != null) {
|
||||
if (query.toString().length() == 0)
|
||||
query.append("?");
|
||||
else
|
||||
query.append("&");
|
||||
String value = parameterToString(param.getValue());
|
||||
query.append(escapeString(param.getName())).append("=").append(escapeString(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
return basePath + path + query.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set header parameters to the request builder, including default headers.
|
||||
*/
|
||||
public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) {
|
||||
for (Entry<String, String> param : headerParams.entrySet()) {
|
||||
reqBuilder.header(param.getKey(), parameterToString(param.getValue()));
|
||||
}
|
||||
for (Entry<String, String> header : defaultHeaderMap.entrySet()) {
|
||||
if (!headerParams.containsKey(header.getKey())) {
|
||||
reqBuilder.header(header.getKey(), parameterToString(header.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update query and header parameters based on authentication settings.
|
||||
*
|
||||
* @param authNames The authentications to apply
|
||||
*/
|
||||
public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
|
||||
for (String authName : authNames) {
|
||||
Authentication auth = authentications.get(authName);
|
||||
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
|
||||
auth.applyToParams(queryParams, headerParams);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a form-encoding request body with the given form parameters.
|
||||
*/
|
||||
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
|
||||
FormEncodingBuilder formBuilder = new FormEncodingBuilder();
|
||||
for (Entry<String, Object> param : formParams.entrySet()) {
|
||||
formBuilder.add(param.getKey(), parameterToString(param.getValue()));
|
||||
}
|
||||
return formBuilder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a multipart (file uploading) request body with the given form parameters,
|
||||
* which could contain text fields and file fields.
|
||||
*/
|
||||
public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) {
|
||||
MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
|
||||
for (Entry<String, Object> param : formParams.entrySet()) {
|
||||
if (param.getValue() instanceof File) {
|
||||
File file = (File) param.getValue();
|
||||
Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\"");
|
||||
MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
|
||||
mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file));
|
||||
} else {
|
||||
Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"");
|
||||
mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue())));
|
||||
}
|
||||
}
|
||||
return mpBuilder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Guess Content-Type header from the given file (defaults to "application/octet-stream").
|
||||
*
|
||||
* @param file The given file
|
||||
* @return The Content-Type guessed
|
||||
*/
|
||||
public String guessContentTypeFromFile(File file) {
|
||||
String contentType = URLConnection.guessContentTypeFromName(file.getName());
|
||||
if (contentType == null) {
|
||||
return "application/octet-stream";
|
||||
} else {
|
||||
return contentType;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
package io.swagger.client;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00")
|
||||
public class ApiException extends Exception {
|
||||
private int code = 0;
|
||||
private Map<String, List<String>> responseHeaders = null;
|
||||
private String responseBody = null;
|
||||
|
||||
public ApiException() {}
|
||||
|
||||
public ApiException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
|
||||
public ApiException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) {
|
||||
super(message, throwable);
|
||||
this.code = code;
|
||||
this.responseHeaders = responseHeaders;
|
||||
this.responseBody = responseBody;
|
||||
}
|
||||
|
||||
public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) {
|
||||
this(message, (Throwable) null, code, responseHeaders, responseBody);
|
||||
}
|
||||
|
||||
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) {
|
||||
this(message, throwable, code, responseHeaders, null);
|
||||
}
|
||||
|
||||
public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) {
|
||||
this((String) null, (Throwable) null, code, responseHeaders, responseBody);
|
||||
}
|
||||
|
||||
public ApiException(int code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
|
||||
this(code, message);
|
||||
this.responseHeaders = responseHeaders;
|
||||
this.responseBody = responseBody;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the HTTP response headers.
|
||||
*/
|
||||
public Map<String, List<String>> getResponseHeaders() {
|
||||
return responseHeaders;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the HTTP response body.
|
||||
*/
|
||||
public String getResponseBody() {
|
||||
return responseBody;
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package io.swagger.client;
|
||||
|
||||
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00")
|
||||
public class Configuration {
|
||||
private static ApiClient defaultApiClient = new ApiClient();
|
||||
|
||||
/**
|
||||
* Get the default API client, which would be used when creating API
|
||||
* instances without providing an API client.
|
||||
*/
|
||||
public static ApiClient getDefaultApiClient() {
|
||||
return defaultApiClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the default API client, which would be used when creating API
|
||||
* instances without providing an API client.
|
||||
*/
|
||||
public static void setDefaultApiClient(ApiClient apiClient) {
|
||||
defaultApiClient = apiClient;
|
||||
}
|
||||
}
|
@ -0,0 +1,102 @@
|
||||
package io.swagger.client;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonDeserializer;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonNull;
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.google.gson.JsonSerializationContext;
|
||||
import com.google.gson.JsonSerializer;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
|
||||
import java.io.StringReader;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Date;
|
||||
|
||||
public class JSON {
|
||||
private ApiClient apiClient;
|
||||
private Gson gson;
|
||||
|
||||
public JSON(ApiClient apiClient) {
|
||||
this.apiClient = apiClient;
|
||||
gson = new GsonBuilder()
|
||||
.serializeNulls()
|
||||
.registerTypeAdapter(Date.class, new DateAdapter(apiClient))
|
||||
.create();
|
||||
}
|
||||
|
||||
public Gson getGson() {
|
||||
return gson;
|
||||
}
|
||||
|
||||
public void setGson(Gson gson) {
|
||||
this.gson = gson;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the given Java object into JSON string.
|
||||
*/
|
||||
public String serialize(Object obj) {
|
||||
return gson.toJson(obj);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize the given JSON string to Java object.
|
||||
*
|
||||
* @param body The JSON string
|
||||
* @param returnType The type to deserialize inot
|
||||
* @return The deserialized Java object
|
||||
*/
|
||||
public <T> T deserialize(String body, Type returnType) {
|
||||
try {
|
||||
if (apiClient.isLenientOnJson()) {
|
||||
JsonReader jsonReader = new JsonReader(new StringReader(body));
|
||||
// see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
|
||||
jsonReader.setLenient(true);
|
||||
return gson.fromJson(jsonReader, returnType);
|
||||
} else {
|
||||
return gson.fromJson(body, returnType);
|
||||
}
|
||||
} catch (JsonParseException e) {
|
||||
// Fallback processing when failed to parse JSON form response body:
|
||||
// return the response body string directly for the String return type;
|
||||
// parse response body into date or datetime for the Date return type.
|
||||
if (returnType.equals(String.class))
|
||||
return (T) body;
|
||||
else if (returnType.equals(Date.class))
|
||||
return (T) apiClient.parseDateOrDatetime(body);
|
||||
else throw(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
|
||||
private final ApiClient apiClient;
|
||||
|
||||
public DateAdapter(ApiClient apiClient) {
|
||||
super();
|
||||
this.apiClient = apiClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
|
||||
if (src == null) {
|
||||
return JsonNull.INSTANCE;
|
||||
} else {
|
||||
return new JsonPrimitive(apiClient.formatDatetime(src));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException {
|
||||
String str = json.getAsJsonPrimitive().getAsString();
|
||||
try {
|
||||
return apiClient.parseDateOrDatetime(str);
|
||||
} catch (RuntimeException e) {
|
||||
throw new JsonParseException(e);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,39 @@
|
||||
package io.swagger.client;
|
||||
|
||||
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00")
|
||||
public class Pair {
|
||||
private String name = "";
|
||||
private String value = "";
|
||||
|
||||
public Pair (String name, String value) {
|
||||
setName(name);
|
||||
setValue(value);
|
||||
}
|
||||
|
||||
private void setName(String name) {
|
||||
if (!isValidString(name)) return;
|
||||
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
private void setValue(String value) {
|
||||
if (!isValidString(value)) return;
|
||||
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
private boolean isValidString(String arg) {
|
||||
if (arg == null) return false;
|
||||
if (arg.trim().isEmpty()) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package io.swagger.client;
|
||||
|
||||
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00")
|
||||
public class StringUtil {
|
||||
/**
|
||||
* Check if the given array contains the given value (with case-insensitive comparison).
|
||||
*
|
||||
* @param array The array
|
||||
* @param value The value to search
|
||||
* @return true if the array contains the value
|
||||
*/
|
||||
public static boolean containsIgnoreCase(String[] array, String value) {
|
||||
for (String str : array) {
|
||||
if (value == null && str == null) return true;
|
||||
if (value != null && value.equalsIgnoreCase(str)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Join an array of strings with the given separator.
|
||||
* <p>
|
||||
* Note: This might be replaced by utility method from commons-lang or guava someday
|
||||
* if one of those libraries is added as dependency.
|
||||
* </p>
|
||||
*
|
||||
* @param array The array of strings
|
||||
* @param separator The separator
|
||||
* @return the resulting string
|
||||
*/
|
||||
public static String join(String[] array, String separator) {
|
||||
int len = array.length;
|
||||
if (len == 0) return "";
|
||||
|
||||
StringBuilder out = new StringBuilder();
|
||||
out.append(array[0]);
|
||||
for (int i = 1; i < len; i++) {
|
||||
out.append(separator).append(array[i]);
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the given object to string with each line indented by 4 spaces
|
||||
* (except the first line).
|
||||
*/
|
||||
public static String toIndentedString(Object o) {
|
||||
if (o == null) return "null";
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
@ -0,0 +1,527 @@
|
||||
package io.swagger.client.api;
|
||||
|
||||
import io.swagger.client.ApiCallback;
|
||||
import io.swagger.client.ApiClient;
|
||||
import io.swagger.client.ApiException;
|
||||
import io.swagger.client.Configuration;
|
||||
import io.swagger.client.Pair;
|
||||
|
||||
import io.swagger.client.model.*;
|
||||
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
|
||||
import com.squareup.okhttp.Call;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import io.swagger.client.model.Pet;
|
||||
import java.io.File;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class PetApi {
|
||||
private ApiClient apiClient;
|
||||
|
||||
public PetApi() {
|
||||
this(Configuration.getDefaultApiClient());
|
||||
}
|
||||
|
||||
public PetApi(ApiClient apiClient) {
|
||||
this.apiClient = apiClient;
|
||||
}
|
||||
|
||||
public ApiClient getApiClient() {
|
||||
return apiClient;
|
||||
}
|
||||
|
||||
public void setApiClient(ApiClient apiClient) {
|
||||
this.apiClient = apiClient;
|
||||
}
|
||||
|
||||
|
||||
/* Build call for updatePet */
|
||||
private Call updatePetCall(Pet body) throws ApiException {
|
||||
Object postBody = body;
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/pet".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);
|
||||
|
||||
String[] authNames = new String[] { "petstore_auth" };
|
||||
return apiClient.buildCall(path, "PUT", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing pet
|
||||
*
|
||||
* @param body Pet object that needs to be added to the store
|
||||
*/
|
||||
public void updatePet(Pet body) throws ApiException {
|
||||
Call call = updatePetCall(body);
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing pet (asynchronously)
|
||||
*
|
||||
* @param body Pet object that needs to be added to the store
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call updatePetAsync(Pet body, ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = updatePetCall(body);
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for addPet */
|
||||
private Call addPetCall(Pet body) throws ApiException {
|
||||
Object postBody = body;
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/pet".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);
|
||||
|
||||
String[] authNames = new String[] { "petstore_auth" };
|
||||
return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new pet to the store
|
||||
*
|
||||
* @param body Pet object that needs to be added to the store
|
||||
*/
|
||||
public void addPet(Pet body) throws ApiException {
|
||||
Call call = addPetCall(body);
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new pet to the store (asynchronously)
|
||||
*
|
||||
* @param body Pet object that needs to be added to the store
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call addPetAsync(Pet body, ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = addPetCall(body);
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for findPetsByStatus */
|
||||
private Call findPetsByStatusCall(List<String> status) throws ApiException {
|
||||
Object postBody = null;
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/pet/findByStatus".replaceAll("\\{format\\}","json");
|
||||
|
||||
List<Pair> queryParams = new ArrayList<Pair>();
|
||||
if (status != null)
|
||||
queryParams.addAll(apiClient.parameterToPairs("multi", "status", status));
|
||||
|
||||
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);
|
||||
|
||||
String[] authNames = new String[] { "petstore_auth" };
|
||||
return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds Pets by status
|
||||
* Multiple status values can be provided with comma seperated strings
|
||||
* @param status Status values that need to be considered for filter
|
||||
* @return List<Pet>
|
||||
*/
|
||||
public List<Pet> findPetsByStatus(List<String> status) throws ApiException {
|
||||
Call call = findPetsByStatusCall(status);
|
||||
Type returnType = new TypeToken<List<Pet>>(){}.getType();
|
||||
return apiClient.execute(call, returnType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds Pets by status (asynchronously)
|
||||
* Multiple status values can be provided with comma seperated strings
|
||||
* @param status Status values that need to be considered for filter
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call findPetsByStatusAsync(List<String> status, ApiCallback<List<Pet>> callback) throws ApiException {
|
||||
Call call = findPetsByStatusCall(status);
|
||||
Type returnType = new TypeToken<List<Pet>>(){}.getType();
|
||||
apiClient.executeAsync(call, returnType, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for findPetsByTags */
|
||||
private Call findPetsByTagsCall(List<String> tags) throws ApiException {
|
||||
Object postBody = null;
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/pet/findByTags".replaceAll("\\{format\\}","json");
|
||||
|
||||
List<Pair> queryParams = new ArrayList<Pair>();
|
||||
if (tags != null)
|
||||
queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags));
|
||||
|
||||
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);
|
||||
|
||||
String[] authNames = new String[] { "petstore_auth" };
|
||||
return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds Pets by tags
|
||||
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
|
||||
* @param tags Tags to filter by
|
||||
* @return List<Pet>
|
||||
*/
|
||||
public List<Pet> findPetsByTags(List<String> tags) throws ApiException {
|
||||
Call call = findPetsByTagsCall(tags);
|
||||
Type returnType = new TypeToken<List<Pet>>(){}.getType();
|
||||
return apiClient.execute(call, returnType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds Pets by tags (asynchronously)
|
||||
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
|
||||
* @param tags Tags to filter by
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call findPetsByTagsAsync(List<String> tags, ApiCallback<List<Pet>> callback) throws ApiException {
|
||||
Call call = findPetsByTagsCall(tags);
|
||||
Type returnType = new TypeToken<List<Pet>>(){}.getType();
|
||||
apiClient.executeAsync(call, returnType, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for getPetById */
|
||||
private Call getPetByIdCall(Long petId) 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 getPetById(Async)");
|
||||
}
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/pet/{petId}".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);
|
||||
|
||||
String[] authNames = new String[] { "petstore_auth", "api_key" };
|
||||
return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find pet by ID
|
||||
* Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
|
||||
* @param petId ID of pet that needs to be fetched
|
||||
* @return Pet
|
||||
*/
|
||||
public Pet getPetById(Long petId) throws ApiException {
|
||||
Call call = getPetByIdCall(petId);
|
||||
Type returnType = new TypeToken<Pet>(){}.getType();
|
||||
return apiClient.execute(call, returnType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find pet by ID (asynchronously)
|
||||
* Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
|
||||
* @param petId ID of pet that needs to be fetched
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call getPetByIdAsync(Long petId, ApiCallback<Pet> callback) throws ApiException {
|
||||
Call call = getPetByIdCall(petId);
|
||||
Type returnType = new TypeToken<Pet>(){}.getType();
|
||||
apiClient.executeAsync(call, returnType, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for updatePetWithForm */
|
||||
private Call updatePetWithFormCall(String petId, String name, String status) 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 updatePetWithForm(Async)");
|
||||
}
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/pet/{petId}".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>();
|
||||
if (name != null)
|
||||
formParams.put("name", name);
|
||||
if (status != null)
|
||||
formParams.put("status", status);
|
||||
|
||||
final String[] accepts = {
|
||||
"application/json", "application/xml"
|
||||
};
|
||||
final String accept = apiClient.selectHeaderAccept(accepts);
|
||||
if (accept != null) headerParams.put("Accept", accept);
|
||||
|
||||
final String[] contentTypes = {
|
||||
"application/x-www-form-urlencoded"
|
||||
};
|
||||
final String contentType = apiClient.selectHeaderContentType(contentTypes);
|
||||
headerParams.put("Content-Type", contentType);
|
||||
|
||||
String[] authNames = new String[] { "petstore_auth" };
|
||||
return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a pet in the store with form data
|
||||
*
|
||||
* @param petId ID of pet that needs to be updated
|
||||
* @param name Updated name of the pet
|
||||
* @param status Updated status of the pet
|
||||
*/
|
||||
public void updatePetWithForm(String petId, String name, String status) throws ApiException {
|
||||
Call call = updatePetWithFormCall(petId, name, status);
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a pet in the store with form data (asynchronously)
|
||||
*
|
||||
* @param petId ID of pet that needs to be updated
|
||||
* @param name Updated name of the pet
|
||||
* @param status Updated status of the pet
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call updatePetWithFormAsync(String petId, String name, String status, ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = updatePetWithFormCall(petId, name, status);
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for deletePet */
|
||||
private Call deletePetCall(Long petId, String apiKey) 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 deletePet(Async)");
|
||||
}
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/pet/{petId}".replaceAll("\\{format\\}","json")
|
||||
.replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
|
||||
|
||||
List<Pair> queryParams = new ArrayList<Pair>();
|
||||
|
||||
Map<String, String> headerParams = new HashMap<String, String>();
|
||||
if (apiKey != null)
|
||||
headerParams.put("api_key", apiClient.parameterToString(apiKey));
|
||||
|
||||
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);
|
||||
|
||||
String[] authNames = new String[] { "petstore_auth" };
|
||||
return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a pet
|
||||
*
|
||||
* @param petId Pet id to delete
|
||||
* @param apiKey
|
||||
*/
|
||||
public void deletePet(Long petId, String apiKey) throws ApiException {
|
||||
Call call = deletePetCall(petId, apiKey);
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a pet (asynchronously)
|
||||
*
|
||||
* @param petId Pet id to delete
|
||||
* @param apiKey
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call deletePetAsync(Long petId, String apiKey, ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = deletePetCall(petId, apiKey);
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for uploadFile */
|
||||
private Call uploadFileCall(Long petId, String additionalMetadata, File file) 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 uploadFile(Async)");
|
||||
}
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/pet/{petId}/uploadImage".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>();
|
||||
if (additionalMetadata != null)
|
||||
formParams.put("additionalMetadata", additionalMetadata);
|
||||
if (file != null)
|
||||
formParams.put("file", file);
|
||||
|
||||
final String[] accepts = {
|
||||
"application/json", "application/xml"
|
||||
};
|
||||
final String accept = apiClient.selectHeaderAccept(accepts);
|
||||
if (accept != null) headerParams.put("Accept", accept);
|
||||
|
||||
final String[] contentTypes = {
|
||||
"multipart/form-data"
|
||||
};
|
||||
final String contentType = apiClient.selectHeaderContentType(contentTypes);
|
||||
headerParams.put("Content-Type", contentType);
|
||||
|
||||
String[] authNames = new String[] { "petstore_auth" };
|
||||
return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* uploads an image
|
||||
*
|
||||
* @param petId ID of pet to update
|
||||
* @param additionalMetadata Additional data to pass to server
|
||||
* @param file file to upload
|
||||
*/
|
||||
public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException {
|
||||
Call call = uploadFileCall(petId, additionalMetadata, file);
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* uploads an image (asynchronously)
|
||||
*
|
||||
* @param petId ID of pet to update
|
||||
* @param additionalMetadata Additional data to pass to server
|
||||
* @param file file to upload
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call uploadFileAsync(Long petId, String additionalMetadata, File file, ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = uploadFileCall(petId, additionalMetadata, file);
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,277 @@
|
||||
package io.swagger.client.api;
|
||||
|
||||
import io.swagger.client.ApiCallback;
|
||||
import io.swagger.client.ApiClient;
|
||||
import io.swagger.client.ApiException;
|
||||
import io.swagger.client.Configuration;
|
||||
import io.swagger.client.Pair;
|
||||
|
||||
import io.swagger.client.model.*;
|
||||
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
|
||||
import com.squareup.okhttp.Call;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import java.util.Map;
|
||||
import io.swagger.client.model.Order;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class StoreApi {
|
||||
private ApiClient apiClient;
|
||||
|
||||
public StoreApi() {
|
||||
this(Configuration.getDefaultApiClient());
|
||||
}
|
||||
|
||||
public StoreApi(ApiClient apiClient) {
|
||||
this.apiClient = apiClient;
|
||||
}
|
||||
|
||||
public ApiClient getApiClient() {
|
||||
return apiClient;
|
||||
}
|
||||
|
||||
public void setApiClient(ApiClient apiClient) {
|
||||
this.apiClient = apiClient;
|
||||
}
|
||||
|
||||
|
||||
/* Build call for getInventory */
|
||||
private Call getInventoryCall() throws ApiException {
|
||||
Object postBody = null;
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/store/inventory".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 = {
|
||||
|
||||
};
|
||||
final String contentType = apiClient.selectHeaderContentType(contentTypes);
|
||||
headerParams.put("Content-Type", contentType);
|
||||
|
||||
String[] authNames = new String[] { "api_key" };
|
||||
return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns pet inventories by status
|
||||
* Returns a map of status codes to quantities
|
||||
* @return Map<String, Integer>
|
||||
*/
|
||||
public Map<String, Integer> getInventory() throws ApiException {
|
||||
Call call = getInventoryCall();
|
||||
Type returnType = new TypeToken<Map<String, Integer>>(){}.getType();
|
||||
return apiClient.execute(call, returnType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns pet inventories by status (asynchronously)
|
||||
* Returns a map of status codes to quantities
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call getInventoryAsync(ApiCallback<Map<String, Integer>> callback) throws ApiException {
|
||||
Call call = getInventoryCall();
|
||||
Type returnType = new TypeToken<Map<String, Integer>>(){}.getType();
|
||||
apiClient.executeAsync(call, returnType, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for placeOrder */
|
||||
private Call placeOrderCall(Order body) throws ApiException {
|
||||
Object postBody = body;
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/store/order".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 = {
|
||||
|
||||
};
|
||||
final String contentType = apiClient.selectHeaderContentType(contentTypes);
|
||||
headerParams.put("Content-Type", contentType);
|
||||
|
||||
String[] authNames = new String[] { };
|
||||
return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Place an order for a pet
|
||||
*
|
||||
* @param body order placed for purchasing the pet
|
||||
* @return Order
|
||||
*/
|
||||
public Order placeOrder(Order body) throws ApiException {
|
||||
Call call = placeOrderCall(body);
|
||||
Type returnType = new TypeToken<Order>(){}.getType();
|
||||
return apiClient.execute(call, returnType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Place an order for a pet (asynchronously)
|
||||
*
|
||||
* @param body order placed for purchasing the pet
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call placeOrderAsync(Order body, ApiCallback<Order> callback) throws ApiException {
|
||||
Call call = placeOrderCall(body);
|
||||
Type returnType = new TypeToken<Order>(){}.getType();
|
||||
apiClient.executeAsync(call, returnType, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for getOrderById */
|
||||
private Call getOrderByIdCall(String orderId) throws ApiException {
|
||||
Object postBody = null;
|
||||
|
||||
// verify the required parameter 'orderId' is set
|
||||
if (orderId == null) {
|
||||
throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)");
|
||||
}
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json")
|
||||
.replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.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);
|
||||
|
||||
String[] authNames = new String[] { };
|
||||
return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find purchase order by ID
|
||||
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
|
||||
* @param orderId ID of pet that needs to be fetched
|
||||
* @return Order
|
||||
*/
|
||||
public Order getOrderById(String orderId) throws ApiException {
|
||||
Call call = getOrderByIdCall(orderId);
|
||||
Type returnType = new TypeToken<Order>(){}.getType();
|
||||
return apiClient.execute(call, returnType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find purchase order by ID (asynchronously)
|
||||
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
|
||||
* @param orderId ID of pet that needs to be fetched
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call getOrderByIdAsync(String orderId, ApiCallback<Order> callback) throws ApiException {
|
||||
Call call = getOrderByIdCall(orderId);
|
||||
Type returnType = new TypeToken<Order>(){}.getType();
|
||||
apiClient.executeAsync(call, returnType, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for deleteOrder */
|
||||
private Call deleteOrderCall(String orderId) throws ApiException {
|
||||
Object postBody = null;
|
||||
|
||||
// verify the required parameter 'orderId' is set
|
||||
if (orderId == null) {
|
||||
throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)");
|
||||
}
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json")
|
||||
.replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.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);
|
||||
|
||||
String[] authNames = new String[] { };
|
||||
return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete purchase order by ID
|
||||
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
|
||||
* @param orderId ID of the order that needs to be deleted
|
||||
*/
|
||||
public void deleteOrder(String orderId) throws ApiException {
|
||||
Call call = deleteOrderCall(orderId);
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete purchase order by ID (asynchronously)
|
||||
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
|
||||
* @param orderId ID of the order that needs to be deleted
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call deleteOrderAsync(String orderId, ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = deleteOrderCall(orderId);
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,500 @@
|
||||
package io.swagger.client.api;
|
||||
|
||||
import io.swagger.client.ApiCallback;
|
||||
import io.swagger.client.ApiClient;
|
||||
import io.swagger.client.ApiException;
|
||||
import io.swagger.client.Configuration;
|
||||
import io.swagger.client.Pair;
|
||||
|
||||
import io.swagger.client.model.*;
|
||||
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
|
||||
import com.squareup.okhttp.Call;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import io.swagger.client.model.User;
|
||||
import java.util.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class UserApi {
|
||||
private ApiClient apiClient;
|
||||
|
||||
public UserApi() {
|
||||
this(Configuration.getDefaultApiClient());
|
||||
}
|
||||
|
||||
public UserApi(ApiClient apiClient) {
|
||||
this.apiClient = apiClient;
|
||||
}
|
||||
|
||||
public ApiClient getApiClient() {
|
||||
return apiClient;
|
||||
}
|
||||
|
||||
public void setApiClient(ApiClient apiClient) {
|
||||
this.apiClient = apiClient;
|
||||
}
|
||||
|
||||
|
||||
/* Build call for createUser */
|
||||
private Call createUserCall(User body) throws ApiException {
|
||||
Object postBody = body;
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/user".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 = {
|
||||
|
||||
};
|
||||
final String contentType = apiClient.selectHeaderContentType(contentTypes);
|
||||
headerParams.put("Content-Type", contentType);
|
||||
|
||||
String[] authNames = new String[] { };
|
||||
return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create user
|
||||
* This can only be done by the logged in user.
|
||||
* @param body Created user object
|
||||
*/
|
||||
public void createUser(User body) throws ApiException {
|
||||
Call call = createUserCall(body);
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create user (asynchronously)
|
||||
* This can only be done by the logged in user.
|
||||
* @param body Created user object
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call createUserAsync(User body, ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = createUserCall(body);
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for createUsersWithArrayInput */
|
||||
private Call createUsersWithArrayInputCall(List<User> body) throws ApiException {
|
||||
Object postBody = body;
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/user/createWithArray".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 = {
|
||||
|
||||
};
|
||||
final String contentType = apiClient.selectHeaderContentType(contentTypes);
|
||||
headerParams.put("Content-Type", contentType);
|
||||
|
||||
String[] authNames = new String[] { };
|
||||
return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates list of users with given input array
|
||||
*
|
||||
* @param body List of user object
|
||||
*/
|
||||
public void createUsersWithArrayInput(List<User> body) throws ApiException {
|
||||
Call call = createUsersWithArrayInputCall(body);
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates list of users with given input array (asynchronously)
|
||||
*
|
||||
* @param body List of user object
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call createUsersWithArrayInputAsync(List<User> body, ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = createUsersWithArrayInputCall(body);
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for createUsersWithListInput */
|
||||
private Call createUsersWithListInputCall(List<User> body) throws ApiException {
|
||||
Object postBody = body;
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/user/createWithList".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 = {
|
||||
|
||||
};
|
||||
final String contentType = apiClient.selectHeaderContentType(contentTypes);
|
||||
headerParams.put("Content-Type", contentType);
|
||||
|
||||
String[] authNames = new String[] { };
|
||||
return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates list of users with given input array
|
||||
*
|
||||
* @param body List of user object
|
||||
*/
|
||||
public void createUsersWithListInput(List<User> body) throws ApiException {
|
||||
Call call = createUsersWithListInputCall(body);
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates list of users with given input array (asynchronously)
|
||||
*
|
||||
* @param body List of user object
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call createUsersWithListInputAsync(List<User> body, ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = createUsersWithListInputCall(body);
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for loginUser */
|
||||
private Call loginUserCall(String username, String password) throws ApiException {
|
||||
Object postBody = null;
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/user/login".replaceAll("\\{format\\}","json");
|
||||
|
||||
List<Pair> queryParams = new ArrayList<Pair>();
|
||||
if (username != null)
|
||||
queryParams.addAll(apiClient.parameterToPairs("", "username", username));
|
||||
if (password != null)
|
||||
queryParams.addAll(apiClient.parameterToPairs("", "password", password));
|
||||
|
||||
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);
|
||||
|
||||
String[] authNames = new String[] { };
|
||||
return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs user into the system
|
||||
*
|
||||
* @param username The user name for login
|
||||
* @param password The password for login in clear text
|
||||
* @return String
|
||||
*/
|
||||
public String loginUser(String username, String password) throws ApiException {
|
||||
Call call = loginUserCall(username, password);
|
||||
Type returnType = new TypeToken<String>(){}.getType();
|
||||
return apiClient.execute(call, returnType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs user into the system (asynchronously)
|
||||
*
|
||||
* @param username The user name for login
|
||||
* @param password The password for login in clear text
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call loginUserAsync(String username, String password, ApiCallback<String> callback) throws ApiException {
|
||||
Call call = loginUserCall(username, password);
|
||||
Type returnType = new TypeToken<String>(){}.getType();
|
||||
apiClient.executeAsync(call, returnType, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for logoutUser */
|
||||
private Call logoutUserCall() throws ApiException {
|
||||
Object postBody = null;
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/user/logout".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 = {
|
||||
|
||||
};
|
||||
final String contentType = apiClient.selectHeaderContentType(contentTypes);
|
||||
headerParams.put("Content-Type", contentType);
|
||||
|
||||
String[] authNames = new String[] { };
|
||||
return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs out current logged in user session
|
||||
*
|
||||
*/
|
||||
public void logoutUser() throws ApiException {
|
||||
Call call = logoutUserCall();
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs out current logged in user session (asynchronously)
|
||||
*
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call logoutUserAsync(ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = logoutUserCall();
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for getUserByName */
|
||||
private Call getUserByNameCall(String username) throws ApiException {
|
||||
Object postBody = null;
|
||||
|
||||
// verify the required parameter 'username' is set
|
||||
if (username == null) {
|
||||
throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)");
|
||||
}
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/user/{username}".replaceAll("\\{format\\}","json")
|
||||
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.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);
|
||||
|
||||
String[] authNames = new String[] { };
|
||||
return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user by user name
|
||||
*
|
||||
* @param username The name that needs to be fetched. Use user1 for testing.
|
||||
* @return User
|
||||
*/
|
||||
public User getUserByName(String username) throws ApiException {
|
||||
Call call = getUserByNameCall(username);
|
||||
Type returnType = new TypeToken<User>(){}.getType();
|
||||
return apiClient.execute(call, returnType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user by user name (asynchronously)
|
||||
*
|
||||
* @param username The name that needs to be fetched. Use user1 for testing.
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call getUserByNameAsync(String username, ApiCallback<User> callback) throws ApiException {
|
||||
Call call = getUserByNameCall(username);
|
||||
Type returnType = new TypeToken<User>(){}.getType();
|
||||
apiClient.executeAsync(call, returnType, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for updateUser */
|
||||
private Call updateUserCall(String username, User body) throws ApiException {
|
||||
Object postBody = body;
|
||||
|
||||
// verify the required parameter 'username' is set
|
||||
if (username == null) {
|
||||
throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)");
|
||||
}
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/user/{username}".replaceAll("\\{format\\}","json")
|
||||
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.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);
|
||||
|
||||
String[] authNames = new String[] { };
|
||||
return apiClient.buildCall(path, "PUT", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updated user
|
||||
* This can only be done by the logged in user.
|
||||
* @param username name that need to be deleted
|
||||
* @param body Updated user object
|
||||
*/
|
||||
public void updateUser(String username, User body) throws ApiException {
|
||||
Call call = updateUserCall(username, body);
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updated user (asynchronously)
|
||||
* This can only be done by the logged in user.
|
||||
* @param username name that need to be deleted
|
||||
* @param body Updated user object
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call updateUserAsync(String username, User body, ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = updateUserCall(username, body);
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
/* Build call for deleteUser */
|
||||
private Call deleteUserCall(String username) throws ApiException {
|
||||
Object postBody = null;
|
||||
|
||||
// verify the required parameter 'username' is set
|
||||
if (username == null) {
|
||||
throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)");
|
||||
}
|
||||
|
||||
|
||||
// create path and map variables
|
||||
String path = "/user/{username}".replaceAll("\\{format\\}","json")
|
||||
.replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.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);
|
||||
|
||||
String[] authNames = new String[] { };
|
||||
return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete user
|
||||
* This can only be done by the logged in user.
|
||||
* @param username The name that needs to be deleted
|
||||
*/
|
||||
public void deleteUser(String username) throws ApiException {
|
||||
Call call = deleteUserCall(username);
|
||||
apiClient.execute(call);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete user (asynchronously)
|
||||
* This can only be done by the logged in user.
|
||||
* @param username The name that needs to be deleted
|
||||
* @param callback The callback to be executed when the API call finishes
|
||||
* @return The request call
|
||||
*/
|
||||
public Call deleteUserAsync(String username, ApiCallback<Void> callback) throws ApiException {
|
||||
Call call = deleteUserCall(username);
|
||||
apiClient.executeAsync(call, callback);
|
||||
return call;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
package io.swagger.client.auth;
|
||||
|
||||
import io.swagger.client.Pair;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00")
|
||||
public class ApiKeyAuth implements Authentication {
|
||||
private final String location;
|
||||
private final String paramName;
|
||||
|
||||
private String apiKey;
|
||||
private String apiKeyPrefix;
|
||||
|
||||
public ApiKeyAuth(String location, String paramName) {
|
||||
this.location = location;
|
||||
this.paramName = paramName;
|
||||
}
|
||||
|
||||
public String getLocation() {
|
||||
return location;
|
||||
}
|
||||
|
||||
public String getParamName() {
|
||||
return paramName;
|
||||
}
|
||||
|
||||
public String getApiKey() {
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
public void setApiKey(String apiKey) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
public String getApiKeyPrefix() {
|
||||
return apiKeyPrefix;
|
||||
}
|
||||
|
||||
public void setApiKeyPrefix(String apiKeyPrefix) {
|
||||
this.apiKeyPrefix = apiKeyPrefix;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
|
||||
String value;
|
||||
if (apiKeyPrefix != null) {
|
||||
value = apiKeyPrefix + " " + apiKey;
|
||||
} else {
|
||||
value = apiKey;
|
||||
}
|
||||
if (location == "query") {
|
||||
queryParams.add(new Pair(paramName, value));
|
||||
} else if (location == "header") {
|
||||
headerParams.put(paramName, value);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package io.swagger.client.auth;
|
||||
|
||||
import io.swagger.client.Pair;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00")
|
||||
public interface Authentication {
|
||||
/** Apply authentication settings to header and query params. */
|
||||
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams);
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package io.swagger.client.auth;
|
||||
|
||||
import io.swagger.client.Pair;
|
||||
|
||||
import com.migcomponents.migbase64.Base64;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
public class HttpBasicAuth implements Authentication {
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
|
||||
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
|
||||
try {
|
||||
headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package io.swagger.client.auth;
|
||||
|
||||
import io.swagger.client.Pair;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00")
|
||||
public class OAuth implements Authentication {
|
||||
@Override
|
||||
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
|
||||
// TODO: support oauth
|
||||
}
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
package io.swagger.client.model;
|
||||
|
||||
import io.swagger.client.StringUtil;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
|
||||
|
||||
import io.swagger.annotations.*;
|
||||
|
||||
|
||||
|
||||
@ApiModel(description = "")
|
||||
public class Category {
|
||||
|
||||
@SerializedName("id")
|
||||
private Long id = null;
|
||||
|
||||
@SerializedName("name")
|
||||
private String name = null;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class Category {\n");
|
||||
|
||||
sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n");
|
||||
sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,142 @@
|
||||
package io.swagger.client.model;
|
||||
|
||||
import io.swagger.client.StringUtil;
|
||||
import java.util.Date;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
|
||||
|
||||
import io.swagger.annotations.*;
|
||||
|
||||
|
||||
|
||||
@ApiModel(description = "")
|
||||
public class Order {
|
||||
|
||||
@SerializedName("id")
|
||||
private Long id = null;
|
||||
|
||||
@SerializedName("petId")
|
||||
private Long petId = null;
|
||||
|
||||
@SerializedName("quantity")
|
||||
private Integer quantity = null;
|
||||
|
||||
@SerializedName("shipDate")
|
||||
private Date shipDate = null;
|
||||
|
||||
|
||||
public enum StatusEnum {
|
||||
@SerializedName("placed")
|
||||
PLACED("placed"),
|
||||
|
||||
@SerializedName("approved")
|
||||
APPROVED("approved"),
|
||||
|
||||
@SerializedName("delivered")
|
||||
DELIVERED("delivered");
|
||||
|
||||
private String value;
|
||||
|
||||
StatusEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
@SerializedName("status")
|
||||
private StatusEnum status = null;
|
||||
|
||||
@SerializedName("complete")
|
||||
private Boolean complete = null;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public Long getPetId() {
|
||||
return petId;
|
||||
}
|
||||
public void setPetId(Long petId) {
|
||||
this.petId = petId;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public Integer getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
public void setQuantity(Integer quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public Date getShipDate() {
|
||||
return shipDate;
|
||||
}
|
||||
public void setShipDate(Date shipDate) {
|
||||
this.shipDate = shipDate;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Order Status
|
||||
**/
|
||||
@ApiModelProperty(value = "Order Status")
|
||||
public StatusEnum getStatus() {
|
||||
return status;
|
||||
}
|
||||
public void setStatus(StatusEnum status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public Boolean getComplete() {
|
||||
return complete;
|
||||
}
|
||||
public void setComplete(Boolean complete) {
|
||||
this.complete = complete;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class Order {\n");
|
||||
|
||||
sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n");
|
||||
sb.append(" petId: ").append(StringUtil.toIndentedString(petId)).append("\n");
|
||||
sb.append(" quantity: ").append(StringUtil.toIndentedString(quantity)).append("\n");
|
||||
sb.append(" shipDate: ").append(StringUtil.toIndentedString(shipDate)).append("\n");
|
||||
sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n");
|
||||
sb.append(" complete: ").append(StringUtil.toIndentedString(complete)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,144 @@
|
||||
package io.swagger.client.model;
|
||||
|
||||
import io.swagger.client.StringUtil;
|
||||
import io.swagger.client.model.Category;
|
||||
import java.util.*;
|
||||
import io.swagger.client.model.Tag;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
|
||||
|
||||
import io.swagger.annotations.*;
|
||||
|
||||
|
||||
|
||||
@ApiModel(description = "")
|
||||
public class Pet {
|
||||
|
||||
@SerializedName("id")
|
||||
private Long id = null;
|
||||
|
||||
@SerializedName("category")
|
||||
private Category category = null;
|
||||
|
||||
@SerializedName("name")
|
||||
private String name = null;
|
||||
|
||||
@SerializedName("photoUrls")
|
||||
private List<String> photoUrls = new ArrayList<String>();
|
||||
|
||||
@SerializedName("tags")
|
||||
private List<Tag> tags = new ArrayList<Tag>();
|
||||
|
||||
|
||||
public enum StatusEnum {
|
||||
@SerializedName("available")
|
||||
AVAILABLE("available"),
|
||||
|
||||
@SerializedName("pending")
|
||||
PENDING("pending"),
|
||||
|
||||
@SerializedName("sold")
|
||||
SOLD("sold");
|
||||
|
||||
private String value;
|
||||
|
||||
StatusEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
@SerializedName("status")
|
||||
private StatusEnum status = null;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public Category getCategory() {
|
||||
return category;
|
||||
}
|
||||
public void setCategory(Category category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(required = true, value = "")
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(required = true, value = "")
|
||||
public List<String> getPhotoUrls() {
|
||||
return photoUrls;
|
||||
}
|
||||
public void setPhotoUrls(List<String> photoUrls) {
|
||||
this.photoUrls = photoUrls;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public List<Tag> getTags() {
|
||||
return tags;
|
||||
}
|
||||
public void setTags(List<Tag> tags) {
|
||||
this.tags = tags;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* pet status in the store
|
||||
**/
|
||||
@ApiModelProperty(value = "pet status in the store")
|
||||
public StatusEnum getStatus() {
|
||||
return status;
|
||||
}
|
||||
public void setStatus(StatusEnum status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class Pet {\n");
|
||||
|
||||
sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n");
|
||||
sb.append(" category: ").append(StringUtil.toIndentedString(category)).append("\n");
|
||||
sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n");
|
||||
sb.append(" photoUrls: ").append(StringUtil.toIndentedString(photoUrls)).append("\n");
|
||||
sb.append(" tags: ").append(StringUtil.toIndentedString(tags)).append("\n");
|
||||
sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
package io.swagger.client.model;
|
||||
|
||||
import io.swagger.client.StringUtil;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
|
||||
|
||||
import io.swagger.annotations.*;
|
||||
|
||||
|
||||
|
||||
@ApiModel(description = "")
|
||||
public class Tag {
|
||||
|
||||
@SerializedName("id")
|
||||
private Long id = null;
|
||||
|
||||
@SerializedName("name")
|
||||
private String name = null;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class Tag {\n");
|
||||
|
||||
sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n");
|
||||
sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,148 @@
|
||||
package io.swagger.client.model;
|
||||
|
||||
import io.swagger.client.StringUtil;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
|
||||
|
||||
|
||||
import io.swagger.annotations.*;
|
||||
|
||||
|
||||
|
||||
@ApiModel(description = "")
|
||||
public class User {
|
||||
|
||||
@SerializedName("id")
|
||||
private Long id = null;
|
||||
|
||||
@SerializedName("username")
|
||||
private String username = null;
|
||||
|
||||
@SerializedName("firstName")
|
||||
private String firstName = null;
|
||||
|
||||
@SerializedName("lastName")
|
||||
private String lastName = null;
|
||||
|
||||
@SerializedName("email")
|
||||
private String email = null;
|
||||
|
||||
@SerializedName("password")
|
||||
private String password = null;
|
||||
|
||||
@SerializedName("phone")
|
||||
private String phone = null;
|
||||
|
||||
@SerializedName("userStatus")
|
||||
private Integer userStatus = null;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
**/
|
||||
@ApiModelProperty(value = "")
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* User Status
|
||||
**/
|
||||
@ApiModelProperty(value = "User Status")
|
||||
public Integer getUserStatus() {
|
||||
return userStatus;
|
||||
}
|
||||
public void setUserStatus(Integer userStatus) {
|
||||
this.userStatus = userStatus;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class User {\n");
|
||||
|
||||
sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n");
|
||||
sb.append(" username: ").append(StringUtil.toIndentedString(username)).append("\n");
|
||||
sb.append(" firstName: ").append(StringUtil.toIndentedString(firstName)).append("\n");
|
||||
sb.append(" lastName: ").append(StringUtil.toIndentedString(lastName)).append("\n");
|
||||
sb.append(" email: ").append(StringUtil.toIndentedString(email)).append("\n");
|
||||
sb.append(" password: ").append(StringUtil.toIndentedString(password)).append("\n");
|
||||
sb.append(" phone: ").append(StringUtil.toIndentedString(phone)).append("\n");
|
||||
sb.append(" userStatus: ").append(StringUtil.toIndentedString(userStatus)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,193 @@
|
||||
package io.swagger.client;
|
||||
|
||||
import io.swagger.client.auth.*;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import org.junit.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class ApiClientTest {
|
||||
ApiClient apiClient = null;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
apiClient = new ApiClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectHeaderAccept() {
|
||||
String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"};
|
||||
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
|
||||
|
||||
accepts = new String[]{"application/json", "application/xml"};
|
||||
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
|
||||
|
||||
accepts = new String[]{"application/xml", "application/json"};
|
||||
assertEquals("application/json", apiClient.selectHeaderAccept(accepts));
|
||||
|
||||
accepts = new String[]{"text/plain", "application/xml"};
|
||||
assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts));
|
||||
|
||||
accepts = new String[]{};
|
||||
assertNull(apiClient.selectHeaderAccept(accepts));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectHeaderContentType() {
|
||||
String[] contentTypes = {"APPLICATION/JSON", "APPLICATION/XML"};
|
||||
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
|
||||
|
||||
contentTypes = new String[]{"application/json", "application/xml"};
|
||||
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
|
||||
|
||||
contentTypes = new String[]{"application/xml", "application/json"};
|
||||
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
|
||||
|
||||
contentTypes = new String[]{"text/plain", "application/xml"};
|
||||
assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes));
|
||||
|
||||
contentTypes = new String[]{};
|
||||
assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAuthentications() {
|
||||
Map<String, Authentication> auths = apiClient.getAuthentications();
|
||||
|
||||
Authentication auth = auths.get("api_key");
|
||||
assertNotNull(auth);
|
||||
assertTrue(auth instanceof ApiKeyAuth);
|
||||
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth;
|
||||
assertEquals("header", apiKeyAuth.getLocation());
|
||||
assertEquals("api_key", apiKeyAuth.getParamName());
|
||||
|
||||
auth = auths.get("petstore_auth");
|
||||
assertTrue(auth instanceof OAuth);
|
||||
assertSame(auth, apiClient.getAuthentication("petstore_auth"));
|
||||
|
||||
assertNull(auths.get("unknown"));
|
||||
|
||||
try {
|
||||
auths.put("my_auth", new HttpBasicAuth());
|
||||
fail("the authentications returned should not be modifiable");
|
||||
} catch (UnsupportedOperationException e) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetUsername() {
|
||||
try {
|
||||
apiClient.setUsername("my-username");
|
||||
fail("there should be no HTTP basic authentications");
|
||||
} catch (RuntimeException e) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetPassword() {
|
||||
try {
|
||||
apiClient.setPassword("my-password");
|
||||
fail("there should be no HTTP basic authentications");
|
||||
} catch (RuntimeException e) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSetApiKeyAndPrefix() {
|
||||
ApiKeyAuth auth = (ApiKeyAuth) apiClient.getAuthentications().get("api_key");
|
||||
auth.setApiKey(null);
|
||||
auth.setApiKeyPrefix(null);
|
||||
|
||||
apiClient.setApiKey("my-api-key");
|
||||
apiClient.setApiKeyPrefix("Token");
|
||||
assertEquals("my-api-key", auth.getApiKey());
|
||||
assertEquals("Token", auth.getApiKeyPrefix());
|
||||
|
||||
// reset values
|
||||
auth.setApiKey(null);
|
||||
auth.setApiKeyPrefix(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParameterToPairsWhenNameIsInvalid() throws Exception {
|
||||
List<Pair> pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1));
|
||||
List<Pair> pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1));
|
||||
|
||||
assertTrue(pairs_a.isEmpty());
|
||||
assertTrue(pairs_b.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParameterToPairsWhenValueIsNull() throws Exception {
|
||||
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", null);
|
||||
|
||||
assertTrue(pairs.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception {
|
||||
|
||||
// single empty string
|
||||
List<Pair> pairs = apiClient.parameterToPairs("csv", "param-a", " ");
|
||||
assertEquals(1, pairs.size());
|
||||
|
||||
// list of empty strings
|
||||
List<String> strs = new ArrayList<String>();
|
||||
strs.add(" ");
|
||||
strs.add(" ");
|
||||
strs.add(" ");
|
||||
|
||||
List<Pair> concatStrings = apiClient.parameterToPairs("csv", "param-a", strs);
|
||||
|
||||
assertEquals(1, concatStrings.size());
|
||||
assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParameterToPairsWhenValueIsNotCollection() throws Exception {
|
||||
String name = "param-a";
|
||||
Integer value = 1;
|
||||
|
||||
List<Pair> pairs = apiClient.parameterToPairs("csv", name, value);
|
||||
|
||||
assertEquals(1, pairs.size());
|
||||
assertEquals(value, Integer.valueOf(pairs.get(0).getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParameterToPairsWhenValueIsCollection() throws Exception {
|
||||
Map<String, String> collectionFormatMap = new HashMap<String, String>();
|
||||
collectionFormatMap.put("csv", ",");
|
||||
collectionFormatMap.put("tsv", "\t");
|
||||
collectionFormatMap.put("ssv", " ");
|
||||
collectionFormatMap.put("pipes", "\\|");
|
||||
collectionFormatMap.put("", ","); // no format, must default to csv
|
||||
collectionFormatMap.put("unknown", ","); // all other formats, must default to csv
|
||||
|
||||
String name = "param-a";
|
||||
|
||||
List<Object> values = new ArrayList<Object>();
|
||||
values.add("value-a");
|
||||
values.add(123);
|
||||
values.add(new Date());
|
||||
|
||||
// check for multi separately
|
||||
List<Pair> multiPairs = apiClient.parameterToPairs("multi", name, values);
|
||||
assertEquals(values.size(), multiPairs.size());
|
||||
|
||||
// all other formats
|
||||
for (String collectionFormat : collectionFormatMap.keySet()) {
|
||||
List<Pair> pairs = apiClient.parameterToPairs(collectionFormat, name, values);
|
||||
|
||||
assertEquals(1, pairs.size());
|
||||
|
||||
String delimiter = collectionFormatMap.get(collectionFormat);
|
||||
String[] pairValueSplit = pairs.get(0).getValue().split(delimiter);
|
||||
|
||||
// must equal input values
|
||||
assertEquals(values.size(), pairValueSplit.length);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package io.swagger.client;
|
||||
|
||||
import org.junit.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class ConfigurationTest {
|
||||
@Test
|
||||
public void testDefaultApiClient() {
|
||||
ApiClient apiClient = Configuration.getDefaultApiClient();
|
||||
assertNotNull(apiClient);
|
||||
assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath());
|
||||
assertFalse(apiClient.isDebugging());
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package io.swagger.client;
|
||||
|
||||
import org.junit.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class StringUtilTest {
|
||||
@Test
|
||||
public void testContainsIgnoreCase() {
|
||||
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc"));
|
||||
assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC"));
|
||||
assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc"));
|
||||
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC"));
|
||||
assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null));
|
||||
|
||||
assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def"));
|
||||
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC"));
|
||||
assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testJoin() {
|
||||
String[] array = {"aa", "bb", "cc"};
|
||||
assertEquals("aa,bb,cc", StringUtil.join(array, ","));
|
||||
assertEquals("aa, bb, cc", StringUtil.join(array, ", "));
|
||||
assertEquals("aabbcc", StringUtil.join(array, ""));
|
||||
assertEquals("aa bb cc", StringUtil.join(array, " "));
|
||||
assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n"));
|
||||
|
||||
assertEquals("", StringUtil.join(new String[]{}, ","));
|
||||
assertEquals("abc", StringUtil.join(new String[]{"abc"}, ","));
|
||||
}
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
package io.swagger.client.auth;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
import io.swagger.client.Pair;
|
||||
import org.junit.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class ApiKeyAuthTest {
|
||||
@Test
|
||||
public void testApplyToParamsInQuery() {
|
||||
List<Pair> queryParams = new ArrayList<Pair>();
|
||||
Map<String, String> headerParams = new HashMap<String, String>();
|
||||
|
||||
ApiKeyAuth auth = new ApiKeyAuth("query", "api_key");
|
||||
auth.setApiKey("my-api-key");
|
||||
auth.applyToParams(queryParams, headerParams);
|
||||
|
||||
assertEquals(1, queryParams.size());
|
||||
for (Pair queryParam : queryParams) {
|
||||
assertEquals("my-api-key", queryParam.getValue());
|
||||
}
|
||||
|
||||
// no changes to header parameters
|
||||
assertEquals(0, headerParams.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testApplyToParamsInHeaderWithPrefix() {
|
||||
List<Pair> queryParams = new ArrayList<Pair>();
|
||||
Map<String, String> headerParams = new HashMap<String, String>();
|
||||
|
||||
ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN");
|
||||
auth.setApiKey("my-api-token");
|
||||
auth.setApiKeyPrefix("Token");
|
||||
auth.applyToParams(queryParams, headerParams);
|
||||
|
||||
// no changes to query parameters
|
||||
assertEquals(0, queryParams.size());
|
||||
assertEquals(1, headerParams.size());
|
||||
assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN"));
|
||||
}
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
package io.swagger.client.auth;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
import io.swagger.client.Pair;
|
||||
import org.junit.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class HttpBasicAuthTest {
|
||||
HttpBasicAuth auth = null;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
auth = new HttpBasicAuth();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testApplyToParams() {
|
||||
List<Pair> queryParams = new ArrayList<Pair>();
|
||||
Map<String, String> headerParams = new HashMap<String, String>();
|
||||
|
||||
auth.setUsername("my-username");
|
||||
auth.setPassword("my-password");
|
||||
auth.applyToParams(queryParams, headerParams);
|
||||
|
||||
// no changes to query parameters
|
||||
assertEquals(0, queryParams.size());
|
||||
assertEquals(1, headerParams.size());
|
||||
// the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix
|
||||
String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ=";
|
||||
assertEquals(expected, headerParams.get("Authorization"));
|
||||
|
||||
// null username should be treated as empty string
|
||||
auth.setUsername(null);
|
||||
auth.applyToParams(queryParams, headerParams);
|
||||
// the string below is base64-encoded result of ":my-password" with the "Basic " prefix
|
||||
expected = "Basic Om15LXBhc3N3b3Jk";
|
||||
assertEquals(expected, headerParams.get("Authorization"));
|
||||
|
||||
// null password should be treated as empty string
|
||||
auth.setUsername("my-username");
|
||||
auth.setPassword(null);
|
||||
auth.applyToParams(queryParams, headerParams);
|
||||
// the string below is base64-encoded result of "my-username:" with the "Basic " prefix
|
||||
expected = "Basic bXktdXNlcm5hbWU6";
|
||||
assertEquals(expected, headerParams.get("Authorization"));
|
||||
}
|
||||
}
|
@ -0,0 +1,192 @@
|
||||
package io.swagger.petstore.test;
|
||||
|
||||
import io.swagger.client.ApiClient;
|
||||
import io.swagger.client.ApiException;
|
||||
import io.swagger.client.Configuration;
|
||||
|
||||
import io.swagger.client.api.*;
|
||||
import io.swagger.client.auth.*;
|
||||
import io.swagger.client.model.*;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PetApiTest {
|
||||
PetApi api = null;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
api = new PetApi();
|
||||
// setup authentication
|
||||
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
|
||||
apiKeyAuth.setApiKey("special-key");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testApiClient() {
|
||||
// the default api client is used
|
||||
assertEquals(Configuration.getDefaultApiClient(), api.getApiClient());
|
||||
assertNotNull(api.getApiClient());
|
||||
assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath());
|
||||
assertFalse(api.getApiClient().isDebugging());
|
||||
|
||||
ApiClient oldClient = api.getApiClient();
|
||||
|
||||
ApiClient newClient = new ApiClient();
|
||||
newClient.setBasePath("http://example.com");
|
||||
newClient.setDebugging(true);
|
||||
|
||||
// set api client via constructor
|
||||
api = new PetApi(newClient);
|
||||
assertNotNull(api.getApiClient());
|
||||
assertEquals("http://example.com", api.getApiClient().getBasePath());
|
||||
assertTrue(api.getApiClient().isDebugging());
|
||||
|
||||
// set api client via setter method
|
||||
api.setApiClient(oldClient);
|
||||
assertNotNull(api.getApiClient());
|
||||
assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath());
|
||||
assertFalse(api.getApiClient().isDebugging());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateAndGetPet() 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 testUpdatePet() 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 testFindPetsByStatus() 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 testFindPetsByTags() throws Exception {
|
||||
Pet pet = createRandomPet();
|
||||
pet.setName("monster");
|
||||
pet.setStatus(Pet.StatusEnum.AVAILABLE);
|
||||
|
||||
List<Tag> tags = new ArrayList<Tag>();
|
||||
Tag tag1 = new Tag();
|
||||
tag1.setName("friendly");
|
||||
tags.add(tag1);
|
||||
pet.setTags(tags);
|
||||
|
||||
api.updatePet(pet);
|
||||
|
||||
List<Pet> pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"}));
|
||||
assertNotNull(pets);
|
||||
|
||||
boolean found = false;
|
||||
for (Pet fetched : pets) {
|
||||
if (fetched.getId().equals(pet.getId())) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertTrue(found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdatePetWithForm() throws Exception {
|
||||
Pet pet = createRandomPet();
|
||||
pet.setName("frank");
|
||||
api.addPet(pet);
|
||||
|
||||
Pet fetched = api.getPetById(pet.getId());
|
||||
|
||||
api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null);
|
||||
Pet updated = api.getPetById(fetched.getId());
|
||||
|
||||
assertEquals(updated.getName(), "furt");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeletePet() 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 testUploadFile() 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;
|
||||
}
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
package io.swagger.petstore.test;
|
||||
|
||||
import io.swagger.client.ApiException;
|
||||
|
||||
import io.swagger.client.*;
|
||||
import io.swagger.client.api.*;
|
||||
import io.swagger.client.auth.*;
|
||||
import io.swagger.client.model.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class StoreApiTest {
|
||||
StoreApi api = null;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
api = new StoreApi();
|
||||
// setup authentication
|
||||
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
|
||||
apiKeyAuth.setApiKey("special-key");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetInventory() throws Exception {
|
||||
Map<String, Integer> inventory = api.getInventory();
|
||||
assertTrue(inventory.keySet().size() > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPlaceOrder() throws Exception {
|
||||
Order order = createOrder();
|
||||
api.placeOrder(order);
|
||||
|
||||
Order fetched = api.getOrderById(String.valueOf(order.getId()));
|
||||
assertEquals(order.getId(), fetched.getId());
|
||||
assertEquals(order.getPetId(), fetched.getPetId());
|
||||
assertEquals(order.getQuantity(), fetched.getQuantity());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteOrder() throws Exception {
|
||||
Order order = createOrder();
|
||||
api.placeOrder(order);
|
||||
|
||||
Order fetched = api.getOrderById(String.valueOf(order.getId()));
|
||||
assertEquals(fetched.getId(), order.getId());
|
||||
|
||||
api.deleteOrder(String.valueOf(order.getId()));
|
||||
|
||||
try {
|
||||
api.getOrderById(String.valueOf(order.getId()));
|
||||
// fail("expected an error");
|
||||
} catch (ApiException e) {
|
||||
// ok
|
||||
}
|
||||
}
|
||||
|
||||
private Order createOrder() {
|
||||
Order order = new Order();
|
||||
order.setId(new Long(System.currentTimeMillis()));
|
||||
order.setPetId(new Long(200));
|
||||
order.setQuantity(new Integer(13));
|
||||
order.setShipDate(new java.util.Date());
|
||||
order.setStatus(Order.StatusEnum.PLACED);
|
||||
order.setComplete(true);
|
||||
|
||||
return order;
|
||||
}
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
package io.swagger.petstore.test;
|
||||
|
||||
import io.swagger.client.api.*;
|
||||
import io.swagger.client.auth.*;
|
||||
import io.swagger.client.model.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class UserApiTest {
|
||||
UserApi api = null;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
api = new UserApi();
|
||||
// setup authentication
|
||||
ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key");
|
||||
apiKeyAuth.setApiKey("special-key");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateUser() throws Exception {
|
||||
User user = createUser();
|
||||
|
||||
api.createUser(user);
|
||||
|
||||
User fetched = api.getUserByName(user.getUsername());
|
||||
assertEquals(user.getId(), fetched.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateUsersWithArray() throws Exception {
|
||||
User user1 = createUser();
|
||||
user1.setUsername("abc123");
|
||||
User user2 = createUser();
|
||||
user2.setUsername("123abc");
|
||||
|
||||
api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2}));
|
||||
|
||||
User fetched = api.getUserByName(user1.getUsername());
|
||||
assertEquals(user1.getId(), fetched.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateUsersWithList() throws Exception {
|
||||
User user1 = createUser();
|
||||
user1.setUsername("abc123");
|
||||
User user2 = createUser();
|
||||
user2.setUsername("123abc");
|
||||
|
||||
api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2}));
|
||||
|
||||
User fetched = api.getUserByName(user1.getUsername());
|
||||
assertEquals(user1.getId(), fetched.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLoginUser() throws Exception {
|
||||
User user = createUser();
|
||||
api.createUser(user);
|
||||
|
||||
String token = api.loginUser(user.getUsername(), user.getPassword());
|
||||
assertTrue(token.startsWith("logged in user session:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logoutUser() throws Exception {
|
||||
api.logoutUser();
|
||||
}
|
||||
|
||||
private User createUser() {
|
||||
User user = new User();
|
||||
user.setId(System.currentTimeMillis());
|
||||
user.setUsername("fred");
|
||||
user.setFirstName("Fred");
|
||||
user.setLastName("Meyer");
|
||||
user.setEmail("fred@fredmeyer.com");
|
||||
user.setPassword("xxXXxx");
|
||||
user.setPhone("408-867-5309");
|
||||
user.setUserStatus(123);
|
||||
|
||||
return user;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user