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 736b533ebc6..6d67e971923 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 @@ -36,12 +36,12 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { reservedWords = new HashSet ( Arrays.asList( - "abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", + "abstract", "continue", "for", "new", "switch", "assert", + "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", "byte", "else", + "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", + "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", + "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", "native", "super", "while") ); @@ -58,7 +58,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { ); instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); - + cliOptions.add(new CliOption("invokerPackage", "root package for generated code")); cliOptions.add(new CliOption("groupId", "groupId in generated pom.xml")); cliOptions.add(new CliOption("artifactId", "artifactId in generated pom.xml")); @@ -69,7 +69,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public void processOpts() { super.processOpts(); - + if(additionalProperties.containsKey("invokerPackage")) { this.setInvokerPackage((String)additionalProperties.get("invokerPackage")); } @@ -77,7 +77,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { //not set, use default to be passed to template additionalProperties.put("invokerPackage", invokerPackage); } - + if(additionalProperties.containsKey("groupId")) { this.setGroupId((String)additionalProperties.get("groupId")); } @@ -85,7 +85,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { //not set, use to be passed to template additionalProperties.put("groupId", groupId); } - + if(additionalProperties.containsKey("artifactId")) { this.setArtifactId((String)additionalProperties.get("artifactId")); } @@ -93,7 +93,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { //not set, use to be passed to template additionalProperties.put("artifactId", artifactId); } - + if(additionalProperties.containsKey("artifactVersion")) { this.setArtifactVersion((String)additionalProperties.get("artifactVersion")); } @@ -101,21 +101,23 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { //not set, use to be passed to template additionalProperties.put("artifactVersion", artifactVersion); } - + if(additionalProperties.containsKey("sourceFolder")) { this.setSourceFolder((String)additionalProperties.get("sourceFolder")); } 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")); } - - + + @Override public String escapeReservedWord(String name) { diff --git a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache similarity index 62% rename from modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache rename to modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index c30ba4cdd12..ae79a726280 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -29,69 +29,116 @@ 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 boolean debugging = 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; - /** - * 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'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")); // 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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 DATE_TIME_FORMAT.parse(str); + return dateFormat.parse(str); } catch (java.text.ParseException e) { throw new RuntimeException(e); } } - public static Date parseDate(String str) { - try { - return DATE_FORMAT.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); } - public static String formatDateTime(Date datetime) { - return DATE_TIME_FORMAT.format(datetime); - } - - public static String formatDate(Date date) { - return DATE_FORMAT.format(date); - } - - public static String parameterToString(Object param) { + /** + * 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) { @@ -105,28 +152,27 @@ 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); - } + /** + * 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; } } - public static Object deserialize(String json, String containerType, Class cls) throws ApiException { + /** + * 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(); } @@ -147,11 +193,14 @@ public class ApiInvoker { } } catch (IOException e) { - throw new ApiException(500, e.getMessage()); + throw new ApiException(500, e.getMessage(), null, json); } } - public static String serialize(Object obj) throws ApiException { + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) throws ApiException { try { if (obj != null) return JsonUtil.getJsonMapper().writeValueAsString(obj); @@ -163,8 +212,20 @@ 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); + /** + * 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(); StringBuilder b = new StringBuilder(); @@ -180,7 +241,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 +297,7 @@ public class ApiInvoker { else { throw new ApiException(500, "unknown method type " + method); } + if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) { return null; } @@ -249,9 +311,11 @@ public class ApiInvoker { } 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(); @@ -259,16 +323,21 @@ public class ApiInvoker { } throw new ApiException( response.getClientResponseStatus().getStatusCode(), - message); + message, + response.getHeaders(), + respBody); } } + /** + * Encode the given form parameters as request body. + */ private String getXWWWFormUrlencodedParams(Map formParams) { 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 +356,16 @@ public class ApiInvoker { return encodedFormParams; } - - private Client getClient(String host) { - if(!hostMap.containsKey(host)) { + /** + * 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(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..9d7523d1fb3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache @@ -0,0 +1,21 @@ +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/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 78bac41d9d6..b33fd7f3733 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,10 @@ 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}}if ({{paramName}} != null) + headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); {{/headerParams}} String[] contentTypes = { {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} @@ -76,25 +81,30 @@ public class {{classname}} { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); {{#formParams}}{{#notFile}} - hasFields = true; - mp.field("{{baseName}}", ApiInvoker.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}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}} + {{#formParams}}{{#notFile}}if ({{paramName}} != null) + 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}}; diff --git a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache index a6bcba75b7c..9afe96c6ffb 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,32 @@ 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; + + /** + * Get the HTTP response headers. + */ + public Map> getResponseHeaders() { + return responseHeaders; } -} \ No newline at end of file + + /** + * Get the HTTP response body. + */ + public String getResponseBody() { + return responseBody; + } +} 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 62% 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..38f021aab22 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,69 +29,116 @@ 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 boolean debugging = 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; - /** - * 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'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")); // 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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 DATE_TIME_FORMAT.parse(str); + return dateFormat.parse(str); } catch (java.text.ParseException e) { throw new RuntimeException(e); } } - public static Date parseDate(String str) { - try { - return DATE_FORMAT.parse(str); - } catch (java.text.ParseException e) { - throw new RuntimeException(e); - } + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); } - public static String formatDateTime(Date datetime) { - return DATE_TIME_FORMAT.format(datetime); - } - - public static String formatDate(Date date) { - return DATE_FORMAT.format(date); - } - - public static String parameterToString(Object param) { + /** + * 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) { @@ -105,28 +152,27 @@ 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); - } + /** + * 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; } } - public static Object deserialize(String json, String containerType, Class cls) throws ApiException { + /** + * 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(); } @@ -147,11 +193,14 @@ public class ApiInvoker { } } catch (IOException e) { - throw new ApiException(500, e.getMessage()); + throw new ApiException(500, e.getMessage(), null, json); } } - public static String serialize(Object obj) throws ApiException { + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) throws ApiException { try { if (obj != null) return JsonUtil.getJsonMapper().writeValueAsString(obj); @@ -163,8 +212,20 @@ 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); + /** + * 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(); StringBuilder b = new StringBuilder(); @@ -180,7 +241,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 +297,7 @@ public class ApiInvoker { else { throw new ApiException(500, "unknown method type " + method); } + if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) { return null; } @@ -249,9 +311,11 @@ public class ApiInvoker { } 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(); @@ -259,16 +323,21 @@ public class ApiInvoker { } throw new ApiException( response.getClientResponseStatus().getStatusCode(), - message); + message, + response.getHeaders(), + respBody); } } + /** + * Encode the given form parameters as request body. + */ private String getXWWWFormUrlencodedParams(Map formParams) { 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 +356,16 @@ public class ApiInvoker { return encodedFormParams; } - - private Client getClient(String host) { - if(!hostMap.containsKey(host)) { + /** + * 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(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/ApiException.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java index 31bc8a0978a..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 @@ -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,32 @@ 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; + + /** + * Get the HTTP response headers. + */ + public Map> getResponseHeaders() { + return responseHeaders; } -} \ No newline at end of file + + /** + * Get the HTTP response body. + */ + public String getResponseBody() { + return 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 new file mode 100644 index 00000000000..f7c360d6122 --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,21 @@ +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/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java index 10326d8a2d6..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 @@ -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(); @@ -334,23 +338,29 @@ public class PetApi { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); - hasFields = true; - mp.field("name", ApiInvoker.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", ApiInvoker.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", ApiInvoker.parameterToString(name)); - formParams.put("status", ApiInvoker.parameterToString(status)); + if (name != null) + formParams.put("name", apiClient.parameterToString(name)); + if (status != null) + 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 +390,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 +398,8 @@ public class PetApi { Map formParams = new HashMap(); - headerParams.put("api_key", ApiInvoker.parameterToString(apiKey)); + if (apiKey != null) + headerParams.put("api_key", apiClient.parameterToString(apiKey)); String[] contentTypes = { @@ -408,7 +419,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 +450,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(); @@ -458,24 +469,29 @@ public class PetApi { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); - hasFields = true; - mp.field("additionalMetadata", ApiInvoker.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", ApiInvoker.parameterToString(additionalMetadata)); + if (additionalMetadata != null) + 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(); - } -} 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..9801be416fb --- /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.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 1bee31e0748..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 @@ -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().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(); @@ -100,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()); @@ -152,4 +181,4 @@ public class PetApiTest { return pet; } -} \ No newline at end of file +}