Merge pull request #1775 from Shyri/android-volley

Android volley client generator
This commit is contained in:
wing328 2016-01-04 14:30:55 +08:00
commit c315d7f3df
46 changed files with 5059 additions and 1 deletions

View File

@ -301,6 +301,7 @@ $ ls -1 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/
AbstractTypeScriptClientCodegen.java
AkkaScalaClientCodegen.java
AndroidClientCodegen.java
AndroidVolleyClientCodegen.java
AsyncScalaClientCodegen.java
CSharpClientCodegen.java
ClojureClientCodegen.java

View 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 -t ../modules/swagger-codegen/src/main/resources/android-volley -i ../modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android-volley -o samples/client/petstore/android-volley"
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,299 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import org.apache.commons.lang.StringUtils;
public class AndroidVolleyClientCodegen extends DefaultCodegen implements CodegenConfig {
public static final String USE_ANDROID_MAVEN_GRADLE_PLUGIN = "useAndroidMavenGradlePlugin";
protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-android-volley-client";
protected String artifactVersion = "1.0.0";
protected String projectFolder = "src/main";
protected String sourceFolder = projectFolder + "/java";
protected Boolean useAndroidMavenGradlePlugin = true;
protected String requestPackage = "io.swagger.client.request";
protected String authPackage = "io.swagger.client.auth";
public AndroidVolleyClientCodegen() {
super();
outputFolder = "generated-code/android-volley";
modelTemplateFiles.put("model.mustache", ".java");
apiTemplateFiles.put("api.mustache", ".java");
embeddedTemplateDir = templateDir = "android-volley";
apiPackage = "io.swagger.client.api";
modelPackage = "io.swagger.client.model";
reservedWords = new HashSet<String>(
Arrays.asList(
"abstract", "continue", "for", "new", "switch", "assert",
"default", "if", "package", "synchronized", "boolean", "do", "goto", "private",
"this", "break", "double", "implements", "protected", "throw", "byte", "else",
"import", "public", "throws", "case", "enum", "instanceof", "return", "transient",
"catch", "extends", "int", "short", "try", "char", "final", "interface", "static",
"void", "class", "finally", "long", "strictfp", "volatile", "const", "float",
"native", "super", "while")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object")
);
instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap");
cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC));
cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, "groupId for use in the generated build.gradle and pom.xml"));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, "artifactId for use in the generated build.gradle and pom.xml"));
cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, "artifact version for use in the generated build.gradle and pom.xml"));
cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC));
cliOptions.add(new CliOption(USE_ANDROID_MAVEN_GRADLE_PLUGIN, "A flag to toggle android-maven gradle plugin. Default is true."));
}
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "android-volley";
}
public String getHelp() {
return "Generates an Android client library.";
}
@Override
public String escapeReservedWord(String name) {
return "_" + name;
}
@Override
public String apiFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar);
}
public String modelFileFolder() {
return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar);
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
type = swaggerType;
}
return toModelName(type);
}
@Override
public String toVarName(String name) {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
// camelize (lower first character) the variable name
// pet_id => petId
name = camelize(name, true);
// for reserved word or word starting with number, append _
if (reservedWords.contains(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toModelName(String name) {
// model name cannot use reserved keyword, e.g. return
if (reservedWords.contains(name)) {
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
}
// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}
@Override
public String toModelFilename(String name) {
// should be the same as the model name
return toModelName(name);
}
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
// method name cannot use reserved keyword, e.g. return
if (reservedWords.contains(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
}
return camelize(operationId, true);
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) {
this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE));
} else {
//not set, use default to be passed to template
additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage);
}
if (additionalProperties.containsKey(CodegenConstants.GROUP_ID)) {
this.setGroupId((String) additionalProperties.get(CodegenConstants.GROUP_ID));
} else {
//not set, use to be passed to template
additionalProperties.put(CodegenConstants.GROUP_ID, groupId);
}
if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_ID)) {
this.setArtifactId((String) additionalProperties.get(CodegenConstants.ARTIFACT_ID));
} else {
//not set, use to be passed to template
additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId);
}
if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_VERSION)) {
this.setArtifactVersion((String) additionalProperties.get(CodegenConstants.ARTIFACT_VERSION));
} else {
//not set, use to be passed to template
additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion);
}
if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) {
this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER));
}
if (additionalProperties.containsKey(USE_ANDROID_MAVEN_GRADLE_PLUGIN)) {
this.setUseAndroidMavenGradlePlugin(Boolean.valueOf((String) additionalProperties
.get(USE_ANDROID_MAVEN_GRADLE_PLUGIN)));
} else {
additionalProperties.put(USE_ANDROID_MAVEN_GRADLE_PLUGIN, useAndroidMavenGradlePlugin);
}
// supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
additionalProperties.put(USE_ANDROID_MAVEN_GRADLE_PLUGIN, useAndroidMavenGradlePlugin);
// supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle"));
supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle"));
supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml"));
supportingFiles.add(new SupportingFile("apiInvoker.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java"));
supportingFiles.add(new SupportingFile("responses.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Responses.java"));
// supportingFiles.add(new SupportingFile("httpPatch.mustache",
// (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "HttpPatch.java"));
supportingFiles.add(new SupportingFile("jsonUtil.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java"));
supportingFiles.add(new SupportingFile("apiException.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java"));
supportingFiles.add(new SupportingFile("Pair.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Pair.java"));
supportingFiles.add(new SupportingFile("request/getrequest.mustache",
(sourceFolder + File.separator + requestPackage).replace(".", java.io.File.separator), "GetRequest.java"));
supportingFiles.add(new SupportingFile("request/postrequest.mustache",
(sourceFolder + File.separator + requestPackage).replace(".", java.io.File.separator), "PostRequest.java"));
supportingFiles.add(new SupportingFile("request/putrequest.mustache",
(sourceFolder + File.separator + requestPackage).replace(".", java.io.File.separator), "PutRequest.java"));
supportingFiles.add(new SupportingFile("request/deleterequest.mustache",
(sourceFolder + File.separator + requestPackage).replace(".", java.io.File.separator), "DeleteRequest.java"));
supportingFiles.add(new SupportingFile("request/patchrequest.mustache",
(sourceFolder + File.separator + requestPackage).replace(".", java.io.File.separator), "PatchRequest.java"));
supportingFiles.add(new SupportingFile("auth/apikeyauth.mustache",
(sourceFolder + File.separator + authPackage).replace(".", java.io.File.separator), "ApiKeyAuth.java"));
supportingFiles.add(new SupportingFile("auth/httpbasicauth.mustache",
(sourceFolder + File.separator + authPackage).replace(".", java.io.File.separator), "HttpBasicAuth.java"));
supportingFiles.add(new SupportingFile("auth/authentication.mustache",
(sourceFolder + File.separator + authPackage).replace(".", java.io.File.separator), "Authentication.java"));
}
public Boolean getUseAndroidMavenGradlePlugin() {
return useAndroidMavenGradlePlugin;
}
public void setUseAndroidMavenGradlePlugin(Boolean useAndroidMavenGradlePlugin) {
this.useAndroidMavenGradlePlugin = useAndroidMavenGradlePlugin;
}
public void setInvokerPackage(String invokerPackage) {
this.invokerPackage = invokerPackage;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public void setArtifactVersion(String artifactVersion) {
this.artifactVersion = artifactVersion;
}
public void setSourceFolder(String sourceFolder) {
this.sourceFolder = sourceFolder;
}
}

