diff --git a/README.md b/README.md index b43351aa619..f288e847b09 100644 --- a/README.md +++ b/README.md @@ -264,6 +264,7 @@ CONFIG OPTIONS library template (sub-template) to use: - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 jersey2 - HTTP client: Jersey client 2.6 + okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 ``` Your config file for java can look like diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 23c2935ed2a..5b044167e7b 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -25,6 +25,7 @@ cd $APP_DIR ./bin/html-petstore.sh ./bin/java-petstore.sh ./bin/java-petstore-jersey2.sh +./bin/java-petstore-okhttp-gson.sh ./bin/jaxrs-petstore-server.sh ./bin/nodejs-petstore-server.sh ./bin/objc-petstore.sh diff --git a/bin/java-petstore-okhttp-gson.json b/bin/java-petstore-okhttp-gson.json new file mode 100644 index 00000000000..b894d172630 --- /dev/null +++ b/bin/java-petstore-okhttp-gson.json @@ -0,0 +1,4 @@ +{ + "library": "okhttp-gson", + "artifactId": "swagger-petstore-okhttp-gson" +} diff --git a/bin/java-petstore-okhttp-gson.sh b/bin/java-petstore-okhttp-gson.sh new file mode 100755 index 00000000000..17a48ddee53 --- /dev/null +++ b/bin/java-petstore-okhttp-gson.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index 326d98010d6..fc72cbd21c5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -83,6 +83,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportedLibraries.put("", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); + supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); cliOptions.add(buildLibraryCliOption(supportedLibraries)); } @@ -159,7 +160,19 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); - supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); + + // library-specific files + if ("okhttp-gson".equals(getLibrary())) { + // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call + supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); + // "build.gradle" is for development with Gradle + supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + // "build.sbt" is for development with SBT + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); + // and does not require "TypeRef.mustache" + } else { + supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); + } final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); diff --git a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache index 073966b0c21..c9583f1bc63 100644 --- a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache @@ -39,4 +39,13 @@ public class StringUtil { } return out.toString(); } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + public static String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache index bb3b53b0aeb..b9a62a6b231 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache @@ -6,20 +6,45 @@ import java.util.List; {{>generatedAnnotation}} public class ApiException extends Exception { private int code = 0; - private String message = null; private Map> responseHeaders = null; private String responseBody = null; public ApiException() {} - public ApiException(int code, String message) { + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); this.code = code; - this.message = message; } public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this.code = code; - this.message = message; + this(code, message); this.responseHeaders = responseHeaders; this.responseBody = responseBody; } @@ -28,10 +53,6 @@ public class ApiException extends Exception { return code; } - public String getMessage() { - return message; - } - /** * Get the HTTP response headers. */ diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache new file mode 100644 index 00000000000..4af16c9faa9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache @@ -0,0 +1,22 @@ +package {{invokerPackage}}; + +import java.io.IOException; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + */ + void onFailure(ApiException e); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + */ + void onSuccess(T result); +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache new file mode 100644 index 00000000000..069aa273b14 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -0,0 +1,762 @@ +package {{invokerPackage}}; + +import com.squareup.okhttp.Call; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.FormEncodingBuilder; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.Headers; + +import java.lang.reflect.Type; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; +import java.util.regex.Pattern; + +import java.net.URLEncoder; +import java.net.URLConnection; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import {{invokerPackage}}.auth.Authentication; +import {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.auth.OAuth; + +public class ApiClient { + private String basePath = "{{basePath}}"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + + private Map authentications; + + private String dateFormat; + private DateFormat dateFormatter; + private int dateLength; + + private String datetimeFormat; + private DateFormat datetimeFormatter; + + private OkHttpClient httpClient; + private JSON json; + + public ApiClient() { + httpClient = new OkHttpClient(); + + json = new JSON(this); + + // Use ISO 8601 format for date and datetime. + // See https://en.wikipedia.org/wiki/ISO_8601 + setDateFormat("yyyy-MM-dd"); + setDatetimeFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + // Set default User-Agent. + setUserAgent("Java-Swagger"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap();{{#authMethods}}{{#isBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public OkHttpClient getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + public JSON getJSON() { + return json; + } + + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + public String getDateFormat() { + return dateFormat; + } + + public ApiClient setDateFormat(String dateFormat) { + this.dateFormat = dateFormat; + + this.dateFormatter = new SimpleDateFormat(dateFormat); + // Use UTC as the default time zone. + this.dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); + + this.dateLength = this.dateFormatter.format(new Date()).length(); + + return this; + } + + public String getDatetimeFormat() { + return datetimeFormat; + } + + public ApiClient setDatetimeFormat(String datetimeFormat) { + this.datetimeFormat = datetimeFormat; + + this.datetimeFormatter = new SimpleDateFormat(datetimeFormat); + // Note: The datetime formatter uses the system's default time zone. + + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + */ + public Date parseDate(String str) { + if (str == null) + return null; + try { + return dateFormatter.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given date-time string into Date object. + * The default datetimeFormat supports these ISO 8601 datetime formats: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see https://en.wikipedia.org/wiki/ISO_8601 + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + if ("yyyy-MM-dd'T'HH:mm:ss.SSSZ".equals(datetimeFormat)) { + /* + * When the default datetime format is used, process the given string + * to support various formats defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + } + + try { + return datetimeFormatter.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormatter.format(date); + } + + /** + * Format the given Date object into string. + */ + public String formatDatetime(Date date) { + return datetimeFormatter.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + return this; + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + Format to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according the Content-Type + * response header. + * + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + */ + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) + return null; + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) + return null; + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (contentType.startsWith("application/json")) { + return json.deserialize(respBody, returnType); + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported", + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body string, according to the + * request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized string + */ + public String serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + if (obj != null) + return json.serialize(obj); + else + return null; + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * @see #execute(Call, Type) + */ + public T execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @return The Java object deserialized from response body. Returns null if returnType is null. + */ + public T execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + return handleResponse(response, returnType); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * #see executeAsync(Call, Type, ApiCallback) + */ + public void executeAsync(Call call, ApiCallback callback) throws ApiException { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param The callback to be executed when the API call finishes + */ + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e)); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e); + return; + } + callback.onSuccess(result); + } + }); + } + + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @return The HTTP call + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) contentType = "application/json"; + + RequestBody reqBody; + if ("GET".equals(method) || "HEAD".equals(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); + } + + Request request; + if ("GET".equals(method)) { + request = reqBuilder.get().build(); + } else if ("HEAD".equals(method)) { + request = reqBuilder.head().build(); + } else if ("POST".equals(method)) { + request = reqBuilder.post(reqBody).build(); + } else if ("PUT".equals(method)) { + request = reqBuilder.put(reqBody).build(); + } else if ("PATCH".equals(method)) { + request = reqBuilder.patch(reqBody).build(); + } else if ("DELETE".equals(method)) { + if (reqBody == null) { + // calling DELETE without sending a request body + request = reqBuilder.delete().build(); + } else { + request = reqBuilder.delete(reqBody).build(); + } + } else { + throw new ApiException("unknown method type: " + method); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + StringBuilder query = new StringBuilder(); + if (queryParams != null) { + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (query.toString().length() == 0) + query.append("?"); + else + query.append("&"); + String value = parameterToString(param.getValue()); + query.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + return basePath + path + query.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The Content-Type guessed + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache new file mode 100644 index 00000000000..10a43d97de0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -0,0 +1,102 @@ +package {{invokerPackage}}; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.stream.JsonReader; + +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .serializeNulls() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .create(); + } + + public Gson getGson() { + return gson; + } + + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache new file mode 100644 index 00000000000..b272687c7fd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -0,0 +1,116 @@ +package {{package}}; + +import {{invokerPackage}}.ApiCallback; +import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.Configuration; +import {{invokerPackage}}.Pair; + +import {{modelPackage}}.*; + +import com.google.gson.reflect.TypeToken; + +import com.squareup.okhttp.Call; + +import java.lang.reflect.Type; + +import java.util.*; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +{{#operations}} +public class {{classname}} { + private ApiClient {{localVariablePrefix}}apiClient; + + public {{classname}}() { + this(Configuration.getDefaultApiClient()); + } + + public {{classname}}(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + public ApiClient getApiClient() { + return {{localVariablePrefix}}apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + {{#operation}} + /* Build call for {{nickname}} */ + private Call {{nickname}}Call({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{nickname}}(Async)"); + } + {{/required}}{{/allParams}} + + // create path and map variables + String {{localVariablePrefix}}path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} + .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + List {{localVariablePrefix}}queryParams = new ArrayList();{{#queryParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} + + Map {{localVariablePrefix}}headerParams = new HashMap();{{#headerParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} + + Map {{localVariablePrefix}}formParams = new HashMap();{{#formParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}});{{/formParams}} + + final String[] {{localVariablePrefix}}accepts = { + {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + final String {{localVariablePrefix}}accept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}accepts); + if ({{localVariablePrefix}}accept != null) {{localVariablePrefix}}headerParams.put("Accept", {{localVariablePrefix}}accept); + + final String[] {{localVariablePrefix}}contentTypes = { + {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + final String {{localVariablePrefix}}contentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}contentTypes); + {{localVariablePrefix}}headerParams.put("Content-Type", {{localVariablePrefix}}contentType); + + String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}authNames); + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}}{{#returnType}} + * @return {{{returnType}}}{{/returnType}} + */ + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + Call {{localVariablePrefix}}call = {{nickname}}Call({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}}Type {{localVariablePrefix}}returnType = new TypeToken<{{{returnType}}}>(){}.getType(); + return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}returnType);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} + } + + /** + * {{summary}} (asynchronously) + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call {{nickname}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { + Call {{localVariablePrefix}}call = {{nickname}}Call({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}}Type {{localVariablePrefix}}returnType = new TypeToken<{{{returnType}}}>(){}.getType(); + {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}returnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} + return {{localVariablePrefix}}call; + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache new file mode 100644 index 00000000000..5b4070fcafb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache @@ -0,0 +1,41 @@ +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; + +import com.migcomponents.migbase64.Base64; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache new file mode 100644 index 00000000000..1113d8b4ee9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache @@ -0,0 +1,28 @@ +apply plugin: 'java' +apply plugin: 'maven' + +repositories { + mavenCentral() +} + +dependencies { + compile 'io.swagger:swagger-annotations:1.5.0' + compile 'com.squareup.okhttp:okhttp:2.4.0' + compile 'com.google.code.gson:gson:2.3.1' + compile 'com.brsanthu:migbase64:2.2' + testCompile 'junit:junit:4.8.1' +} + +group = '{{groupId}}' +version = '{{artifactVersion}}' + +install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } +} + +task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache new file mode 100644 index 00000000000..b748f53e48d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache @@ -0,0 +1,18 @@ +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.0", + "com.squareup.okhttp" % "okhttp" % "2.4.0", + "com.google.code.gson" % "gson" % "2.3.1", + "com.brsanthu" % "migbase64" % "2.2", + "junit" % "junit" % "4.8.1" % "test" + ) + ) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache new file mode 100644 index 00000000000..cc00e9d392e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache @@ -0,0 +1,17 @@ +public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#enumVars}}@SerializedName("{{value}}") + {{name}}("{{value}}"){{^-last}}, + + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache new file mode 100644 index 00000000000..0987aa68f34 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache @@ -0,0 +1,58 @@ +package {{package}}; + +import {{invokerPackage}}.StringUtil; +{{#imports}}import {{import}}; +{{/imports}} + +import com.google.gson.annotations.SerializedName; + +{{#serializableModel}} +import java.io.Serializable;{{/serializableModel}} + +import io.swagger.annotations.*; + +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@ApiModel(description = "{{{description}}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { + {{#vars}}{{#isEnum}} + +{{>libraries/okhttp-gson/enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} + +{{>libraries/okhttp-gson/enumClass}}{{/items}}{{/items.isEnum}} + @SerializedName("{{baseName}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; + {{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache new file mode 100644 index 00000000000..67fc10e8323 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache @@ -0,0 +1,146 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + com.squareup.okhttp + okhttp + ${okhttp-version} + + + com.google.code.gson + gson + ${gson-version} + + + com.brsanthu + migbase64 + 2.2 + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.4.0 + 2.3.1 + 1.0.0 + 4.8.1 + + diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index bfb65a3d419..f5e48ba997f 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -1,5 +1,6 @@ package {{package}}; +import {{invokerPackage}}.StringUtil; {{#imports}}import {{import}}; {{/imports}} @@ -45,9 +46,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); - {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); - {{/vars}}sb.append("}\n"); + {{#parent}}sb.append(" ").append(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); return sb.toString(); } } diff --git a/pom.xml b/pom.xml index e7a93c0e052..ada6e427bad 100644 --- a/pom.xml +++ b/pom.xml @@ -328,6 +328,18 @@ samples/client/petstore/java/jersey2 + + java-client-okhttp-gson + + + env + java + + + + samples/client/petstore/java/okhttp-gson + + scala-client @@ -412,6 +424,7 @@ samples/client/petstore/android-java samples/client/petstore/java/default samples/client/petstore/java/jersey2 + samples/client/petstore/java/okhttp-gson samples/client/petstore/scala samples/server/petstore/spring-mvc diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle new file mode 100644 index 00000000000..96c8f7718d3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -0,0 +1,28 @@ +apply plugin: 'java' +apply plugin: 'maven' + +repositories { + mavenCentral() +} + +dependencies { + compile 'io.swagger:swagger-annotations:1.5.0' + compile 'com.squareup.okhttp:okhttp:2.4.0' + compile 'com.google.code.gson:gson:2.3.1' + compile 'com.brsanthu:migbase64:2.2' + testCompile 'junit:junit:4.8.1' +} + +group = 'io.swagger' +version = '1.0.0' + +install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-okhttp-gson' + } +} + +task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath +} diff --git a/samples/client/petstore/java/okhttp-gson/build.sbt b/samples/client/petstore/java/okhttp-gson/build.sbt new file mode 100644 index 00000000000..f70c7ea41c7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/build.sbt @@ -0,0 +1,18 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-okhttp-gson", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.0", + "com.squareup.okhttp" % "okhttp" % "2.4.0", + "com.google.code.gson" % "gson" % "2.3.1", + "com.brsanthu" % "migbase64" % "2.2", + "junit" % "junit" % "4.8.1" % "test" + ) + ) diff --git a/samples/client/petstore/java/okhttp-gson/hello.txt b/samples/client/petstore/java/okhttp-gson/hello.txt new file mode 100644 index 00000000000..6769dd60bdf --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml new file mode 100644 index 00000000000..2442e1c318e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -0,0 +1,146 @@ + + 4.0.0 + io.swagger + swagger-petstore-okhttp-gson + jar + swagger-petstore-okhttp-gson + 1.0.0 + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + com.squareup.okhttp + okhttp + ${okhttp-version} + + + com.google.code.gson + gson + ${gson-version} + + + com.brsanthu + migbase64 + 2.2 + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.4.0 + 2.3.1 + 1.0.0 + 4.8.1 + + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 00000000000..f8254311bce --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,22 @@ +package io.swagger.client; + +import java.io.IOException; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + */ + void onFailure(ApiException e); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + */ + void onSuccess(T result); +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..f189ea10238 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,761 @@ +package io.swagger.client; + +import com.squareup.okhttp.Call; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.FormEncodingBuilder; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.Headers; + +import java.lang.reflect.Type; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; +import java.util.regex.Pattern; + +import java.net.URLEncoder; +import java.net.URLConnection; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; + +public class ApiClient { + private String basePath = "http://petstore.swagger.io/v2"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + + private Map authentications; + + private String dateFormat; + private DateFormat dateFormatter; + private int dateLength; + + private String datetimeFormat; + private DateFormat datetimeFormatter; + + private OkHttpClient httpClient; + private JSON json; + + public ApiClient() { + httpClient = new OkHttpClient(); + + json = new JSON(this); + + // Use ISO 8601 format for date and datetime. + // See https://en.wikipedia.org/wiki/ISO_8601 + setDateFormat("yyyy-MM-dd"); + setDatetimeFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + // Set default User-Agent. + setUserAgent("Java-Swagger"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public OkHttpClient getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + public JSON getJSON() { + return json; + } + + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + public String getDateFormat() { + return dateFormat; + } + + public ApiClient setDateFormat(String dateFormat) { + this.dateFormat = dateFormat; + + this.dateFormatter = new SimpleDateFormat(dateFormat); + // Use UTC as the default time zone. + this.dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); + + this.dateLength = this.dateFormatter.format(new Date()).length(); + + return this; + } + + public String getDatetimeFormat() { + return datetimeFormat; + } + + public ApiClient setDatetimeFormat(String datetimeFormat) { + this.datetimeFormat = datetimeFormat; + + this.datetimeFormatter = new SimpleDateFormat(datetimeFormat); + // Note: The datetime formatter uses the system's default time zone. + + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + */ + public Date parseDate(String str) { + if (str == null) + return null; + try { + return dateFormatter.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given date-time string into Date object. + * The default datetimeFormat supports these ISO 8601 datetime formats: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see https://en.wikipedia.org/wiki/ISO_8601 + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + if ("yyyy-MM-dd'T'HH:mm:ss.SSSZ".equals(datetimeFormat)) { + /* + * When the default datetime format is used, process the given string + * to support various formats defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + } + + try { + return datetimeFormatter.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormatter.format(date); + } + + /** + * Format the given Date object into string. + */ + public String formatDatetime(Date date) { + return datetimeFormatter.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + return this; + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + Format to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according the Content-Type + * response header. + * + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + */ + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) + return null; + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) + return null; + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (contentType.startsWith("application/json")) { + return json.deserialize(respBody, returnType); + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported", + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body string, according to the + * request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized string + */ + public String serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + if (obj != null) + return json.serialize(obj); + else + return null; + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * @see #execute(Call, Type) + */ + public T execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @return The Java object deserialized from response body. Returns null if returnType is null. + */ + public T execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + return handleResponse(response, returnType); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * #see executeAsync(Call, Type, ApiCallback) + */ + public void executeAsync(Call call, ApiCallback callback) throws ApiException { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param The callback to be executed when the API call finishes + */ + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e)); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e); + return; + } + callback.onSuccess(result); + } + }); + } + + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @return The HTTP call + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) contentType = "application/json"; + + RequestBody reqBody; + if ("GET".equals(method) || "HEAD".equals(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); + } + + Request request; + if ("GET".equals(method)) { + request = reqBuilder.get().build(); + } else if ("HEAD".equals(method)) { + request = reqBuilder.head().build(); + } else if ("POST".equals(method)) { + request = reqBuilder.post(reqBody).build(); + } else if ("PUT".equals(method)) { + request = reqBuilder.put(reqBody).build(); + } else if ("PATCH".equals(method)) { + request = reqBuilder.patch(reqBody).build(); + } else if ("DELETE".equals(method)) { + if (reqBody == null) { + // calling DELETE without sending a request body + request = reqBuilder.delete().build(); + } else { + request = reqBuilder.delete(reqBody).build(); + } + } else { + throw new ApiException("unknown method type: " + method); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + StringBuilder query = new StringBuilder(); + if (queryParams != null) { + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (query.toString().length() == 0) + query.append("?"); + else + query.append("&"); + String value = parameterToString(param.getValue()); + query.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + return basePath + path + query.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The Content-Type guessed + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 00000000000..d19aa8ebb3a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,69 @@ +package io.swagger.client; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..07c97e116d7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,22 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 00000000000..f88639b9c82 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,102 @@ +package io.swagger.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.stream.JsonReader; + +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .serializeNulls() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .create(); + } + + public Gson getGson() { + return gson; + } + + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 00000000000..bb0cd823791 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,39 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 00000000000..9a58d6d5558 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,51 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + public static String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 00000000000..debe576dc9d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,527 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import io.swagger.client.model.*; + +import com.google.gson.reflect.TypeToken; + +import com.squareup.okhttp.Call; + +import java.lang.reflect.Type; + +import java.util.*; + +import io.swagger.client.model.Pet; +import java.io.File; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /* Build call for updatePet */ + private Call updatePetCall(Pet body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + "application/json", "application/xml" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "PUT", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public void updatePet(Pet body) throws ApiException { + Call call = updatePetCall(body); + apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call updatePetAsync(Pet body, ApiCallback callback) throws ApiException { + Call call = updatePetCall(body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for addPet */ + private Call addPetCall(Pet body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + "application/json", "application/xml" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + public void addPet(Pet body) throws ApiException { + Call call = addPetCall(body); + apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call addPetAsync(Pet body, ApiCallback callback) throws ApiException { + Call call = addPetCall(body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for findPetsByStatus */ + private Call findPetsByStatusCall(List status) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + if (status != null) + queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + * @return List + */ + public List findPetsByStatus(List status) throws ApiException { + Call call = findPetsByStatusCall(status); + Type returnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call findPetsByStatusAsync(List status, ApiCallback> callback) throws ApiException { + Call call = findPetsByStatusCall(status); + Type returnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for findPetsByTags */ + private Call findPetsByTagsCall(List tags) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + if (tags != null) + queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Finds Pets by tags + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @return List + */ + public List findPetsByTags(List tags) throws ApiException { + Call call = findPetsByTagsCall(tags); + Type returnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call findPetsByTagsAsync(List tags, ApiCallback> callback) throws ApiException { + Call call = findPetsByTagsCall(tags); + Type returnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for getPetById */ + private Call getPetByIdCall(Long petId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth", "api_key" }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return Pet + */ + public Pet getPetById(Long petId) throws ApiException { + Call call = getPetByIdCall(petId); + Type returnType = new TypeToken(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call getPetByIdAsync(Long petId, ApiCallback callback) throws ApiException { + Call call = getPetByIdCall(petId); + Type returnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for updatePetWithForm */ + private Call updatePetWithFormCall(String petId, String name, String status) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + if (name != null) + formParams.put("name", name); + if (status != null) + formParams.put("status", status); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + public void updatePetWithForm(String petId, String name, String status) throws ApiException { + Call call = updatePetWithFormCall(petId, name, status); + apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call updatePetWithFormAsync(String petId, String name, String status, ApiCallback callback) throws ApiException { + Call call = updatePetWithFormCall(petId, name, status); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for deletePet */ + private Call deletePetCall(Long petId, String apiKey) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + if (apiKey != null) + headerParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + Call call = deletePetCall(petId, apiKey); + apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete + * @param apiKey + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call deletePetAsync(Long petId, String apiKey, ApiCallback callback) throws ApiException { + Call call = deletePetCall(petId, apiKey); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for uploadFile */ + private Call uploadFileCall(Long petId, String additionalMetadata, File file) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + if (additionalMetadata != null) + formParams.put("additionalMetadata", additionalMetadata); + if (file != null) + formParams.put("file", file); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + "multipart/form-data" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + Call call = uploadFileCall(petId, additionalMetadata, file); + apiClient.execute(call); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call uploadFileAsync(Long petId, String additionalMetadata, File file, ApiCallback callback) throws ApiException { + Call call = uploadFileCall(petId, additionalMetadata, file); + apiClient.executeAsync(call, callback); + return call; + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..a3fb14bb521 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,277 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import io.swagger.client.model.*; + +import com.google.gson.reflect.TypeToken; + +import com.squareup.okhttp.Call; + +import java.lang.reflect.Type; + +import java.util.*; + +import java.util.Map; +import io.swagger.client.model.Order; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /* Build call for getInventory */ + private Call getInventoryCall() throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/store/inventory".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "api_key" }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + */ + public Map getInventory() throws ApiException { + Call call = getInventoryCall(); + Type returnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call getInventoryAsync(ApiCallback> callback) throws ApiException { + Call call = getInventoryCall(); + Type returnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for placeOrder */ + private Call placeOrderCall(Order body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/store/order".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order + */ + public Order placeOrder(Order body) throws ApiException { + Call call = placeOrderCall(body); + Type returnType = new TypeToken(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call placeOrderAsync(Order body, ApiCallback callback) throws ApiException { + Call call = placeOrderCall(body); + Type returnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for getOrderById */ + private Call getOrderByIdCall(String orderId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @return Order + */ + public Order getOrderById(String orderId) throws ApiException { + Call call = getOrderByIdCall(orderId); + Type returnType = new TypeToken(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Find purchase order by ID (asynchronously) + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * @param orderId ID of pet that needs to be fetched + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call getOrderByIdAsync(String orderId, ApiCallback callback) throws ApiException { + Call call = getOrderByIdCall(orderId); + Type returnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for deleteOrder */ + private Call deleteOrderCall(String orderId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + */ + public void deleteOrder(String orderId) throws ApiException { + Call call = deleteOrderCall(orderId); + apiClient.execute(call); + } + + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call deleteOrderAsync(String orderId, ApiCallback callback) throws ApiException { + Call call = deleteOrderCall(orderId); + apiClient.executeAsync(call, callback); + return call; + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..27429765069 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,500 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import io.swagger.client.model.*; + +import com.google.gson.reflect.TypeToken; + +import com.squareup.okhttp.Call; + +import java.lang.reflect.Type; + +import java.util.*; + +import io.swagger.client.model.User; +import java.util.*; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /* Build call for createUser */ + private Call createUserCall(User body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + public void createUser(User body) throws ApiException { + Call call = createUserCall(body); + apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call createUserAsync(User body, ApiCallback callback) throws ApiException { + Call call = createUserCall(body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for createUsersWithArrayInput */ + private Call createUsersWithArrayInputCall(List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public void createUsersWithArrayInput(List body) throws ApiException { + Call call = createUsersWithArrayInputCall(body); + apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call createUsersWithArrayInputAsync(List body, ApiCallback callback) throws ApiException { + Call call = createUsersWithArrayInputCall(body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for createUsersWithListInput */ + private Call createUsersWithListInputCall(List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public void createUsersWithListInput(List body) throws ApiException { + Call call = createUsersWithListInputCall(body); + apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call createUsersWithListInputAsync(List body, ApiCallback callback) throws ApiException { + Call call = createUsersWithListInputCall(body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for loginUser */ + private Call loginUserCall(String username, String password) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/login".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + if (username != null) + queryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + queryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return String + */ + public String loginUser(String username, String password) throws ApiException { + Call call = loginUserCall(username, password); + Type returnType = new TypeToken(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login + * @param password The password for login in clear text + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call loginUserAsync(String username, String password, ApiCallback callback) throws ApiException { + Call call = loginUserCall(username, password); + Type returnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for logoutUser */ + private Call logoutUserCall() throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/logout".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Logs out current logged in user session + * + */ + public void logoutUser() throws ApiException { + Call call = logoutUserCall(); + apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call logoutUserAsync(ApiCallback callback) throws ApiException { + Call call = logoutUserCall(); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for getUserByName */ + private Call getUserByNameCall(String username) throws ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ + public User getUserByName(String username) throws ApiException { + Call call = getUserByNameCall(username); + Type returnType = new TypeToken(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call getUserByNameAsync(String username, ApiCallback callback) throws ApiException { + Call call = getUserByNameCall(username); + Type returnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for updateUser */ + private Call updateUserCall(String username, User body) throws ApiException { + Object postBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "PUT", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + public void updateUser(String username, User body) throws ApiException { + Call call = updateUserCall(username, body); + apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call updateUserAsync(String username, User body, ApiCallback callback) throws ApiException { + Call call = updateUserCall(username, body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for deleteUser */ + private Call deleteUserCall(String username) throws ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + public void deleteUser(String username) throws ApiException { + Call call = deleteUserCall(username); + apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call deleteUserAsync(String username, ApiCallback callback) throws ApiException { + Call call = deleteUserCall(username); + apiClient.executeAsync(call, callback); + return call; + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..20ebbf17e74 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,59 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map 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); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..9197d04b1b7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,12 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public interface Authentication { + /** Apply authentication settings to header and query params. */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..d2b56433169 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,41 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import com.migcomponents.migbase64.Base64; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..184b9e82ca7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,14 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class OAuth implements Authentication { + @Override + public void applyToParams(List queryParams, Map headerParams) { + // TODO: support oauth + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 00000000000..0a7023ac7a5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,57 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Category { + + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 00000000000..df8e77b6fb3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,142 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import java.util.Date; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Order { + + @SerializedName("id") + private Long id = null; + + @SerializedName("petId") + private Long petId = null; + + @SerializedName("quantity") + private Integer quantity = null; + + @SerializedName("shipDate") + private Date shipDate = null; + + +public enum StatusEnum { + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + @SerializedName("complete") + private Boolean complete = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(StringUtil.toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(StringUtil.toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(StringUtil.toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(StringUtil.toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 00000000000..9ab5457e26a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,144 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import io.swagger.client.model.Category; +import java.util.*; +import io.swagger.client.model.Tag; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Pet { + + @SerializedName("id") + private Long id = null; + + @SerializedName("category") + private Category category = null; + + @SerializedName("name") + private String name = null; + + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + + @SerializedName("tags") + private List tags = new ArrayList(); + + +public enum StatusEnum { + @SerializedName("available") + AVAILABLE("available"), + + @SerializedName("pending") + PENDING("pending"), + + @SerializedName("sold") + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" category: ").append(StringUtil.toIndentedString(category)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(StringUtil.toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(StringUtil.toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 00000000000..9935b744f2d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,57 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Tag { + + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 00000000000..cba6abef8dd --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,148 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class User { + + @SerializedName("id") + private Long id = null; + + @SerializedName("username") + private String username = null; + + @SerializedName("firstName") + private String firstName = null; + + @SerializedName("lastName") + private String lastName = null; + + @SerializedName("email") + private String email = null; + + @SerializedName("password") + private String password = null; + + @SerializedName("phone") + private String phone = null; + + @SerializedName("userStatus") + private Integer userStatus = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" username: ").append(StringUtil.toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(StringUtil.toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(StringUtil.toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(StringUtil.toIndentedString(email)).append("\n"); + sb.append(" password: ").append(StringUtil.toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(StringUtil.toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(StringUtil.toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 00000000000..802c0cae3b9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,193 @@ +package io.swagger.client; + +import io.swagger.client.auth.*; + +import java.util.*; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Test + public void testSetUsername() { + try { + apiClient.setUsername("my-username"); + fail("there should be no HTTP basic authentications"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetPassword() { + try { + apiClient.setPassword("my-password"); + fail("there should be no HTTP basic authentications"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = (ApiKeyAuth) apiClient.getAuthentications().get("api_key"); + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1)); + List pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + + // single empty string + List pairs = apiClient.parameterToPairs("csv", "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPairs("csv", name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "\\|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 00000000000..b95eb74605e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 00000000000..4b03c7a9812 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class StringUtilTest { + @Test + public void testContainsIgnoreCase() { + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null)); + + assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null)); + } + + @Test + public void testJoin() { + String[] array = {"aa", "bb", "cc"}; + assertEquals("aa,bb,cc", StringUtil.join(array, ",")); + assertEquals("aa, bb, cc", StringUtil.join(array, ", ")); + assertEquals("aabbcc", StringUtil.join(array, "")); + assertEquals("aa bb cc", StringUtil.join(array, " ")); + assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n")); + + assertEquals("", StringUtil.join(new String[]{}, ",")); + assertEquals("abc", StringUtil.join(new String[]{"abc"}, ",")); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 00000000000..5bdb4fb78fb --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 00000000000..52c5497ba83 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 00000000000..0a8f8a1665d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,192 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.Configuration; + +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.*; +import static org.junit.Assert.*; + +public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + } + + @Test + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(System.currentTimeMillis()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java new file mode 100644 index 00000000000..a1fd7e345a8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -0,0 +1,72 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiException; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Map; + +import org.junit.*; +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(String.valueOf(order.getId())); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setId(new Long(System.currentTimeMillis())); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(new java.util.Date()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + return order; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java new file mode 100644 index 00000000000..26e46bfa602 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -0,0 +1,86 @@ +package io.swagger.petstore.test; + +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +}