Merge pull request #791 from xhh/java-api-client

[Java] Make API client more pluggable
This commit is contained in:
Tony Tam 2015-06-05 00:36:05 -07:00
commit aecb4adf4a
14 changed files with 576 additions and 341 deletions

View File

@ -107,8 +107,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml"));
supportingFiles.add(new SupportingFile("apiInvoker.mustache", supportingFiles.add(new SupportingFile("ApiClient.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java")); (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", supportingFiles.add(new SupportingFile("JsonUtil.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java")); (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java"));
supportingFiles.add(new SupportingFile("apiException.mustache", supportingFiles.add(new SupportingFile("apiException.mustache",

View File

@ -29,69 +29,116 @@ import java.net.URLEncoder;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.text.ParseException; import java.text.ParseException;
public class ApiInvoker { public class ApiClient {
private static ApiInvoker INSTANCE = new ApiInvoker();
private Map<String, Client> hostMap = new HashMap<String, Client>(); private Map<String, Client> hostMap = new HashMap<String, Client>();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>(); private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private boolean isDebug = false; private boolean debugging = false;
private String basePath = "{{basePath}}";
/** private DateFormat dateFormat;
* 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");
/** public ApiClient() {
* ISO 8601 date format. // Use ISO 8601 format for date and datetime.
* @see https://en.wikipedia.org/wiki/ISO_8601 // See https://en.wikipedia.org/wiki/ISO_8601
*/ this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
static {
// Use UTC as the default time zone. // Use UTC as the default time zone.
DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
// Set default User-Agent. // Set default User-Agent.
setUserAgent("Java-Swagger"); setUserAgent("Java-Swagger");
} }
public static void setUserAgent(String userAgent) { public String getBasePath() {
INSTANCE.addDefaultHeader("User-Agent", userAgent); 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 { try {
return DATE_TIME_FORMAT.parse(str); return dateFormat.parse(str);
} catch (java.text.ParseException e) { } catch (java.text.ParseException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public static Date parseDate(String str) { /**
try { * Format the given Date object into string.
return DATE_FORMAT.parse(str); */
} catch (java.text.ParseException e) { public String formatDate(Date date) {
throw new RuntimeException(e); return dateFormat.format(date);
}
} }
public static String formatDateTime(Date datetime) { /**
return DATE_TIME_FORMAT.format(datetime); * Format the given parameter object into string.
} */
public String parameterToString(Object param) {
public static String formatDate(Date date) {
return DATE_FORMAT.format(date);
}
public static String parameterToString(Object param) {
if (param == null) { if (param == null) {
return ""; return "";
} else if (param instanceof Date) { } else if (param instanceof Date) {
return formatDateTime((Date) param); return formatDate((Date) param);
} else if (param instanceof Collection) { } else if (param instanceof Collection) {
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
for(Object o : (Collection)param) { for(Object o : (Collection)param) {
@ -105,28 +152,27 @@ public class ApiInvoker {
return String.valueOf(param); 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) { public String escapeString(String str) {
try{ try {
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
} } catch (UnsupportedEncodingException e) {
catch(UnsupportedEncodingException e) {
return str; 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) { if(null != containerType) {
containerType = containerType.toLowerCase(); containerType = containerType.toLowerCase();
} }
@ -147,11 +193,14 @@ public class ApiInvoker {
} }
} }
catch (IOException e) { 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 { try {
if (obj != null) if (obj != null)
return JsonUtil.getJsonMapper().writeValueAsString(obj); return JsonUtil.getJsonMapper().writeValueAsString(obj);
@ -163,8 +212,20 @@ public class ApiInvoker {
} }
} }
public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> 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<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType) throws ApiException {
Client client = getClient();
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
@ -180,7 +241,7 @@ public class ApiInvoker {
} }
String querystring = b.toString(); 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()) { for(String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key)); builder = builder.header(key, headerParams.get(key));
} }
@ -236,6 +297,7 @@ public class ApiInvoker {
else { else {
throw new ApiException(500, "unknown method type " + method); throw new ApiException(500, "unknown method type " + method);
} }
if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) { if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) {
return null; return null;
} }
@ -249,9 +311,11 @@ public class ApiInvoker {
} }
else { else {
String message = "error"; String message = "error";
String respBody = null;
if(response.hasEntity()) { if(response.hasEntity()) {
try{ try{
message = String.valueOf(response.getEntity(String.class)); respBody = String.valueOf(response.getEntity(String.class));
message = respBody;
} }
catch (RuntimeException e) { catch (RuntimeException e) {
// e.printStackTrace(); // e.printStackTrace();
@ -259,16 +323,21 @@ public class ApiInvoker {
} }
throw new ApiException( throw new ApiException(
response.getClientResponseStatus().getStatusCode(), response.getClientResponseStatus().getStatusCode(),
message); message,
response.getHeaders(),
respBody);
} }
} }
/**
* Encode the given form parameters as request body.
*/
private String getXWWWFormUrlencodedParams(Map<String, String> formParams) { private String getXWWWFormUrlencodedParams(Map<String, String> formParams) {
StringBuilder formParamBuilder = new StringBuilder(); StringBuilder formParamBuilder = new StringBuilder();
for (Entry<String, String> param : formParams.entrySet()) { for (Entry<String, String> param : formParams.entrySet()) {
String keyStr = ApiInvoker.parameterToString(param.getKey()); String keyStr = parameterToString(param.getKey());
String valueStr = ApiInvoker.parameterToString(param.getValue()); String valueStr = parameterToString(param.getValue());
try { try {
formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) formParamBuilder.append(URLEncoder.encode(keyStr, "utf8"))
@ -287,14 +356,16 @@ public class ApiInvoker {
return encodedFormParams; return encodedFormParams;
} }
/**
private Client getClient(String host) { * Get an existing client or create a new client to handle HTTP request.
if(!hostMap.containsKey(host)) { */
private Client getClient() {
if(!hostMap.containsKey(basePath)) {
Client client = Client.create(); Client client = Client.create();
if(isDebug) if (debugging)
client.addFilter(new LoggingFilter()); client.addFilter(new LoggingFilter());
hostMap.put(host, client); hostMap.put(basePath, client);
} }
return hostMap.get(host); return hostMap.get(basePath);
} }
} }

View File

@ -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;
}
}

View File

@ -1,7 +1,8 @@
package {{package}}; package {{package}};
import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.ApiInvoker; import {{invokerPackage}}.ApiClient;
import {{invokerPackage}}.Configuration;
import {{modelPackage}}.*; import {{modelPackage}}.*;
@ -21,19 +22,22 @@ import java.util.HashMap;
{{#operations}} {{#operations}}
public class {{classname}} { public class {{classname}} {
String basePath = "{{basePath}}"; private ApiClient apiClient;
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public ApiInvoker getInvoker() { public {{classname}}() {
return apiInvoker; this(Configuration.getDefaultApiClient());
} }
public void setBasePath(String basePath) { public {{classname}}(ApiClient apiClient) {
this.basePath = basePath; this.apiClient = apiClient;
} }
public String getBasePath() { public ApiClient getApiClient() {
return basePath; return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
} }
{{#operation}} {{#operation}}
@ -54,7 +58,7 @@ public class {{classname}} {
// create path and map variables // create path and map variables
String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}
.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; .replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params // query params
Map<String, String> queryParams = new HashMap<String, String>(); Map<String, String> queryParams = new HashMap<String, String>();
@ -62,9 +66,10 @@ public class {{classname}} {
Map<String, String> formParams = new HashMap<String, String>(); Map<String, String> formParams = new HashMap<String, String>();
{{#queryParams}}if ({{paramName}} != null) {{#queryParams}}if ({{paramName}} != null)
queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));
{{/queryParams}} {{/queryParams}}
{{#headerParams}}headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); {{#headerParams}}if ({{paramName}} != null)
headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));
{{/headerParams}} {{/headerParams}}
String[] contentTypes = { String[] contentTypes = {
{{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}}
@ -76,25 +81,30 @@ public class {{classname}} {
boolean hasFields = false; boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart(); FormDataMultiPart mp = new FormDataMultiPart();
{{#formParams}}{{#notFile}} {{#formParams}}{{#notFile}}
if ({{paramName}} != null) {
hasFields = true; 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}} {{/notFile}}{{#isFile}}
if ({{paramName}} != null) {
hasFields = true; hasFields = true;
mp.field("{{baseName}}", file.getName()); mp.field("{{baseName}}", {{paramName}}.getName());
mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE)); mp.bodyPart(new FileDataBodyPart("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE));
}
{{/isFile}}{{/formParams}} {{/isFile}}{{/formParams}}
if(hasFields) if(hasFields)
postBody = mp; postBody = mp;
} }
else { else {
{{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}} {{#formParams}}{{#notFile}}if ({{paramName}} != null)
formParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));{{/notFile}}
{{/formParams}} {{/formParams}}
} }
try { 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){ if(response != null){
return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; return {{#returnType}}({{{returnType}}}) apiClient.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
} }
else { else {
return {{#returnType}}null{{/returnType}}; return {{#returnType}}null{{/returnType}};

View File

@ -1,8 +1,13 @@
package {{invokerPackage}}; package {{invokerPackage}};
import java.util.Map;
import java.util.List;
public class ApiException extends Exception { public class ApiException extends Exception {
int code = 0; private int code = 0;
String message = null; private String message = null;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
public ApiException() {} public ApiException() {}
@ -11,19 +16,32 @@ public class ApiException extends Exception {
this.message = message; this.message = message;
} }
public int getCode() { public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
return code; this.code = code;
this.message = message;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
} }
public void setCode(int code) { public int getCode() {
this.code = code; return code;
} }
public String getMessage() { public String getMessage() {
return message; return message;
} }
public void setMessage(String message) { /**
this.message = message; * Get the HTTP response headers.
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get the HTTP response body.
*/
public String getResponseBody() {
return responseBody;
} }
} }

View File

@ -29,69 +29,116 @@ import java.net.URLEncoder;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.text.ParseException; import java.text.ParseException;
public class ApiInvoker { public class ApiClient {
private static ApiInvoker INSTANCE = new ApiInvoker();
private Map<String, Client> hostMap = new HashMap<String, Client>(); private Map<String, Client> hostMap = new HashMap<String, Client>();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>(); private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private boolean isDebug = false; private boolean debugging = false;
private String basePath = "http://petstore.swagger.io/v2";
/** private DateFormat dateFormat;
* 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");
/** public ApiClient() {
* ISO 8601 date format. // Use ISO 8601 format for date and datetime.
* @see https://en.wikipedia.org/wiki/ISO_8601 // See https://en.wikipedia.org/wiki/ISO_8601
*/ this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
static {
// Use UTC as the default time zone. // Use UTC as the default time zone.
DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
// Set default User-Agent. // Set default User-Agent.
setUserAgent("Java-Swagger"); setUserAgent("Java-Swagger");
} }
public static void setUserAgent(String userAgent) { public String getBasePath() {
INSTANCE.addDefaultHeader("User-Agent", userAgent); 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 { try {
return DATE_TIME_FORMAT.parse(str); return dateFormat.parse(str);
} catch (java.text.ParseException e) { } catch (java.text.ParseException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public static Date parseDate(String str) { /**
try { * Format the given Date object into string.
return DATE_FORMAT.parse(str); */
} catch (java.text.ParseException e) { public String formatDate(Date date) {
throw new RuntimeException(e); return dateFormat.format(date);
}
} }
public static String formatDateTime(Date datetime) { /**
return DATE_TIME_FORMAT.format(datetime); * Format the given parameter object into string.
} */
public String parameterToString(Object param) {
public static String formatDate(Date date) {
return DATE_FORMAT.format(date);
}
public static String parameterToString(Object param) {
if (param == null) { if (param == null) {
return ""; return "";
} else if (param instanceof Date) { } else if (param instanceof Date) {
return formatDateTime((Date) param); return formatDate((Date) param);
} else if (param instanceof Collection) { } else if (param instanceof Collection) {
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
for(Object o : (Collection)param) { for(Object o : (Collection)param) {
@ -105,28 +152,27 @@ public class ApiInvoker {
return String.valueOf(param); 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) { public String escapeString(String str) {
try{ try {
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
} } catch (UnsupportedEncodingException e) {
catch(UnsupportedEncodingException e) {
return str; 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) { if(null != containerType) {
containerType = containerType.toLowerCase(); containerType = containerType.toLowerCase();
} }
@ -147,11 +193,14 @@ public class ApiInvoker {
} }
} }
catch (IOException e) { 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 { try {
if (obj != null) if (obj != null)
return JsonUtil.getJsonMapper().writeValueAsString(obj); return JsonUtil.getJsonMapper().writeValueAsString(obj);
@ -163,8 +212,20 @@ public class ApiInvoker {
} }
} }
public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> 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<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType) throws ApiException {
Client client = getClient();
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
@ -180,7 +241,7 @@ public class ApiInvoker {
} }
String querystring = b.toString(); 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()) { for(String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key)); builder = builder.header(key, headerParams.get(key));
} }
@ -236,6 +297,7 @@ public class ApiInvoker {
else { else {
throw new ApiException(500, "unknown method type " + method); throw new ApiException(500, "unknown method type " + method);
} }
if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) { if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) {
return null; return null;
} }
@ -249,9 +311,11 @@ public class ApiInvoker {
} }
else { else {
String message = "error"; String message = "error";
String respBody = null;
if(response.hasEntity()) { if(response.hasEntity()) {
try{ try{
message = String.valueOf(response.getEntity(String.class)); respBody = String.valueOf(response.getEntity(String.class));
message = respBody;
} }
catch (RuntimeException e) { catch (RuntimeException e) {
// e.printStackTrace(); // e.printStackTrace();
@ -259,16 +323,21 @@ public class ApiInvoker {
} }
throw new ApiException( throw new ApiException(
response.getClientResponseStatus().getStatusCode(), response.getClientResponseStatus().getStatusCode(),
message); message,
response.getHeaders(),
respBody);
} }
} }
/**
* Encode the given form parameters as request body.
*/
private String getXWWWFormUrlencodedParams(Map<String, String> formParams) { private String getXWWWFormUrlencodedParams(Map<String, String> formParams) {
StringBuilder formParamBuilder = new StringBuilder(); StringBuilder formParamBuilder = new StringBuilder();
for (Entry<String, String> param : formParams.entrySet()) { for (Entry<String, String> param : formParams.entrySet()) {
String keyStr = ApiInvoker.parameterToString(param.getKey()); String keyStr = parameterToString(param.getKey());
String valueStr = ApiInvoker.parameterToString(param.getValue()); String valueStr = parameterToString(param.getValue());
try { try {
formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) formParamBuilder.append(URLEncoder.encode(keyStr, "utf8"))
@ -287,14 +356,16 @@ public class ApiInvoker {
return encodedFormParams; return encodedFormParams;
} }
/**
private Client getClient(String host) { * Get an existing client or create a new client to handle HTTP request.
if(!hostMap.containsKey(host)) { */
private Client getClient() {
if(!hostMap.containsKey(basePath)) {
Client client = Client.create(); Client client = Client.create();
if(isDebug) if (debugging)
client.addFilter(new LoggingFilter()); client.addFilter(new LoggingFilter());
hostMap.put(host, client); hostMap.put(basePath, client);
} }
return hostMap.get(host); return hostMap.get(basePath);
} }
} }

View File

@ -1,8 +1,13 @@
package io.swagger.client; package io.swagger.client;
import java.util.Map;
import java.util.List;
public class ApiException extends Exception { public class ApiException extends Exception {
int code = 0; private int code = 0;
String message = null; private String message = null;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
public ApiException() {} public ApiException() {}
@ -11,19 +16,32 @@ public class ApiException extends Exception {
this.message = message; this.message = message;
} }
public int getCode() { public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
return code; this.code = code;
this.message = message;
this.responseHeaders = responseHeaders;
this.responseBody = responseBody;
} }
public void setCode(int code) { public int getCode() {
this.code = code; return code;
} }
public String getMessage() { public String getMessage() {
return message; return message;
} }
public void setMessage(String message) { /**
this.message = message; * Get the HTTP response headers.
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get the HTTP response body.
*/
public String getResponseBody() {
return responseBody;
} }
} }

View File

@ -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;
}
}

View File

@ -1,7 +1,8 @@
package io.swagger.client.api; package io.swagger.client.api;
import io.swagger.client.ApiException; 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.*; import io.swagger.client.model.*;
@ -20,19 +21,22 @@ import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
public class PetApi { public class PetApi {
String basePath = "http://petstore.swagger.io/v2"; private ApiClient apiClient;
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public ApiInvoker getInvoker() { public PetApi() {
return apiInvoker; this(Configuration.getDefaultApiClient());
} }
public void setBasePath(String basePath) { public PetApi(ApiClient apiClient) {
this.basePath = basePath; this.apiClient = apiClient;
} }
public String getBasePath() { public ApiClient getApiClient() {
return basePath; return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
} }
@ -74,7 +78,7 @@ public class PetApi {
} }
try { 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){ if(response != null){
return ; return ;
} }
@ -124,7 +128,7 @@ public class PetApi {
} }
try { 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){ if(response != null){
return ; return ;
} }
@ -155,7 +159,7 @@ public class PetApi {
Map<String, String> formParams = new HashMap<String, String>(); Map<String, String> formParams = new HashMap<String, String>();
if (status != null) if (status != null)
queryParams.put("status", ApiInvoker.parameterToString(status)); queryParams.put("status", apiClient.parameterToString(status));
String[] contentTypes = { String[] contentTypes = {
@ -176,9 +180,9 @@ public class PetApi {
} }
try { 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){ if(response != null){
return (List<Pet>) ApiInvoker.deserialize(response, "array", Pet.class); return (List<Pet>) apiClient.deserialize(response, "array", Pet.class);
} }
else { else {
return null; return null;
@ -207,7 +211,7 @@ public class PetApi {
Map<String, String> formParams = new HashMap<String, String>(); Map<String, String> formParams = new HashMap<String, String>();
if (tags != null) if (tags != null)
queryParams.put("tags", ApiInvoker.parameterToString(tags)); queryParams.put("tags", apiClient.parameterToString(tags));
String[] contentTypes = { String[] contentTypes = {
@ -228,9 +232,9 @@ public class PetApi {
} }
try { 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){ if(response != null){
return (List<Pet>) ApiInvoker.deserialize(response, "array", Pet.class); return (List<Pet>) apiClient.deserialize(response, "array", Pet.class);
} }
else { else {
return null; return null;
@ -257,7 +261,7 @@ public class PetApi {
// create path and map variables // create path and map variables
String path = "/pet/{petId}".replaceAll("\\{format\\}","json") String path = "/pet/{petId}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
// query params // query params
Map<String, String> queryParams = new HashMap<String, String>(); Map<String, String> queryParams = new HashMap<String, String>();
@ -284,9 +288,9 @@ public class PetApi {
} }
try { 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){ if(response != null){
return (Pet) ApiInvoker.deserialize(response, "", Pet.class); return (Pet) apiClient.deserialize(response, "", Pet.class);
} }
else { else {
return null; return null;
@ -315,7 +319,7 @@ public class PetApi {
// create path and map variables // create path and map variables
String path = "/pet/{petId}".replaceAll("\\{format\\}","json") String path = "/pet/{petId}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
// query params // query params
Map<String, String> queryParams = new HashMap<String, String>(); Map<String, String> queryParams = new HashMap<String, String>();
@ -334,23 +338,29 @@ public class PetApi {
boolean hasFields = false; boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart(); FormDataMultiPart mp = new FormDataMultiPart();
if (name != null) {
hasFields = true; hasFields = true;
mp.field("name", ApiInvoker.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); mp.field("name", apiClient.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE);
}
if (status != null) {
hasFields = true; 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) if(hasFields)
postBody = mp; postBody = mp;
} }
else { else {
formParams.put("name", ApiInvoker.parameterToString(name)); if (name != null)
formParams.put("status", ApiInvoker.parameterToString(status)); formParams.put("name", apiClient.parameterToString(name));
if (status != null)
formParams.put("status", apiClient.parameterToString(status));
} }
try { 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){ if(response != null){
return ; return ;
} }
@ -380,7 +390,7 @@ public class PetApi {
// create path and map variables // create path and map variables
String path = "/pet/{petId}".replaceAll("\\{format\\}","json") String path = "/pet/{petId}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
// query params // query params
Map<String, String> queryParams = new HashMap<String, String>(); Map<String, String> queryParams = new HashMap<String, String>();
@ -388,7 +398,8 @@ public class PetApi {
Map<String, String> formParams = new HashMap<String, String>(); Map<String, String> formParams = new HashMap<String, String>();
headerParams.put("api_key", ApiInvoker.parameterToString(apiKey)); if (apiKey != null)
headerParams.put("api_key", apiClient.parameterToString(apiKey));
String[] contentTypes = { String[] contentTypes = {
@ -408,7 +419,7 @@ public class PetApi {
} }
try { 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){ if(response != null){
return ; return ;
} }
@ -439,7 +450,7 @@ public class PetApi {
// create path and map variables // create path and map variables
String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
// query params // query params
Map<String, String> queryParams = new HashMap<String, String>(); Map<String, String> queryParams = new HashMap<String, String>();
@ -458,24 +469,29 @@ public class PetApi {
boolean hasFields = false; boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart(); FormDataMultiPart mp = new FormDataMultiPart();
if (additionalMetadata != null) {
hasFields = true; hasFields = true;
mp.field("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata), MediaType.MULTIPART_FORM_DATA_TYPE); mp.field("additionalMetadata", apiClient.parameterToString(additionalMetadata), MediaType.MULTIPART_FORM_DATA_TYPE);
}
if (file != null) {
hasFields = true; hasFields = true;
mp.field("file", file.getName()); mp.field("file", file.getName());
mp.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)); mp.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE));
}
if(hasFields) if(hasFields)
postBody = mp; postBody = mp;
} }
else { else {
formParams.put("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata)); if (additionalMetadata != null)
formParams.put("additionalMetadata", apiClient.parameterToString(additionalMetadata));
} }
try { 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){ if(response != null){
return ; return ;
} }

View File

@ -1,7 +1,8 @@
package io.swagger.client.api; package io.swagger.client.api;
import io.swagger.client.ApiException; 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.*; import io.swagger.client.model.*;
@ -20,19 +21,22 @@ import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
public class StoreApi { public class StoreApi {
String basePath = "http://petstore.swagger.io/v2"; private ApiClient apiClient;
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public ApiInvoker getInvoker() { public StoreApi() {
return apiInvoker; this(Configuration.getDefaultApiClient());
} }
public void setBasePath(String basePath) { public StoreApi(ApiClient apiClient) {
this.basePath = basePath; this.apiClient = apiClient;
} }
public String getBasePath() { public ApiClient getApiClient() {
return basePath; return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
} }
@ -73,9 +77,9 @@ public class StoreApi {
} }
try { 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){ if(response != null){
return (Map<String, Integer>) ApiInvoker.deserialize(response, "map", Map.class); return (Map<String, Integer>) apiClient.deserialize(response, "map", Map.class);
} }
else { else {
return null; return null;
@ -123,9 +127,9 @@ public class StoreApi {
} }
try { 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){ if(response != null){
return (Order) ApiInvoker.deserialize(response, "", Order.class); return (Order) apiClient.deserialize(response, "", Order.class);
} }
else { else {
return null; return null;
@ -152,7 +156,7 @@ public class StoreApi {
// create path and map variables // create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString()));
// query params // query params
Map<String, String> queryParams = new HashMap<String, String>(); Map<String, String> queryParams = new HashMap<String, String>();
@ -179,9 +183,9 @@ public class StoreApi {
} }
try { 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){ if(response != null){
return (Order) ApiInvoker.deserialize(response, "", Order.class); return (Order) apiClient.deserialize(response, "", Order.class);
} }
else { else {
return null; return null;
@ -208,7 +212,7 @@ public class StoreApi {
// create path and map variables // create path and map variables
String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString()));
// query params // query params
Map<String, String> queryParams = new HashMap<String, String>(); Map<String, String> queryParams = new HashMap<String, String>();
@ -235,7 +239,7 @@ public class StoreApi {
} }
try { 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){ if(response != null){
return ; return ;
} }

View File

@ -1,7 +1,8 @@
package io.swagger.client.api; package io.swagger.client.api;
import io.swagger.client.ApiException; 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.*; import io.swagger.client.model.*;
@ -20,19 +21,22 @@ import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
public class UserApi { public class UserApi {
String basePath = "http://petstore.swagger.io/v2"; private ApiClient apiClient;
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public ApiInvoker getInvoker() { public UserApi() {
return apiInvoker; this(Configuration.getDefaultApiClient());
} }
public void setBasePath(String basePath) { public UserApi(ApiClient apiClient) {
this.basePath = basePath; this.apiClient = apiClient;
} }
public String getBasePath() { public ApiClient getApiClient() {
return basePath; return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
} }
@ -74,7 +78,7 @@ public class UserApi {
} }
try { 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){ if(response != null){
return ; return ;
} }
@ -124,7 +128,7 @@ public class UserApi {
} }
try { 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){ if(response != null){
return ; return ;
} }
@ -174,7 +178,7 @@ public class UserApi {
} }
try { 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){ if(response != null){
return ; return ;
} }
@ -206,9 +210,9 @@ public class UserApi {
Map<String, String> formParams = new HashMap<String, String>(); Map<String, String> formParams = new HashMap<String, String>();
if (username != null) if (username != null)
queryParams.put("username", ApiInvoker.parameterToString(username)); queryParams.put("username", apiClient.parameterToString(username));
if (password != null) if (password != null)
queryParams.put("password", ApiInvoker.parameterToString(password)); queryParams.put("password", apiClient.parameterToString(password));
String[] contentTypes = { String[] contentTypes = {
@ -229,9 +233,9 @@ public class UserApi {
} }
try { 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){ if(response != null){
return (String) ApiInvoker.deserialize(response, "", String.class); return (String) apiClient.deserialize(response, "", String.class);
} }
else { else {
return null; return null;
@ -278,7 +282,7 @@ public class UserApi {
} }
try { 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){ if(response != null){
return ; return ;
} }
@ -307,7 +311,7 @@ public class UserApi {
// create path and map variables // create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json") String path = "/user/{username}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
// query params // query params
Map<String, String> queryParams = new HashMap<String, String>(); Map<String, String> queryParams = new HashMap<String, String>();
@ -334,9 +338,9 @@ public class UserApi {
} }
try { 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){ if(response != null){
return (User) ApiInvoker.deserialize(response, "", User.class); return (User) apiClient.deserialize(response, "", User.class);
} }
else { else {
return null; return null;
@ -364,7 +368,7 @@ public class UserApi {
// create path and map variables // create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json") String path = "/user/{username}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
// query params // query params
Map<String, String> queryParams = new HashMap<String, String>(); Map<String, String> queryParams = new HashMap<String, String>();
@ -391,7 +395,7 @@ public class UserApi {
} }
try { 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){ if(response != null){
return ; return ;
} }
@ -420,7 +424,7 @@ public class UserApi {
// create path and map variables // create path and map variables
String path = "/user/{username}".replaceAll("\\{format\\}","json") String path = "/user/{username}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString()));
// query params // query params
Map<String, String> queryParams = new HashMap<String, String>(); Map<String, String> queryParams = new HashMap<String, String>();
@ -447,7 +451,7 @@ public class UserApi {
} }
try { 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){ if(response != null){
return ; return ;
} }

View File

@ -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();
}
}

View File

@ -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());
}
}

View File

@ -1,6 +1,8 @@
package io.swagger.petstore.test; package io.swagger.petstore.test;
import io.swagger.client.ApiException; import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.api.*; import io.swagger.client.api.*;
import io.swagger.client.model.*; import io.swagger.client.model.*;
@ -18,6 +20,33 @@ public class PetApiTest {
api = new PetApi(); 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 @Test
public void testCreateAndGetPet() throws Exception { public void testCreateAndGetPet() throws Exception {
Pet pet = createRandomPet(); Pet pet = createRandomPet();