View File

@ -5,7 +5,6 @@ import {{invokerPackage}}.Pair;
import java.util.Map;
import java.util.List;
{{>generatedAnnotation}}
public interface Authentication {
/** Apply authentication settings to header and query params. */
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams);

View File

@ -1,4 +1,5 @@
io.swagger.codegen.languages.AndroidClientCodegen
io.swagger.codegen.languages.AndroidVolleyClientCodegen
io.swagger.codegen.languages.AsyncScalaClientCodegen
io.swagger.codegen.languages.CSharpClientCodegen
io.swagger.codegen.languages.DartClientCodegen

View File

@ -0,0 +1,38 @@
package {{invokerPackage}};
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;
}
}

View File

@ -0,0 +1,140 @@
package {{package}};
import {{invokerPackage}}.Responses;
import {{invokerPackage}}.ApiInvoker;
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.Pair;
import {{modelPackage}}.*;
import java.util.*;
import com.android.volley.Response;
import com.android.volley.VolleyError;
{{#imports}}import {{import}};
{{/imports}}
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import java.util.Map;
import java.util.HashMap;
import java.io.File;
{{#operations}}
public class {{classname}} {
String basePath = "{{basePath}}";
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public void addHeader(String key, String value) {
getInvoker().addDefaultHeader(key, value);
}
public ApiInvoker getInvoker() {
return apiInvoker;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return basePath;
}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}} * @param {{paramName}} {{description}}
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
public void {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}, {{/hasMore}}{{/allParams}}final {{#returnBaseType}}Responses.{{returnBaseType}}{{#isListContainer}}List{{/isListContainer}}Response{{/returnBaseType}}{{^returnBaseType}}Responses.StringResponse{{/returnBaseType}} responseListener, final Response.ErrorListener errorListener) {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
VolleyError error = new VolleyError("Missing the required parameter '{{paramName}}' when calling {{nickname}}",
new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"));
}
{{/required}}{{/allParams}}
// create path and map variables
String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
{{#queryParams}}
queryParams.addAll(ApiInvoker.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));
{{/queryParams}}
{{#headerParams}}
headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
{{/headerParams}}
String[] contentTypes = {
{{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}}
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
{{#formParams}}{{#notFile}}
if ({{paramName}} != null) {
builder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8);
}
{{/notFile}}{{#isFile}}
if ({{paramName}} != null) {
builder.addBinaryBody("{{baseName}}", {{paramName}});
}
{{/isFile}}{{/formParams}}
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
{{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}}
{{/formParams}}
}
String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
try {
apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
{{#returnType}}
try {
responseListener.onResponse(({{{returnType}}}) ApiInvoker.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class));
{{/returnType}}
{{^returnType}}
responseListener.onResponse(response);
{{/returnType}}
{{#returnType}}
} catch (ApiException exception) {
errorListener.onErrorResponse(new VolleyError(exception));
}
{{/returnType}}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,29 @@
package {{invokerPackage}};
public class ApiException extends Exception {
int code = 0;
String message = null;
public ApiException() {}
public ApiException(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@ -0,0 +1,439 @@
package {{invokerPackage}};
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.gson.JsonParseException;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import {{invokerPackage}}.auth.Authentication;
import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.request.GetRequest;
import {{invokerPackage}}.request.PostRequest;
import {{invokerPackage}}.request.PutRequest;
import {{invokerPackage}}.request.DeleteRequest;
import {{invokerPackage}}.request.PatchRequest;
public class ApiInvoker {
private static ApiInvoker INSTANCE;
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Context context;
private RequestQueue mRequestQueue;
private Map<String, Authentication> authentications;
/** Content type "text/plain" with UTF-8 encoding. */
public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8);
/**
* ISO 8601 date time format.
* @see https://en.wikipedia.org/wiki/ISO_8601
*/
public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
/**
* ISO 8601 date format.
* @see https://en.wikipedia.org/wiki/ISO_8601
*/
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
static {
// Use UTC as the default time zone.
DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public static void setUserAgent(String userAgent) {
INSTANCE.addDefaultHeader("User-Agent", userAgent);
}
public static Date parseDateTime(String str) {
try {
return DATE_TIME_FORMAT.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
public static Date parseDate(String str) {
try {
return DATE_FORMAT.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
public static String formatDateTime(Date datetime) {
return DATE_TIME_FORMAT.format(datetime);
}
public static String formatDate(Date date) {
return DATE_FORMAT.format(date);
}
public static 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 static 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;
}
public static void initializeInstance(Context context) {
INSTANCE = new ApiInvoker(context);
setUserAgent("Android-Volley-Swagger");
// Setup authentications (key: authentication name, value: authentication).
INSTANCE.authentications = new HashMap<String, Authentication>();
{{#authMethods}}
{{#isApiKey}}
INSTANCE.authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));
{{/isApiKey}}
{{#isBasic}}
INSTANCE.authentications.put("{{name}}", new HttpBasicAuth());
{{/isBasic}}
{{/authMethods}}
// Prevent the authentications from being modified.
INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications);
}
private ApiInvoker(Context context) {
this.context = context;
initConnectionManager();
}
public ApiInvoker() {
initConnectionManager();
}
public static ApiInvoker getInstance() {
return INSTANCE;
}
public void addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
}
public String escapeString(String str) {
return str;
}
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
try{
if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
return JsonUtil.deserializeToList(json, cls);
}
else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 1);
else
return json;
}
else {
return JsonUtil.deserializeToObject(json, cls);
}
}
catch (JsonParseException e) {
throw new ApiException(500, e.getMessage());
}
}
public static String serialize(Object obj) throws ApiException {
try {
if (obj != null)
return JsonUtil.serialize(obj);
else
return null;
}
catch (Exception e) {
throw new ApiException(500, e.getMessage());
}
}
/**
* 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!");
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
*/
private 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);
}
}
public void invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException {
StringBuilder b = new StringBuilder();
b.append("?");
updateParamsForAuth(authNames, queryParams, headerParams);
if (queryParams != null){
for (Pair queryParam : queryParams){
if (!queryParam.getName().isEmpty()) {
b.append(escapeString(queryParam.getName()));
b.append("=");
b.append(escapeString(queryParam.getValue()));
b.append("&");
}
}
}
String querystring = b.substring(0, b.length() - 1);
String url = host + path + querystring;
HashMap<String, String> headers = new HashMap<String, String>();
for(String key : headerParams.keySet()) {
headers.put(key, headerParams.get(key));
}
for(String key : defaultHeaderMap.keySet()) {
if(!headerParams.containsKey(key)) {
headers.put(key, defaultHeaderMap.get(key));
}
}
headers.put("Accept", "application/json");
// URL encoded string from form parameters
String formParamStr = null;
// for form data
if ("application/x-www-form-urlencoded".equals(contentType)) {
StringBuilder formParamBuilder = new StringBuilder();
// encode the form params
for (String key : formParams.keySet()) {
String value = formParams.get(key);
if (value != null && !"".equals(value.trim())) {
if (formParamBuilder.length() > 0) {
formParamBuilder.append("&");
}
try {
formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8"));
}
catch (Exception e) {
// move on to next
}
}
}
formParamStr = formParamBuilder.toString();
}
if ("GET".equals(method)) {
GetRequest request = new GetRequest(url, headers, null, stringRequest, errorListener);
mRequestQueue.add(request);
}
else if ("POST".equals(method)) {
PostRequest request = null;
if (formParamStr != null) {
request = new PostRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEntity) {
request = new PostRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener);
} else {
request = new PostRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
}
if(request != null) mRequestQueue.add(request);
}
else if ("PUT".equals(method)) {
PutRequest request = null;
if (formParamStr != null) {
request = new PutRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEntity) {
request = new PutRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener);
} else {
request = new PutRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
}
if(request != null) mRequestQueue.add(request);
}
else if ("DELETE".equals(method)) {
DeleteRequest request = null;
if (formParamStr != null) {
request = new DeleteRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEntity) {
request = new DeleteRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener);
} else {
request = new DeleteRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
}
if(request != null) mRequestQueue.add(request);
}
else if ("PATCH".equals(method)) {
PatchRequest request = null;
if (formParamStr != null) {
request = new PatchRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEntity) {
request = new PatchRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener);
} else {
request = new PatchRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
}
if(request != null) mRequestQueue.add(request);
}
}
private void initConnectionManager() {
mRequestQueue = Volley.newRequestQueue(context);
}
}

View File

@ -0,0 +1,58 @@
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
import java.util.Map;
import java.util.List;
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);
}
}
}

View File

@ -0,0 +1,11 @@
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
import java.util.Map;
import java.util.List;
public interface Authentication {
/** Apply authentication settings to header and query params. */
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams);
}

View File

@ -0,0 +1,35 @@
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
import android.util.Base64;
import java.util.Map;
import java.util.List;
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);
headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes(), Base64.DEFAULT));
}
}

View File

@ -0,0 +1,91 @@
{{#useAndroidMavenGradlePlugin}}
group = '{{groupId}}'
project.version = '{{artifactVersion}}'
{{/useAndroidMavenGradlePlugin}}
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
{{#useAndroidMavenGradlePlugin}}
classpath 'com.github.dcendents:android-maven-plugin:1.2'
{{/useAndroidMavenGradlePlugin}}
}
}
allprojects {
repositories {
jcenter()
}
}
apply plugin: 'com.android.library'
{{#useAndroidMavenGradlePlugin}}
apply plugin: 'com.github.dcendents.android-maven'
{{/useAndroidMavenGradlePlugin}}
android {
compileSdkVersion 22
buildToolsVersion '22.0.0'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
ext {
swagger_annotations_version = "1.5.0"
gson_version = "2.3.1"
httpclient_version = "4.3.3"
junit_version = "4.8.1"
}
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.gson:gson:$gson_version"
compile "org.apache.httpcomponents:httpcore:$httpclient_version"
compile "org.apache.httpcomponents:httpmime:$httpclient_version"
testCompile "junit:junit:$junit_version"
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
{{#useAndroidMavenGradlePlugin}}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
{{/useAndroidMavenGradlePlugin}}

View File

@ -0,0 +1,55 @@
package {{invokerPackage}};
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import {{modelPackage}}.*;
public class JsonUtil {
public static GsonBuilder gsonBuilder;
static {
gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
}
public static Gson getGson() {
return gsonBuilder.create();
}
public static String serialize(Object obj){
return getGson().toJson(obj);
}
public static <T> T deserializeToList(String jsonString, Class cls){
return getGson().fromJson(jsonString, getListTypeForDeserialization(cls));
}
public static <T> T deserializeToObject(String jsonString, Class cls){
return getGson().fromJson(jsonString, getTypeForDeserialization(cls));
}
public static Type getListTypeForDeserialization(Class cls) {
String className = cls.getSimpleName();
{{#models}}{{#model}}
if ("{{classname}}".equalsIgnoreCase(className)) {
return new TypeToken<List<{{classname}}>>(){}.getType();
}
{{/model}}{{/models}}
return new TypeToken<List<Object>>(){}.getType();
}
public static Type getTypeForDeserialization(Class cls) {
String className = cls.getSimpleName();
{{#models}}{{#model}}
if ("{{classname}}".equalsIgnoreCase(className)) {
return new TypeToken<{{classname}}>(){}.getType();
}
{{/model}}{{/models}}
return new TypeToken<Object>(){}.getType();
}
};

View File

@ -0,0 +1,5 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="{{invokerPackage}}">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application />
</manifest>

View File

@ -0,0 +1,52 @@
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
{{#models}}
{{#model}}{{#description}}
/**
* {{description}}
**/{{/description}}
@ApiModel(description = "{{{description}}}")
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
{{#vars}}{{#isEnum}}
public enum {{datatypeWithEnum}} {
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
};
@SerializedName("{{baseName}}")
private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}}
@SerializedName("{{baseName}}")
private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/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(" " + super.toString()).append("\n");{{/parent}}
{{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n");
{{/vars}}sb.append("}\n");
return sb.toString();
}
}
{{/model}}
{{/models}}

View File

@ -0,0 +1,86 @@
package {{invokerPackage}}.request;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.HttpEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class DeleteRequest extends Request<String> {
HttpEntity entity;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public DeleteRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.DELETE, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
}

View File

@ -0,0 +1,39 @@
package {{invokerPackage}}.request;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class GetRequest extends StringRequest{
Map<String, String> apiHeaders;
String contentType;
public GetRequest(String url, Map<String, String> apiHeaders, String contentType, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, listener, errorListener);
this.apiHeaders = apiHeaders;
this.contentType = contentType;
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
}

View File

@ -0,0 +1,86 @@
package {{invokerPackage}}.request;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.HttpEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class PatchRequest extends Request<String> {
HttpEntity entity;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public PatchRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.PATCH, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
}

View File

@ -0,0 +1,86 @@
package {{invokerPackage}}.request;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.HttpEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class PostRequest extends Request<String> {
HttpEntity entity;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public PostRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
}

View File

@ -0,0 +1,86 @@
package {{invokerPackage}}.request;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.HttpEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class PutRequest extends Request<String> {
HttpEntity entity;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public PutRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.PUT, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
}

View File

@ -0,0 +1,24 @@
package {{invokerPackage}};
import java.util.List;
import {{modelPackage}}.*;
public class Responses {
{{#models}}
{{#model}}
public static interface {{classname}}Response {
public void onResponse({{classname}} {{classVarName}});
}
public static interface {{classname}}ListResponse {
public void onResponse(List<{{classname}}> {{classVarName}}List);
}
{{/model}}
{{/models}}
public static interface StringResponse {
public void onResponse(String response);
}
public static interface StringListResponse {
public void onResponse(List<String> stringList);
}
}

View File

@ -0,0 +1,48 @@
package io.swagger.codegen.androidvolley;
import io.swagger.codegen.AbstractOptionsTest;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.languages.AndroidVolleyClientCodegen;
import io.swagger.codegen.options.AndroidClientOptionsProvider;
import io.swagger.codegen.options.AndroidVolleyClientOptionsProvider;
import mockit.Expectations;
import mockit.Tested;
public class AndroidVolleyClientOptionsTest extends AbstractOptionsTest {
@Tested
private AndroidVolleyClientCodegen clientCodegen;
public AndroidVolleyClientOptionsTest() {
super(new AndroidVolleyClientOptionsProvider());
}
@Override
protected CodegenConfig getCodegenConfig() {
return clientCodegen;
}
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{
clientCodegen.setModelPackage(AndroidVolleyClientOptionsProvider.MODEL_PACKAGE_VALUE);
times = 1;
clientCodegen.setApiPackage(AndroidVolleyClientOptionsProvider.API_PACKAGE_VALUE);
times = 1;
clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(AndroidVolleyClientOptionsProvider.SORT_PARAMS_VALUE));
times = 1;
clientCodegen.setInvokerPackage(AndroidVolleyClientOptionsProvider.INVOKER_PACKAGE_VALUE);
times = 1;
clientCodegen.setGroupId(AndroidVolleyClientOptionsProvider.GROUP_ID_VALUE);
times = 1;
clientCodegen.setArtifactId(AndroidVolleyClientOptionsProvider.ARTIFACT_ID_VALUE);
times = 1;
clientCodegen.setArtifactVersion(AndroidVolleyClientOptionsProvider.ARTIFACT_VERSION_VALUE);
times = 1;
clientCodegen.setSourceFolder(AndroidVolleyClientOptionsProvider.SOURCE_FOLDER_VALUE);
times = 1;
clientCodegen.setUseAndroidMavenGradlePlugin(Boolean.valueOf(AndroidVolleyClientOptionsProvider.ANDROID_MAVEN_GRADLE_PLUGIN_VALUE));
times = 1;
}};
}
}

View File

@ -0,0 +1,47 @@
package io.swagger.codegen.options;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.languages.AndroidVolleyClientCodegen;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
public class AndroidVolleyClientOptionsProvider implements OptionsProvider {
public static final String ARTIFACT_ID_VALUE = "swagger-java-client-test";
public static final String MODEL_PACKAGE_VALUE = "package";
public static final String API_PACKAGE_VALUE = "apiPackage";
public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test";
public static final String SORT_PARAMS_VALUE = "false";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
public static final String GROUP_ID_VALUE = "io.swagger.test";
public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT";
public static final String SOURCE_FOLDER_VALUE = "src/main/java/test";
public static final String ANDROID_MAVEN_GRADLE_PLUGIN_VALUE = "true";
@Override
public String getLanguage() {
return "android-volley";
}
@Override
public Map<String, String> createOptions() {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE)
.put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE)
.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
.put(CodegenConstants.INVOKER_PACKAGE, INVOKER_PACKAGE_VALUE)
.put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE)
.put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE)
.put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE)
.put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE)
.put(AndroidVolleyClientCodegen.USE_ANDROID_MAVEN_GRADLE_PLUGIN, ANDROID_MAVEN_GRADLE_PLUGIN_VALUE)
.build();
}
@Override
public boolean isServer() {
return false;
}
}

View File

@ -0,0 +1,93 @@
group = 'io.swagger'
project.version = '1.0.0'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'
}
}
allprojects {
repositories {
jcenter()
}
}
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 23
buildToolsVersion '23.0.2'
defaultConfig {
minSdkVersion 14
targetSdkVersion 23
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
ext {
swagger_annotations_version = "1.5.0"
gson_version = "2.3.1"
httpclient_version = "4.3.3"
junit_version = "4.8.1"
volley_version = "1.0.19"
}
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.gson:gson:$gson_version"
compile "org.apache.httpcomponents:httpcore:$httpclient_version"
compile "org.apache.httpcomponents:httpmime:$httpclient_version"
compile "com.mcxiaoke.volley:library:${volley_version}@aar"
testCompile "junit:junit:$junit_version"
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}

View File

@ -0,0 +1,5 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.swagger.client">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application />
</manifest>

View File

@ -0,0 +1,29 @@
package io.swagger.client;
public class ApiException extends Exception {
int code = 0;
String message = null;
public ApiException() {}
public ApiException(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@ -0,0 +1,440 @@
package io.swagger.client;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.gson.JsonParseException;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import io.swagger.client.auth.Authentication;
import io.swagger.client.auth.ApiKeyAuth;
import io.swagger.client.auth.HttpBasicAuth;
import io.swagger.client.request.GetRequest;
import io.swagger.client.request.PostRequest;
import io.swagger.client.request.PutRequest;
import io.swagger.client.request.DeleteRequest;
import io.swagger.client.request.PatchRequest;
public class ApiInvoker {
private static ApiInvoker INSTANCE;
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Context context;
private RequestQueue mRequestQueue;
private Map<String, Authentication> authentications;
/** Content type "text/plain" with UTF-8 encoding. */
public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8);
/**
* ISO 8601 date time format.
* @see https://en.wikipedia.org/wiki/ISO_8601
*/
public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
/**
* ISO 8601 date format.
* @see https://en.wikipedia.org/wiki/ISO_8601
*/
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
static {
// Use UTC as the default time zone.
DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public static void setUserAgent(String userAgent) {
INSTANCE.addDefaultHeader("User-Agent", userAgent);
}
public static Date parseDateTime(String str) {
try {
return DATE_TIME_FORMAT.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
public static Date parseDate(String str) {
try {
return DATE_FORMAT.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
public static String formatDateTime(Date datetime) {
return DATE_TIME_FORMAT.format(datetime);
}
public static String formatDate(Date date) {
return DATE_FORMAT.format(date);
}
public static 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 static 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;
}
public static void initializeInstance(Context context) {
INSTANCE = new ApiInvoker(context);
setUserAgent("Android-Volley-Swagger");
// Setup authentications (key: authentication name, value: authentication).
INSTANCE.authentications = new HashMap<String, Authentication>();
INSTANCE.authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
// Prevent the authentications from being modified.
INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications);
}
private ApiInvoker(Context context) {
this.context = context;
initConnectionManager();
}
public ApiInvoker() {
initConnectionManager();
}
public static ApiInvoker getInstance() {
return INSTANCE;
}
public void addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
}
public String escapeString(String str) {
return str;
}
public static Object deserialize(String json, String containerType, Class cls) throws ApiException {
try{
if("list".equalsIgnoreCase(containerType) || "array".equalsIgnoreCase(containerType)) {
return JsonUtil.deserializeToList(json, cls);
}
else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 1);
else
return json;
}
else {
return JsonUtil.deserializeToObject(json, cls);
}
}
catch (JsonParseException e) {
throw new ApiException(500, e.getMessage());
}
}
public static String serialize(Object obj) throws ApiException {
try {
if (obj != null)
return JsonUtil.serialize(obj);
else
return null;
}
catch (Exception e) {
throw new ApiException(500, e.getMessage());
}
}
/**
* 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!");
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
*/
private 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);
}
}
public void invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames, Response.Listener<String> stringRequest, Response.ErrorListener errorListener) throws ApiException {
StringBuilder b = new StringBuilder();
b.append("?");
updateParamsForAuth(authNames, queryParams, headerParams);
if (queryParams != null){
for (Pair queryParam : queryParams){
if (!queryParam.getName().isEmpty()) {
b.append(escapeString(queryParam.getName()));
b.append("=");
b.append(escapeString(queryParam.getValue()));
b.append("&");
}
}
}
String querystring = b.substring(0, b.length() - 1);
String url = host + path + querystring;
HashMap<String, String> headers = new HashMap<String, String>();
for(String key : headerParams.keySet()) {
headers.put(key, headerParams.get(key));
}
for(String key : defaultHeaderMap.keySet()) {
if(!headerParams.containsKey(key)) {
headers.put(key, defaultHeaderMap.get(key));
}
}
headers.put("Accept", "application/json");
// URL encoded string from form parameters
String formParamStr = null;
// for form data
if ("application/x-www-form-urlencoded".equals(contentType)) {
StringBuilder formParamBuilder = new StringBuilder();
// encode the form params
for (String key : formParams.keySet()) {
String value = formParams.get(key);
if (value != null && !"".equals(value.trim())) {
if (formParamBuilder.length() > 0) {
formParamBuilder.append("&");
}
try {
formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8"));
}
catch (Exception e) {
// move on to next
}
}
}
formParamStr = formParamBuilder.toString();
}
if ("GET".equals(method)) {
GetRequest request = new GetRequest(url, headers, null, stringRequest, errorListener);
mRequestQueue.add(request);
}
else if ("POST".equals(method)) {
PostRequest request = null;
if (formParamStr != null) {
request = new PostRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEntity) {
request = new PostRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener);
} else {
request = new PostRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
}
if(request != null) mRequestQueue.add(request);
}
else if ("PUT".equals(method)) {
PutRequest request = null;
if (formParamStr != null) {
request = new PutRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEntity) {
request = new PutRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener);
} else {
request = new PutRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
}
if(request != null) mRequestQueue.add(request);
}
else if ("DELETE".equals(method)) {
DeleteRequest request = null;
if (formParamStr != null) {
request = new DeleteRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEntity) {
request = new DeleteRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener);
} else {
request = new DeleteRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
}
if(request != null) mRequestQueue.add(request);
}
else if ("PATCH".equals(method)) {
PatchRequest request = null;
if (formParamStr != null) {
request = new PatchRequest(url, headers, contentType, new StringEntity(formParamStr, "UTF-8"), stringRequest, errorListener);
} else if (body != null) {
if (body instanceof HttpEntity) {
request = new PatchRequest(url, headers, null, (HttpEntity) body, stringRequest, errorListener);
} else {
request = new PatchRequest(url, headers, contentType, new StringEntity(serialize(body), "UTF-8"), stringRequest, errorListener);
}
}
if(request != null) mRequestQueue.add(request);
}
}
private void initConnectionManager() {
mRequestQueue = Volley.newRequestQueue(context);
}
}

View File

@ -0,0 +1,87 @@
package io.swagger.client;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import io.swagger.client.model.*;
public class JsonUtil {
public static GsonBuilder gsonBuilder;
static {
gsonBuilder = new GsonBuilder();
gsonBuilder.serializeNulls();
gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
}
public static Gson getGson() {
return gsonBuilder.create();
}
public static String serialize(Object obj){
return getGson().toJson(obj);
}
public static <T> T deserializeToList(String jsonString, Class cls){
return getGson().fromJson(jsonString, getListTypeForDeserialization(cls));
}
public static <T> T deserializeToObject(String jsonString, Class cls){
return getGson().fromJson(jsonString, getTypeForDeserialization(cls));
}
public static Type getListTypeForDeserialization(Class cls) {
String className = cls.getSimpleName();
if ("User".equalsIgnoreCase(className)) {
return new TypeToken<List<User>>(){}.getType();
}
if ("Category".equalsIgnoreCase(className)) {
return new TypeToken<List<Category>>(){}.getType();
}
if ("Pet".equalsIgnoreCase(className)) {
return new TypeToken<List<Pet>>(){}.getType();
}
if ("Tag".equalsIgnoreCase(className)) {
return new TypeToken<List<Tag>>(){}.getType();
}
if ("Order".equalsIgnoreCase(className)) {
return new TypeToken<List<Order>>(){}.getType();
}
return new TypeToken<List<Object>>(){}.getType();
}
public static Type getTypeForDeserialization(Class cls) {
String className = cls.getSimpleName();
if ("User".equalsIgnoreCase(className)) {
return new TypeToken<User>(){}.getType();
}
if ("Category".equalsIgnoreCase(className)) {
return new TypeToken<Category>(){}.getType();
}
if ("Pet".equalsIgnoreCase(className)) {
return new TypeToken<Pet>(){}.getType();
}
if ("Tag".equalsIgnoreCase(className)) {
return new TypeToken<Tag>(){}.getType();
}
if ("Order".equalsIgnoreCase(className)) {
return new TypeToken<Order>(){}.getType();
}
return new TypeToken<Object>(){}.getType();
}
};

View File

@ -0,0 +1,38 @@
package io.swagger.client;
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;
}
}

View File

@ -0,0 +1,53 @@
package io.swagger.client;
import java.util.List;
import io.swagger.client.model.*;
public class Responses {
public static interface UserResponse {
public void onResponse(User user);
}
public static interface UserListResponse {
public void onResponse(List<User> userList);
}
public static interface CategoryResponse {
public void onResponse(Category category);
}
public static interface CategoryListResponse {
public void onResponse(List<Category> categoryList);
}
public static interface PetResponse {
public void onResponse(Pet pet);
}
public static interface PetListResponse {
public void onResponse(List<Pet> petList);
}
public static interface TagResponse {
public void onResponse(Tag tag);
}
public static interface TagListResponse {
public void onResponse(List<Tag> tagList);
}
public static interface OrderResponse {
public void onResponse(Order order);
}
public static interface OrderListResponse {
public void onResponse(List<Order> orderList);
}
}

View File

@ -0,0 +1,647 @@
package io.swagger.client.api;
import io.swagger.client.Responses;
import io.swagger.client.ApiInvoker;
import io.swagger.client.ApiException;
import io.swagger.client.Pair;
import io.swagger.client.model.*;
import java.util.*;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import io.swagger.client.model.Pet;
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import java.util.Map;
import java.util.HashMap;
import java.io.File;
public class PetApi {
String basePath = "http://petstore.swagger.io/v2";
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public void addHeader(String key, String value) {
getInvoker().addDefaultHeader(key, value);
}
public ApiInvoker getInvoker() {
return apiInvoker;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return basePath;
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
* @return void
*/
public void updatePet (Pet body, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = body;
// create path and map variables
String path = "/pet".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
"application/json","application/xml"
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { "petstore_auth" };
try {
apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
* @return void
*/
public void addPet (Pet body, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = body;
// create path and map variables
String path = "/pet".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
"application/json","application/xml"
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { "petstore_auth" };
try {
apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* 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 void findPetsByStatus (List<String> status, final Responses.PetListResponse responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// create path and map variables
String path = "/pet/findByStatus".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
queryParams.addAll(ApiInvoker.parameterToPairs("multi", "status", status));
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { "petstore_auth" };
try {
apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
responseListener.onResponse((List<Pet>) ApiInvoker.deserialize(response, "array", Pet.class));
} catch (ApiException exception) {
errorListener.onErrorResponse(new VolleyError(exception));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* 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 void findPetsByTags (List<String> tags, final Responses.PetListResponse responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// create path and map variables
String path = "/pet/findByTags".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
queryParams.addAll(ApiInvoker.parameterToPairs("multi", "tags", tags));
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { "petstore_auth" };
try {
apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
responseListener.onResponse((List<Pet>) ApiInvoker.deserialize(response, "array", Pet.class));
} catch (ApiException exception) {
errorListener.onErrorResponse(new VolleyError(exception));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return Pet
*/
public void getPetById (Long petId, final Responses.PetResponse responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling getPetById",
new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"));
}
// create path and map variables
String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { "api_key" };
try {
apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
responseListener.onResponse((Pet) ApiInvoker.deserialize(response, "", Pet.class));
} catch (ApiException exception) {
errorListener.onErrorResponse(new VolleyError(exception));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
* @return void
*/
public void updatePetWithForm (String petId, String name, String status, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling updatePetWithForm",
new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"));
}
// create path and map variables
String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
"application/x-www-form-urlencoded"
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (name != null) {
builder.addTextBody("name", ApiInvoker.parameterToString(name), ApiInvoker.TEXT_PLAIN_UTF8);
}
if (status != null) {
builder.addTextBody("status", ApiInvoker.parameterToString(status), ApiInvoker.TEXT_PLAIN_UTF8);
}
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
formParams.put("name", ApiInvoker.parameterToString(name));
formParams.put("status", ApiInvoker.parameterToString(status));
}
String[] authNames = new String[] { "petstore_auth" };
try {
apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
* @return void
*/
public void deletePet (Long petId, String apiKey, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling deletePet",
new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"));
}
// create path and map variables
String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
headerParams.put("api_key", ApiInvoker.parameterToString(apiKey));
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { "petstore_auth" };
try {
apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
* @return void
*/
public void uploadFile (Long petId, String additionalMetadata, File file, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling uploadFile",
new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"));
}
// create path and map variables
String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
"multipart/form-data"
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (additionalMetadata != null) {
builder.addTextBody("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata), ApiInvoker.TEXT_PLAIN_UTF8);
}
if (file != null) {
builder.addBinaryBody("file", file);
}
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
formParams.put("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata));
}
String[] authNames = new String[] { "petstore_auth" };
try {
apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
}

View File

@ -0,0 +1,339 @@
package io.swagger.client.api;
import io.swagger.client.Responses;
import io.swagger.client.ApiInvoker;
import io.swagger.client.ApiException;
import io.swagger.client.Pair;
import io.swagger.client.model.*;
import java.util.*;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import java.util.Map;
import io.swagger.client.model.Order;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import java.util.Map;
import java.util.HashMap;
import java.io.File;
public class StoreApi {
String basePath = "http://petstore.swagger.io/v2";
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public void addHeader(String key, String value) {
getInvoker().addDefaultHeader(key, value);
}
public ApiInvoker getInvoker() {
return apiInvoker;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return basePath;
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return Map<String, Integer>
*/
public void getInventory (final Responses.MapResponse responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// create path and map variables
String path = "/store/inventory".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { "api_key" };
try {
apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
responseListener.onResponse((Map<String, Integer>) ApiInvoker.deserialize(response, "map", Map.class));
} catch (ApiException exception) {
errorListener.onErrorResponse(new VolleyError(exception));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Order
*/
public void placeOrder (Order body, final Responses.OrderResponse responseListener, final Response.ErrorListener errorListener) {
Object postBody = body;
// create path and map variables
String path = "/store/order".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { };
try {
apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
responseListener.onResponse((Order) ApiInvoker.deserialize(response, "", Order.class));
} catch (ApiException exception) {
errorListener.onErrorResponse(new VolleyError(exception));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
public void getOrderById (String orderId, final Responses.OrderResponse responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling getOrderById",
new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"));
}
// create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { };
try {
apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
responseListener.onResponse((Order) ApiInvoker.deserialize(response, "", Order.class));
} catch (ApiException exception) {
errorListener.onErrorResponse(new VolleyError(exception));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
* @return void
*/
public void deleteOrder (String orderId, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling deleteOrder",
new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"));
}
// create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { };
try {
apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
}

View File

@ -0,0 +1,610 @@
package io.swagger.client.api;
import io.swagger.client.Responses;
import io.swagger.client.ApiInvoker;
import io.swagger.client.ApiException;
import io.swagger.client.Pair;
import io.swagger.client.model.*;
import java.util.*;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import io.swagger.client.model.User;
import java.util.*;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import java.util.Map;
import java.util.HashMap;
import java.io.File;
public class UserApi {
String basePath = "http://petstore.swagger.io/v2";
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public void addHeader(String key, String value) {
getInvoker().addDefaultHeader(key, value);
}
public ApiInvoker getInvoker() {
return apiInvoker;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return basePath;
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
* @return void
*/
public void createUser (User body, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = body;
// create path and map variables
String path = "/user".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { };
try {
apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
*/
public void createUsersWithArrayInput (List<User> body, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = body;
// create path and map variables
String path = "/user/createWithArray".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { };
try {
apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return void
*/
public void createUsersWithListInput (List<User> body, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = body;
// create path and map variables
String path = "/user/createWithList".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { };
try {
apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @return String
*/
public void loginUser (String username, String password, final Responses.StringResponse responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// create path and map variables
String path = "/user/login".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
queryParams.addAll(ApiInvoker.parameterToPairs("", "username", username));
queryParams.addAll(ApiInvoker.parameterToPairs("", "password", password));
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { };
try {
apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
responseListener.onResponse((String) ApiInvoker.deserialize(response, "", String.class));
} catch (ApiException exception) {
errorListener.onErrorResponse(new VolleyError(exception));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Logs out current logged in user session
*
* @return void
*/
public void logoutUser (final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// create path and map variables
String path = "/user/logout".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { };
try {
apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
public void getUserByName (String username, final Responses.UserResponse responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
VolleyError error = new VolleyError("Missing the required parameter 'username' when calling getUserByName",
new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"));
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { };
try {
apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
responseListener.onResponse((User) ApiInvoker.deserialize(response, "", User.class));
} catch (ApiException exception) {
errorListener.onErrorResponse(new VolleyError(exception));
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param body Updated user object
* @return void
*/
public void updateUser (String username, User body, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = body;
// verify the required parameter 'username' is set
if (username == null) {
VolleyError error = new VolleyError("Missing the required parameter 'username' when calling updateUser",
new ApiException(400, "Missing the required parameter 'username' when calling updateUser"));
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { };
try {
apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return void
*/
public void deleteUser (String username, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
VolleyError error = new VolleyError("Missing the required parameter 'username' when calling deleteUser",
new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"));
}
// create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
}
String[] authNames = new String[] { };
try {
apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
responseListener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorListener.onErrorResponse(error);
}
});
} catch (ApiException ex) {
errorListener.onErrorResponse(new VolleyError(ex));
}
}
}

View File

@ -0,0 +1,58 @@
package io.swagger.client.auth;
import io.swagger.client.Pair;
import java.util.Map;
import java.util.List;
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);
}
}
}

View File

@ -0,0 +1,11 @@
package io.swagger.client.auth;
import io.swagger.client.Pair;
import java.util.Map;
import java.util.List;
public interface Authentication {
/** Apply authentication settings to header and query params. */
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams);
}

View File

@ -0,0 +1,54 @@
package io.swagger.client.model;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@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(id).append("\n");
sb.append(" name: ").append(name).append("\n");
sb.append("}\n");
return sb.toString();
}
}

View File

@ -0,0 +1,115 @@
package io.swagger.client.model;
import java.util.Date;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@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 {
placed, approved, delivered,
};
@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(id).append("\n");
sb.append(" petId: ").append(petId).append("\n");
sb.append(" quantity: ").append(quantity).append("\n");
sb.append(" shipDate: ").append(shipDate).append("\n");
sb.append(" status: ").append(status).append("\n");
sb.append(" complete: ").append(complete).append("\n");
sb.append("}\n");
return sb.toString();
}
}

View File

@ -0,0 +1,117 @@
package io.swagger.client.model;
import io.swagger.client.model.Category;
import java.util.*;
import io.swagger.client.model.Tag;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@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 = null;
@SerializedName("tags")
private List<Tag> tags = null;
public enum StatusEnum {
available, pending, sold,
};
@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(id).append("\n");
sb.append(" category: ").append(category).append("\n");
sb.append(" name: ").append(name).append("\n");
sb.append(" photoUrls: ").append(photoUrls).append("\n");
sb.append(" tags: ").append(tags).append("\n");
sb.append(" status: ").append(status).append("\n");
sb.append("}\n");
return sb.toString();
}
}

View File

@ -0,0 +1,54 @@
package io.swagger.client.model;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@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(id).append("\n");
sb.append(" name: ").append(name).append("\n");
sb.append("}\n");
return sb.toString();
}
}

View File

@ -0,0 +1,139 @@
package io.swagger.client.model;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@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(id).append("\n");
sb.append(" username: ").append(username).append("\n");
sb.append(" firstName: ").append(firstName).append("\n");
sb.append(" lastName: ").append(lastName).append("\n");
sb.append(" email: ").append(email).append("\n");
sb.append(" password: ").append(password).append("\n");
sb.append(" phone: ").append(phone).append("\n");
sb.append(" userStatus: ").append(userStatus).append("\n");
sb.append("}\n");
return sb.toString();
}
}

View File

@ -0,0 +1,86 @@
package io.swagger.client.request;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.HttpEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class DeleteRequest extends Request<String> {
HttpEntity entity;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public DeleteRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.DELETE, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
}

View File

@ -0,0 +1,39 @@
package io.swagger.client.request;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class GetRequest extends StringRequest{
Map<String, String> apiHeaders;
String contentType;
public GetRequest(String url, Map<String, String> apiHeaders, String contentType, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, listener, errorListener);
this.apiHeaders = apiHeaders;
this.contentType = contentType;
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
}

View File

@ -0,0 +1,86 @@
package io.swagger.client.request;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.HttpEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class PatchRequest extends Request<String> {
HttpEntity entity;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public PatchRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.PATCH, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
}

View File

@ -0,0 +1,86 @@
package io.swagger.client.request;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.HttpEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class PostRequest extends Request<String> {
HttpEntity entity;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public PostRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
}

View File

@ -0,0 +1,86 @@
package io.swagger.client.request;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import org.apache.http.HttpEntity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class PutRequest extends Request<String> {
HttpEntity entity;
private final Response.Listener<String> mListener;
String contentType;
Map<String, String> apiHeaders;
public PutRequest(String url, Map<String, String> apiHeaders, String contentType, HttpEntity entity, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.PUT, url, errorListener);
mListener = listener;
this.entity = entity;
this.contentType = contentType;
this.apiHeaders = apiHeaders;
}
@Override
public String getBodyContentType() {
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
/* (non-Javadoc)
* @see com.android.volley.Request#getHeaders()
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) {
headers.putAll(apiHeaders);
}
if(contentType != null) {
headers.put("Content-Type", contentType);
}
return headers;
}
}