From ac134c0afa9e50b27fea9df519df99bb55fc7784 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 26 May 2015 16:05:47 +0800 Subject: [PATCH 1/6] Make ApiClient more pluggable for Java - Rename ApiInvoker to ApiClient - Make ApiClient pluggable by allowing setting the ApiClient field of API classes - Introduce a Configuration class, containing the default ApiClient (which is also customizable) - Move basePath from API class to ApiClient - Change static methods in ApiClient to instance level --- .../codegen/languages/JavaClientCodegen.java | 10 +- ...apiInvoker.mustache => ApiClient.mustache} | 106 +++++++++--------- .../resources/Java/Configuration.mustache | 13 +++ .../src/main/resources/Java/api.mustache | 36 +++--- 4 files changed, 95 insertions(+), 70 deletions(-) rename modules/swagger-codegen/src/main/resources/Java/{apiInvoker.mustache => ApiClient.mustache} (77%) create mode 100644 modules/swagger-codegen/src/main/resources/Java/Configuration.mustache diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 7c0ac7422ff..0881b2035f8 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -51,11 +51,13 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("artifactVersion", artifactVersion); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java")); - supportingFiles.add(new SupportingFile("JsonUtil.mustache", + supportingFiles.add(new SupportingFile("ApiClient.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiClient.java")); + supportingFiles.add(new SupportingFile("Configuration.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Configuration.java")); + supportingFiles.add(new SupportingFile("JsonUtil.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java")); - supportingFiles.add(new SupportingFile("apiException.mustache", + supportingFiles.add(new SupportingFile("apiException.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java")); languageSpecificPrimitives = new HashSet( diff --git a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache similarity index 77% rename from modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache rename to modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index c30ba4cdd12..cd0805d775f 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -29,65 +29,82 @@ import java.net.URLEncoder; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; -public class ApiInvoker { - private static ApiInvoker INSTANCE = new ApiInvoker(); +public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); private boolean isDebug = false; + private String basePath = "{{basePath}}"; - /** - * ISO 8601 date time format. - * @see https://en.wikipedia.org/wiki/ISO_8601 - */ - public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + private DateFormat dateFormat; + private DateFormat datetimeFormat; - /** - * ISO 8601 date format. - * @see https://en.wikipedia.org/wiki/ISO_8601 - */ - public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + public ApiClient() { + // Use ISO 8601 format for date and datetime. + // See https://en.wikipedia.org/wiki/ISO_8601 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - static { // Use UTC as the default time zone. - DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); - DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // Set default User-Agent. setUserAgent("Java-Swagger"); } - public static void setUserAgent(String userAgent) { - INSTANCE.addDefaultHeader("User-Agent", userAgent); + public String getBasePath() { + return basePath; } - public static Date parseDateTime(String str) { + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + public ApiClient enableDebug() { + isDebug = true; + return this; + } + + public Date parseDateTime(String str) { try { - return DATE_TIME_FORMAT.parse(str); + return datetimeFormat.parse(str); } catch (java.text.ParseException e) { throw new RuntimeException(e); } } - public static Date parseDate(String str) { + public Date parseDate(String str) { try { - return DATE_FORMAT.parse(str); + return dateFormat.parse(str); } catch (java.text.ParseException e) { throw new RuntimeException(e); } } - public static String formatDateTime(Date datetime) { - return DATE_TIME_FORMAT.format(datetime); + public String formatDateTime(Date datetime) { + return datetimeFormat.format(datetime); } - public static String formatDate(Date date) { - return DATE_FORMAT.format(date); + public String formatDate(Date date) { + return dateFormat.format(date); } - public static String parameterToString(Object param) { + public String parameterToString(Object param) { if (param == null) { return ""; } else if (param instanceof Date) { @@ -105,17 +122,6 @@ public class ApiInvoker { return String.valueOf(param); } } - public void enableDebug() { - isDebug = true; - } - - public static ApiInvoker getInstance() { - return INSTANCE; - } - - public void addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - } public String escapeString(String str) { try{ @@ -126,7 +132,7 @@ public class ApiInvoker { } } - public static Object deserialize(String json, String containerType, Class cls) throws ApiException { + public Object deserialize(String json, String containerType, Class cls) throws ApiException { if(null != containerType) { containerType = containerType.toLowerCase(); } @@ -151,7 +157,7 @@ public class ApiInvoker { } } - public static String serialize(Object obj) throws ApiException { + public String serialize(Object obj) throws ApiException { try { if (obj != null) return JsonUtil.getJsonMapper().writeValueAsString(obj); @@ -163,8 +169,8 @@ public class ApiInvoker { } } - public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { - Client client = getClient(host); + public String invokeAPI(String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { + Client client = getClient(); StringBuilder b = new StringBuilder(); @@ -180,7 +186,7 @@ public class ApiInvoker { } String querystring = b.toString(); - Builder builder = client.resource(host + path + querystring).accept("application/json"); + Builder builder = client.resource(basePath + path + querystring).accept("application/json"); for(String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); } @@ -236,6 +242,7 @@ public class ApiInvoker { else { throw new ApiException(500, "unknown method type " + method); } + if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) { return null; } @@ -267,8 +274,8 @@ public class ApiInvoker { StringBuilder formParamBuilder = new StringBuilder(); for (Entry param : formParams.entrySet()) { - String keyStr = ApiInvoker.parameterToString(param.getKey()); - String valueStr = ApiInvoker.parameterToString(param.getValue()); + String keyStr = parameterToString(param.getKey()); + String valueStr = parameterToString(param.getValue()); try { formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) @@ -287,14 +294,13 @@ public class ApiInvoker { return encodedFormParams; } - - private Client getClient(String host) { - if(!hostMap.containsKey(host)) { + private Client getClient() { + if(!hostMap.containsKey(basePath)) { Client client = Client.create(); if(isDebug) client.addFilter(new LoggingFilter()); - hostMap.put(host, client); + hostMap.put(basePath, client); } - return hostMap.get(host); + return hostMap.get(basePath); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache new file mode 100644 index 00000000000..ce1e6dec1ce --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache @@ -0,0 +1,13 @@ +package {{invokerPackage}}; + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 78bac41d9d6..6e6a7a79940 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -1,7 +1,8 @@ package {{package}}; import {{invokerPackage}}.ApiException; -import {{invokerPackage}}.ApiInvoker; +import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.Configuration; import {{modelPackage}}.*; @@ -21,19 +22,22 @@ import java.util.HashMap; {{#operations}} public class {{classname}} { - String basePath = "{{basePath}}"; - ApiInvoker apiInvoker = ApiInvoker.getInstance(); + private ApiClient apiClient; - public ApiInvoker getInvoker() { - return apiInvoker; + public {{classname}}() { + this(Configuration.getDefaultApiClient()); } - public void setBasePath(String basePath) { - this.basePath = basePath; + public {{classname}}(ApiClient apiClient) { + this.apiClient = apiClient; } - public String getBasePath() { - return basePath; + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } {{#operation}} @@ -54,7 +58,7 @@ public class {{classname}} { // create path and map variables String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} - .replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; + .replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params Map queryParams = new HashMap(); @@ -62,9 +66,9 @@ public class {{classname}} { Map formParams = new HashMap(); {{#queryParams}}if ({{paramName}} != null) - queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); + queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); {{/queryParams}} - {{#headerParams}}headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); + {{#headerParams}}headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); {{/headerParams}} String[] contentTypes = { {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} @@ -77,7 +81,7 @@ public class {{classname}} { FormDataMultiPart mp = new FormDataMultiPart(); {{#formParams}}{{#notFile}} hasFields = true; - mp.field("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); + mp.field("{{baseName}}", apiClient.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); {{/notFile}}{{#isFile}} hasFields = true; mp.field("{{baseName}}", file.getName()); @@ -87,14 +91,14 @@ public class {{classname}} { postBody = mp; } else { - {{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}} + {{#formParams}}{{#notFile}}formParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));{{/notFile}} {{/formParams}} } try { - String response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; + return {{#returnType}}({{{returnType}}}) apiClient.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; } else { return {{#returnType}}null{{/returnType}}; From 62c8f9e1e2ebd4333cc21f6a881f6584bcdb3fc2 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 26 May 2015 16:13:19 +0800 Subject: [PATCH 2/6] Rebuild Java Petstore sample --- .../{ApiInvoker.java => ApiClient.java} | 106 +++++++++--------- .../java/io/swagger/client/Configuration.java | 13 +++ .../java/io/swagger/client/api/PetApi.java | 70 ++++++------ .../java/io/swagger/client/api/StoreApi.java | 40 ++++--- .../java/io/swagger/client/api/UserApi.java | 52 +++++---- .../io/swagger/client/model/ApiResponse.java | 64 ----------- 6 files changed, 156 insertions(+), 189 deletions(-) rename samples/client/petstore/java/src/main/java/io/swagger/client/{ApiInvoker.java => ApiClient.java} (77%) create mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java delete mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java similarity index 77% rename from samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index 69d13136274..b937edfedd3 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -29,65 +29,82 @@ import java.net.URLEncoder; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; -public class ApiInvoker { - private static ApiInvoker INSTANCE = new ApiInvoker(); +public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); private boolean isDebug = false; + private String basePath = "http://petstore.swagger.io/v2"; - /** - * ISO 8601 date time format. - * @see https://en.wikipedia.org/wiki/ISO_8601 - */ - public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + private DateFormat dateFormat; + private DateFormat datetimeFormat; - /** - * ISO 8601 date format. - * @see https://en.wikipedia.org/wiki/ISO_8601 - */ - public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); + public ApiClient() { + // Use ISO 8601 format for date and datetime. + // See https://en.wikipedia.org/wiki/ISO_8601 + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); - static { // Use UTC as the default time zone. - DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); - DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // Set default User-Agent. setUserAgent("Java-Swagger"); } - public static void setUserAgent(String userAgent) { - INSTANCE.addDefaultHeader("User-Agent", userAgent); + public String getBasePath() { + return basePath; } - public static Date parseDateTime(String str) { + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + public ApiClient enableDebug() { + isDebug = true; + return this; + } + + public Date parseDateTime(String str) { try { - return DATE_TIME_FORMAT.parse(str); + return datetimeFormat.parse(str); } catch (java.text.ParseException e) { throw new RuntimeException(e); } } - public static Date parseDate(String str) { + public Date parseDate(String str) { try { - return DATE_FORMAT.parse(str); + return dateFormat.parse(str); } catch (java.text.ParseException e) { throw new RuntimeException(e); } } - public static String formatDateTime(Date datetime) { - return DATE_TIME_FORMAT.format(datetime); + public String formatDateTime(Date datetime) { + return datetimeFormat.format(datetime); } - public static String formatDate(Date date) { - return DATE_FORMAT.format(date); + public String formatDate(Date date) { + return dateFormat.format(date); } - public static String parameterToString(Object param) { + public String parameterToString(Object param) { if (param == null) { return ""; } else if (param instanceof Date) { @@ -105,17 +122,6 @@ public class ApiInvoker { return String.valueOf(param); } } - public void enableDebug() { - isDebug = true; - } - - public static ApiInvoker getInstance() { - return INSTANCE; - } - - public void addDefaultHeader(String key, String value) { - defaultHeaderMap.put(key, value); - } public String escapeString(String str) { try{ @@ -126,7 +132,7 @@ public class ApiInvoker { } } - public static Object deserialize(String json, String containerType, Class cls) throws ApiException { + public Object deserialize(String json, String containerType, Class cls) throws ApiException { if(null != containerType) { containerType = containerType.toLowerCase(); } @@ -151,7 +157,7 @@ public class ApiInvoker { } } - public static String serialize(Object obj) throws ApiException { + public String serialize(Object obj) throws ApiException { try { if (obj != null) return JsonUtil.getJsonMapper().writeValueAsString(obj); @@ -163,8 +169,8 @@ public class ApiInvoker { } } - public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { - Client client = getClient(host); + public String invokeAPI(String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { + Client client = getClient(); StringBuilder b = new StringBuilder(); @@ -180,7 +186,7 @@ public class ApiInvoker { } String querystring = b.toString(); - Builder builder = client.resource(host + path + querystring).accept("application/json"); + Builder builder = client.resource(basePath + path + querystring).accept("application/json"); for(String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); } @@ -236,6 +242,7 @@ public class ApiInvoker { else { throw new ApiException(500, "unknown method type " + method); } + if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) { return null; } @@ -267,8 +274,8 @@ public class ApiInvoker { StringBuilder formParamBuilder = new StringBuilder(); for (Entry param : formParams.entrySet()) { - String keyStr = ApiInvoker.parameterToString(param.getKey()); - String valueStr = ApiInvoker.parameterToString(param.getValue()); + String keyStr = parameterToString(param.getKey()); + String valueStr = parameterToString(param.getValue()); try { formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) @@ -287,14 +294,13 @@ public class ApiInvoker { return encodedFormParams; } - - private Client getClient(String host) { - if(!hostMap.containsKey(host)) { + private Client getClient() { + if(!hostMap.containsKey(basePath)) { Client client = Client.create(); if(isDebug) client.addFilter(new LoggingFilter()); - hostMap.put(host, client); + hostMap.put(basePath, client); } - return hostMap.get(host); + return hostMap.get(basePath); } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..63622ead5dc --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,13 @@ +package io.swagger.client; + +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java index 10326d8a2d6..4d3d5c51d87 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java @@ -1,7 +1,8 @@ package io.swagger.client.api; import io.swagger.client.ApiException; -import io.swagger.client.ApiInvoker; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; import io.swagger.client.model.*; @@ -20,19 +21,22 @@ import java.util.Map; import java.util.HashMap; public class PetApi { - String basePath = "http://petstore.swagger.io/v2"; - ApiInvoker apiInvoker = ApiInvoker.getInstance(); + private ApiClient apiClient; - public ApiInvoker getInvoker() { - return apiInvoker; + public PetApi() { + this(Configuration.getDefaultApiClient()); } - public void setBasePath(String basePath) { - this.basePath = basePath; + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; } - public String getBasePath() { - return basePath; + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } @@ -74,7 +78,7 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } @@ -124,7 +128,7 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } @@ -155,7 +159,7 @@ public class PetApi { Map formParams = new HashMap(); if (status != null) - queryParams.put("status", ApiInvoker.parameterToString(status)); + queryParams.put("status", apiClient.parameterToString(status)); String[] contentTypes = { @@ -176,9 +180,9 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return (List) ApiInvoker.deserialize(response, "array", Pet.class); + return (List) apiClient.deserialize(response, "array", Pet.class); } else { return null; @@ -207,7 +211,7 @@ public class PetApi { Map formParams = new HashMap(); if (tags != null) - queryParams.put("tags", ApiInvoker.parameterToString(tags)); + queryParams.put("tags", apiClient.parameterToString(tags)); String[] contentTypes = { @@ -228,9 +232,9 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return (List) ApiInvoker.deserialize(response, "array", Pet.class); + return (List) apiClient.deserialize(response, "array", Pet.class); } else { return null; @@ -257,7 +261,7 @@ public class PetApi { // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params Map queryParams = new HashMap(); @@ -284,9 +288,9 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return (Pet) ApiInvoker.deserialize(response, "", Pet.class); + return (Pet) apiClient.deserialize(response, "", Pet.class); } else { return null; @@ -315,7 +319,7 @@ public class PetApi { // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params Map queryParams = new HashMap(); @@ -335,22 +339,22 @@ public class PetApi { FormDataMultiPart mp = new FormDataMultiPart(); hasFields = true; - mp.field("name", ApiInvoker.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); + mp.field("name", apiClient.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); hasFields = true; - mp.field("status", ApiInvoker.parameterToString(status), MediaType.MULTIPART_FORM_DATA_TYPE); + mp.field("status", apiClient.parameterToString(status), MediaType.MULTIPART_FORM_DATA_TYPE); if(hasFields) postBody = mp; } else { - formParams.put("name", ApiInvoker.parameterToString(name)); - formParams.put("status", ApiInvoker.parameterToString(status)); + formParams.put("name", apiClient.parameterToString(name)); + formParams.put("status", apiClient.parameterToString(status)); } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } @@ -380,7 +384,7 @@ public class PetApi { // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params Map queryParams = new HashMap(); @@ -388,7 +392,7 @@ public class PetApi { Map formParams = new HashMap(); - headerParams.put("api_key", ApiInvoker.parameterToString(apiKey)); + headerParams.put("api_key", apiClient.parameterToString(apiKey)); String[] contentTypes = { @@ -408,7 +412,7 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } @@ -439,7 +443,7 @@ public class PetApi { // create path and map variables String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params Map queryParams = new HashMap(); @@ -459,7 +463,7 @@ public class PetApi { FormDataMultiPart mp = new FormDataMultiPart(); hasFields = true; - mp.field("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata), MediaType.MULTIPART_FORM_DATA_TYPE); + mp.field("additionalMetadata", apiClient.parameterToString(additionalMetadata), MediaType.MULTIPART_FORM_DATA_TYPE); hasFields = true; mp.field("file", file.getName()); @@ -469,13 +473,13 @@ public class PetApi { postBody = mp; } else { - formParams.put("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata)); + formParams.put("additionalMetadata", apiClient.parameterToString(additionalMetadata)); } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java index 6da7b5abb2f..7b956f79a22 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,7 +1,8 @@ package io.swagger.client.api; import io.swagger.client.ApiException; -import io.swagger.client.ApiInvoker; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; import io.swagger.client.model.*; @@ -20,19 +21,22 @@ import java.util.Map; import java.util.HashMap; public class StoreApi { - String basePath = "http://petstore.swagger.io/v2"; - ApiInvoker apiInvoker = ApiInvoker.getInstance(); + private ApiClient apiClient; - public ApiInvoker getInvoker() { - return apiInvoker; + public StoreApi() { + this(Configuration.getDefaultApiClient()); } - public void setBasePath(String basePath) { - this.basePath = basePath; + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; } - public String getBasePath() { - return basePath; + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } @@ -73,9 +77,9 @@ public class StoreApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return (Map) ApiInvoker.deserialize(response, "map", Map.class); + return (Map) apiClient.deserialize(response, "map", Map.class); } else { return null; @@ -123,9 +127,9 @@ public class StoreApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return (Order) ApiInvoker.deserialize(response, "", Order.class); + return (Order) apiClient.deserialize(response, "", Order.class); } else { return null; @@ -152,7 +156,7 @@ public class StoreApi { // create path and map variables String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params Map queryParams = new HashMap(); @@ -179,9 +183,9 @@ public class StoreApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return (Order) ApiInvoker.deserialize(response, "", Order.class); + return (Order) apiClient.deserialize(response, "", Order.class); } else { return null; @@ -208,7 +212,7 @@ public class StoreApi { // create path and map variables String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params Map queryParams = new HashMap(); @@ -235,7 +239,7 @@ public class StoreApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java index d0974d95a52..0c6f331abe0 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java @@ -1,7 +1,8 @@ package io.swagger.client.api; import io.swagger.client.ApiException; -import io.swagger.client.ApiInvoker; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; import io.swagger.client.model.*; @@ -20,19 +21,22 @@ import java.util.Map; import java.util.HashMap; public class UserApi { - String basePath = "http://petstore.swagger.io/v2"; - ApiInvoker apiInvoker = ApiInvoker.getInstance(); + private ApiClient apiClient; - public ApiInvoker getInvoker() { - return apiInvoker; + public UserApi() { + this(Configuration.getDefaultApiClient()); } - public void setBasePath(String basePath) { - this.basePath = basePath; + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; } - public String getBasePath() { - return basePath; + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; } @@ -74,7 +78,7 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } @@ -124,7 +128,7 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } @@ -174,7 +178,7 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } @@ -206,9 +210,9 @@ public class UserApi { Map formParams = new HashMap(); if (username != null) - queryParams.put("username", ApiInvoker.parameterToString(username)); + queryParams.put("username", apiClient.parameterToString(username)); if (password != null) - queryParams.put("password", ApiInvoker.parameterToString(password)); + queryParams.put("password", apiClient.parameterToString(password)); String[] contentTypes = { @@ -229,9 +233,9 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return (String) ApiInvoker.deserialize(response, "", String.class); + return (String) apiClient.deserialize(response, "", String.class); } else { return null; @@ -278,7 +282,7 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } @@ -307,7 +311,7 @@ public class UserApi { // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params Map queryParams = new HashMap(); @@ -334,9 +338,9 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return (User) ApiInvoker.deserialize(response, "", User.class); + return (User) apiClient.deserialize(response, "", User.class); } else { return null; @@ -364,7 +368,7 @@ public class UserApi { // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params Map queryParams = new HashMap(); @@ -391,7 +395,7 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } @@ -420,7 +424,7 @@ public class UserApi { // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params Map queryParams = new HashMap(); @@ -447,7 +451,7 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); + String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ return ; } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java deleted file mode 100644 index cd9ff24975c..00000000000 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java +++ /dev/null @@ -1,64 +0,0 @@ -package io.swagger.client.model; - - -import com.wordnik.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; - - -@ApiModel(description = "") -public class ApiResponse { - - private Integer code = null; - private String type = null; - private String message = null; - - - /** - **/ - @ApiModelProperty(required = false, value = "") - @JsonProperty("code") - public Integer getCode() { - return code; - } - public void setCode(Integer code) { - this.code = code; - } - - - /** - **/ - @ApiModelProperty(required = false, value = "") - @JsonProperty("type") - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - - - /** - **/ - @ApiModelProperty(required = false, value = "") - @JsonProperty("message") - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ApiResponse {\n"); - - sb.append(" code: ").append(code).append("\n"); - sb.append(" type: ").append(type).append("\n"); - sb.append(" message: ").append(message).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} From a8c526efd5588ed6cac259f94b2421262882eb97 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 26 May 2015 16:41:04 +0800 Subject: [PATCH 3/6] Add unit tests for Configuration and ApiClient --- .../main/resources/Java/ApiClient.mustache | 4 +++ .../java/io/swagger/client/ApiClient.java | 4 +++ .../io/swagger/client/ConfigurationTest.java | 14 +++++++++ .../io/swagger/petstore/test/PetApiTest.java | 29 +++++++++++++++++++ 4 files changed, 51 insertions(+) create mode 100644 samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index cd0805d775f..239ce54a34a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -75,6 +75,10 @@ public class ApiClient { return this; } + public boolean isDebug() { + return isDebug; + } + public ApiClient enableDebug() { isDebug = true; return this; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index b937edfedd3..ec0a150ef4e 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -75,6 +75,10 @@ public class ApiClient { return this; } + public boolean isDebug() { + return isDebug; + } + public ApiClient enableDebug() { isDebug = true; return this; diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 00000000000..e16eaf4c086 --- /dev/null +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,14 @@ +package io.swagger.client; + +import static org.junit.Assert.*; +import org.junit.*; + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebug()); + } +} diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java index 1bee31e0748..8416e13b468 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -1,6 +1,8 @@ package io.swagger.petstore.test; import io.swagger.client.ApiException; +import io.swagger.client.ApiClient; +import io.swagger.client.Configuration; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -18,6 +20,33 @@ public class PetApiTest { api = new PetApi(); } + @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().isDebug()); + + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.enableDebug(); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebug()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebug()); + } + @Test public void testCreateAndGetPet() throws Exception { Pet pet = createRandomPet(); From 19540ed7f004a3c8fae71ed7d8313e30e787a655 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 2 Jun 2015 15:33:44 +0800 Subject: [PATCH 4/6] Store response headers and body in ApiException --- .../main/resources/Java/ApiClient.mustache | 10 +++-- .../main/resources/Java/apiException.mustache | 40 ++++++++++++++++--- .../java/io/swagger/client/ApiClient.java | 10 +++-- .../java/io/swagger/client/ApiException.java | 40 ++++++++++++++++--- 4 files changed, 82 insertions(+), 18 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 239ce54a34a..45987bded75 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -157,7 +157,7 @@ public class ApiClient { } } catch (IOException e) { - throw new ApiException(500, e.getMessage()); + throw new ApiException(500, e.getMessage(), null, json); } } @@ -260,9 +260,11 @@ public class ApiClient { } else { String message = "error"; + String respBody = null; if(response.hasEntity()) { try{ - message = String.valueOf(response.getEntity(String.class)); + respBody = String.valueOf(response.getEntity(String.class)); + message = respBody; } catch (RuntimeException e) { // e.printStackTrace(); @@ -270,7 +272,9 @@ public class ApiClient { } throw new ApiException( response.getClientResponseStatus().getStatusCode(), - message); + message, + response.getHeaders(), + respBody); } } diff --git a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache index a6bcba75b7c..aac7caaf019 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache @@ -1,8 +1,13 @@ package {{invokerPackage}}; +import java.util.Map; +import java.util.List; + public class ApiException extends Exception { - int code = 0; - String message = null; + private int code = 0; + private String message = null; + private Map> responseHeaders = null; + private String responseBody = null; public ApiException() {} @@ -11,19 +16,42 @@ public class ApiException extends Exception { this.message = message; } + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this.code = code; + this.message = message; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + public int getCode() { return code; } - + public void setCode(int code) { this.code = code; } - + public String getMessage() { return message; } - + public void setMessage(String message) { this.message = message; } -} \ No newline at end of file + + public Map> getResponseHeaders() { + return responseHeaders; + } + + public void setResponseHeaders(Map> responseHeaders) { + this.responseHeaders = responseHeaders; + } + + public String getResponseBody() { + return responseBody; + } + + public void setResponseBody(String responseBody) { + this.responseBody = responseBody; + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index ec0a150ef4e..6a4dfffefab 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -157,7 +157,7 @@ public class ApiClient { } } catch (IOException e) { - throw new ApiException(500, e.getMessage()); + throw new ApiException(500, e.getMessage(), null, json); } } @@ -260,9 +260,11 @@ public class ApiClient { } else { String message = "error"; + String respBody = null; if(response.hasEntity()) { try{ - message = String.valueOf(response.getEntity(String.class)); + respBody = String.valueOf(response.getEntity(String.class)); + message = respBody; } catch (RuntimeException e) { // e.printStackTrace(); @@ -270,7 +272,9 @@ public class ApiClient { } throw new ApiException( response.getClientResponseStatus().getStatusCode(), - message); + message, + response.getHeaders(), + respBody); } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java index 31bc8a0978a..515c21d85d4 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java @@ -1,8 +1,13 @@ package io.swagger.client; +import java.util.Map; +import java.util.List; + public class ApiException extends Exception { - int code = 0; - String message = null; + private int code = 0; + private String message = null; + private Map> responseHeaders = null; + private String responseBody = null; public ApiException() {} @@ -11,19 +16,42 @@ public class ApiException extends Exception { this.message = message; } + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this.code = code; + this.message = message; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + public int getCode() { return code; } - + public void setCode(int code) { this.code = code; } - + public String getMessage() { return message; } - + public void setMessage(String message) { this.message = message; } -} \ No newline at end of file + + public Map> getResponseHeaders() { + return responseHeaders; + } + + public void setResponseHeaders(Map> responseHeaders) { + this.responseHeaders = responseHeaders; + } + + public String getResponseBody() { + return responseBody; + } + + public void setResponseBody(String responseBody) { + this.responseBody = responseBody; + } +} From eb4973237ba6d0368c4346c9fe904ec7c1453114 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 3 Jun 2015 10:09:36 +0800 Subject: [PATCH 5/6] Add comments to code --- .../main/resources/Java/ApiClient.mustache | 105 ++++++++++++++---- .../resources/Java/Configuration.mustache | 8 ++ .../main/resources/Java/apiException.mustache | 22 +--- .../java/io/swagger/client/ApiClient.java | 105 ++++++++++++++---- .../java/io/swagger/client/ApiException.java | 22 +--- .../java/io/swagger/client/Configuration.java | 8 ++ .../io/swagger/client/ConfigurationTest.java | 2 +- .../io/swagger/petstore/test/PetApiTest.java | 12 +- 8 files changed, 197 insertions(+), 87 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 45987bded75..ae79a726280 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -36,21 +36,18 @@ import java.text.ParseException; public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); - private boolean isDebug = false; + private boolean debugging = false; private String basePath = "{{basePath}}"; private DateFormat dateFormat; - private DateFormat datetimeFormat; public ApiClient() { // Use ISO 8601 format for date and datetime. // See https://en.wikipedia.org/wiki/ISO_8601 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // Set default User-Agent. setUserAgent("Java-Swagger"); @@ -65,33 +62,60 @@ public class ApiClient { return this; } + /** + * 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; } - public boolean isDebug() { - return isDebug; + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; } - public ApiClient enableDebug() { - isDebug = true; + /** + * 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; } - public Date parseDateTime(String str) { - try { - return datetimeFormat.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } + /** + * Get the date format used to parse/format date parameters. + */ + public DateFormat getDateFormat() { + return dateFormat; } + /** + * Set the date format used to parse/format date parameters. + */ + public ApiClient getDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + return this; + } + + /** + * Parse the given string into Date object. + */ public Date parseDate(String str) { try { return dateFormat.parse(str); @@ -100,19 +124,21 @@ public class ApiClient { } } - public String formatDateTime(Date datetime) { - return datetimeFormat.format(datetime); - } - + /** + * Format the given Date object into string. + */ public String formatDate(Date date) { return dateFormat.format(date); } + /** + * 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); + return formatDate((Date) param); } else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); for(Object o : (Collection)param) { @@ -127,15 +153,25 @@ public class ApiClient { } } + /** + * Escape the given string to be used as URL query value. + */ public String escapeString(String str) { - try{ + try { return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } - catch(UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { return str; } } + /** + * Deserialize the given JSON string to Java object. + * + * @param json The JSON string + * @param containerType The container type, one of "list", "array" or "" + * @param cls The type of the Java object + * @return The deserialized Java object + */ public Object deserialize(String json, String containerType, Class cls) throws ApiException { if(null != containerType) { containerType = containerType.toLowerCase(); @@ -161,6 +197,9 @@ public class ApiClient { } } + /** + * Serialize the given Java object into JSON string. + */ public String serialize(Object obj) throws ApiException { try { if (obj != null) @@ -173,6 +212,18 @@ public class ApiClient { } } + /** + * Invoke API by sending HTTP request with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param contentType The request Content-Type + * @return The response body in type of string + */ public String invokeAPI(String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { Client client = getClient(); @@ -278,6 +329,9 @@ public class ApiClient { } } + /** + * Encode the given form parameters as request body. + */ private String getXWWWFormUrlencodedParams(Map formParams) { StringBuilder formParamBuilder = new StringBuilder(); @@ -302,10 +356,13 @@ public class ApiClient { return encodedFormParams; } + /** + * Get an existing client or create a new client to handle HTTP request. + */ private Client getClient() { if(!hostMap.containsKey(basePath)) { Client client = Client.create(); - if(isDebug) + if (debugging) client.addFilter(new LoggingFilter()); hostMap.put(basePath, client); } diff --git a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache index ce1e6dec1ce..9d7523d1fb3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache @@ -3,10 +3,18 @@ package {{invokerPackage}}; 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/modules/swagger-codegen/src/main/resources/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache index aac7caaf019..9afe96c6ffb 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache @@ -27,31 +27,21 @@ public class ApiException extends Exception { return code; } - public void setCode(int code) { - this.code = code; - } - public String getMessage() { return message; } - public void setMessage(String message) { - this.message = message; - } - + /** + * Get the HTTP response headers. + */ public Map> getResponseHeaders() { return responseHeaders; } - public void setResponseHeaders(Map> responseHeaders) { - this.responseHeaders = responseHeaders; - } - + /** + * Get the HTTP response body. + */ public String getResponseBody() { return responseBody; } - - public void setResponseBody(String responseBody) { - this.responseBody = responseBody; - } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index 6a4dfffefab..38f021aab22 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -36,21 +36,18 @@ import java.text.ParseException; public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); - private boolean isDebug = false; + private boolean debugging = false; private String basePath = "http://petstore.swagger.io/v2"; private DateFormat dateFormat; - private DateFormat datetimeFormat; public ApiClient() { // Use ISO 8601 format for date and datetime. // See https://en.wikipedia.org/wiki/ISO_8601 - this.dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - this.datetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); // Use UTC as the default time zone. this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - this.datetimeFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // Set default User-Agent. setUserAgent("Java-Swagger"); @@ -65,33 +62,60 @@ public class ApiClient { return this; } + /** + * 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; } - public boolean isDebug() { - return isDebug; + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; } - public ApiClient enableDebug() { - isDebug = true; + /** + * 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; } - public Date parseDateTime(String str) { - try { - return datetimeFormat.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } + /** + * Get the date format used to parse/format date parameters. + */ + public DateFormat getDateFormat() { + return dateFormat; } + /** + * Set the date format used to parse/format date parameters. + */ + public ApiClient getDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + return this; + } + + /** + * Parse the given string into Date object. + */ public Date parseDate(String str) { try { return dateFormat.parse(str); @@ -100,19 +124,21 @@ public class ApiClient { } } - public String formatDateTime(Date datetime) { - return datetimeFormat.format(datetime); - } - + /** + * Format the given Date object into string. + */ public String formatDate(Date date) { return dateFormat.format(date); } + /** + * 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); + return formatDate((Date) param); } else if (param instanceof Collection) { StringBuilder b = new StringBuilder(); for(Object o : (Collection)param) { @@ -127,15 +153,25 @@ public class ApiClient { } } + /** + * Escape the given string to be used as URL query value. + */ public String escapeString(String str) { - try{ + try { return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); - } - catch(UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { return str; } } + /** + * Deserialize the given JSON string to Java object. + * + * @param json The JSON string + * @param containerType The container type, one of "list", "array" or "" + * @param cls The type of the Java object + * @return The deserialized Java object + */ public Object deserialize(String json, String containerType, Class cls) throws ApiException { if(null != containerType) { containerType = containerType.toLowerCase(); @@ -161,6 +197,9 @@ public class ApiClient { } } + /** + * Serialize the given Java object into JSON string. + */ public String serialize(Object obj) throws ApiException { try { if (obj != null) @@ -173,6 +212,18 @@ public class ApiClient { } } + /** + * Invoke API by sending HTTP request with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param contentType The request Content-Type + * @return The response body in type of string + */ public String invokeAPI(String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { Client client = getClient(); @@ -278,6 +329,9 @@ public class ApiClient { } } + /** + * Encode the given form parameters as request body. + */ private String getXWWWFormUrlencodedParams(Map formParams) { StringBuilder formParamBuilder = new StringBuilder(); @@ -302,10 +356,13 @@ public class ApiClient { return encodedFormParams; } + /** + * Get an existing client or create a new client to handle HTTP request. + */ private Client getClient() { if(!hostMap.containsKey(basePath)) { Client client = Client.create(); - if(isDebug) + if (debugging) client.addFilter(new LoggingFilter()); hostMap.put(basePath, client); } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java index 515c21d85d4..a39785eb47e 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java @@ -27,31 +27,21 @@ public class ApiException extends Exception { return code; } - public void setCode(int code) { - this.code = code; - } - public String getMessage() { return message; } - public void setMessage(String message) { - this.message = message; - } - + /** + * Get the HTTP response headers. + */ public Map> getResponseHeaders() { return responseHeaders; } - public void setResponseHeaders(Map> responseHeaders) { - this.responseHeaders = responseHeaders; - } - + /** + * Get the HTTP response body. + */ public String getResponseBody() { return responseBody; } - - public void setResponseBody(String responseBody) { - this.responseBody = responseBody; - } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java index 63622ead5dc..f7c360d6122 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java @@ -3,10 +3,18 @@ package io.swagger.client; 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/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java index e16eaf4c086..9801be416fb 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java @@ -9,6 +9,6 @@ public class ConfigurationTest { ApiClient apiClient = Configuration.getDefaultApiClient(); assertNotNull(apiClient); assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath()); - assertFalse(apiClient.isDebug()); + assertFalse(apiClient.isDebugging()); } } diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java index 8416e13b468..4ea5474eb59 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -26,25 +26,25 @@ public class PetApiTest { assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); assertNotNull(api.getApiClient()); assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebug()); + assertFalse(api.getApiClient().isDebugging()); ApiClient oldClient = api.getApiClient(); ApiClient newClient = new ApiClient(); newClient.setBasePath("http://example.com"); - newClient.enableDebug(); + 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().isDebug()); + 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().isDebug()); + assertFalse(api.getApiClient().isDebugging()); } @Test @@ -129,7 +129,7 @@ public class PetApiTest { api.addPet(pet); Pet fetched = api.getPetById(pet.getId()); - + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); Pet updated = api.getPetById(fetched.getId()); @@ -181,4 +181,4 @@ public class PetApiTest { return pet; } -} \ No newline at end of file +} From cf4b4de970c16cdb25b5516f8ce374a3a40eaf54 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 3 Jun 2015 20:26:14 +0800 Subject: [PATCH 6/6] Skip null header/form parameters and fix the bug of getting file name for file parameter --- .../src/main/resources/Java/api.mustache | 20 ++++++---- .../java/io/swagger/client/api/PetApi.java | 38 ++++++++++++------- 2 files changed, 38 insertions(+), 20 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 6e6a7a79940..b33fd7f3733 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -68,7 +68,8 @@ public class {{classname}} { {{#queryParams}}if ({{paramName}} != null) queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); {{/queryParams}} - {{#headerParams}}headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); + {{#headerParams}}if ({{paramName}} != null) + headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); {{/headerParams}} String[] contentTypes = { {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} @@ -80,18 +81,23 @@ public class {{classname}} { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); {{#formParams}}{{#notFile}} - hasFields = true; - mp.field("{{baseName}}", apiClient.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); + if ({{paramName}} != null) { + hasFields = true; + mp.field("{{baseName}}", apiClient.parameterToString({{paramName}}), MediaType.MULTIPART_FORM_DATA_TYPE); + } {{/notFile}}{{#isFile}} - hasFields = true; - mp.field("{{baseName}}", file.getName()); - mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)); + if ({{paramName}} != null) { + hasFields = true; + mp.field("{{baseName}}", {{paramName}}.getName()); + mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)); + } {{/isFile}}{{/formParams}} if(hasFields) postBody = mp; } else { - {{#formParams}}{{#notFile}}formParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));{{/notFile}} + {{#formParams}}{{#notFile}}if ({{paramName}} != null) + formParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));{{/notFile}} {{/formParams}} } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java index 4d3d5c51d87..1c3cc4cb483 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java @@ -338,18 +338,24 @@ public class PetApi { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); - hasFields = true; - mp.field("name", apiClient.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); + if (name != null) { + hasFields = true; + mp.field("name", apiClient.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); + } - hasFields = true; - mp.field("status", apiClient.parameterToString(status), MediaType.MULTIPART_FORM_DATA_TYPE); + if (status != null) { + hasFields = true; + mp.field("status", apiClient.parameterToString(status), MediaType.MULTIPART_FORM_DATA_TYPE); + } if(hasFields) postBody = mp; } else { - formParams.put("name", apiClient.parameterToString(name)); - formParams.put("status", apiClient.parameterToString(status)); + if (name != null) + formParams.put("name", apiClient.parameterToString(name)); + if (status != null) + formParams.put("status", apiClient.parameterToString(status)); } @@ -392,7 +398,8 @@ public class PetApi { Map formParams = new HashMap(); - headerParams.put("api_key", apiClient.parameterToString(apiKey)); + if (apiKey != null) + headerParams.put("api_key", apiClient.parameterToString(apiKey)); String[] contentTypes = { @@ -462,18 +469,23 @@ public class PetApi { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); - hasFields = true; - mp.field("additionalMetadata", apiClient.parameterToString(additionalMetadata), MediaType.MULTIPART_FORM_DATA_TYPE); + if (additionalMetadata != null) { + hasFields = true; + mp.field("additionalMetadata", apiClient.parameterToString(additionalMetadata), MediaType.MULTIPART_FORM_DATA_TYPE); + } - hasFields = true; - mp.field("file", file.getName()); - mp.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)); + if (file != null) { + hasFields = true; + mp.field("file", file.getName()); + mp.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)); + } if(hasFields) postBody = mp; } else { - formParams.put("additionalMetadata", apiClient.parameterToString(additionalMetadata)); + if (additionalMetadata != null) + formParams.put("additionalMetadata", apiClient.parameterToString(additionalMetadata)); }