rollback java template

This commit is contained in:
wing328 2015-06-09 13:08:32 +08:00
parent 900f39686d
commit 180d48e89d
12 changed files with 857 additions and 896 deletions

View File

@ -40,482 +40,468 @@ import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.OAuth; import {{invokerPackage}}.auth.OAuth;
public class ApiClient { public class ApiClient {
private Map private Map<String, Client> hostMap = new HashMap<String, Client>();
<String, Client> hostMap = new HashMap private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
<String, Client>(); private boolean debugging = false;
private Map private String basePath = "{{basePath}}";
<String, String> defaultHeaderMap = new HashMap
<String, String>();
private boolean debugging = false;
private String basePath = "{{basePath}}";
private Map private Map<String, Authentication> authentications;
<String, Authentication> authentications;
private DateFormat dateFormat; private DateFormat dateFormat;
public ApiClient() { public ApiClient() {
// Use ISO 8601 format for date and datetime. // 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"); this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
// Use UTC as the default time zone. // Use UTC as the default time zone.
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// Set default User-Agent. // Set default User-Agent.
setUserAgent("Java-Swagger"); setUserAgent("Java-Swagger");
// Setup authentications (key: authentication name, value: authentication). // Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}
<String, Authentication>();{{#authMethods}}{{#isBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
// Prevent the authentications from being modified. // Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications); authentications = Collections.unmodifiableMap(authentications);
} }
public String getBasePath() { public String getBasePath() {
return basePath; return basePath;
} }
public ApiClient setBasePath(String basePath) { public ApiClient setBasePath(String basePath) {
this.basePath = basePath; this.basePath = basePath;
return this; return this;
} }
/** /**
* Get authentications (key: authentication name, value: authentication). * Get authentications (key: authentication name, value: authentication).
*/ */
public Map public Map<String, Authentication> getAuthentications() {
<String, Authentication> getAuthentications() { return authentications;
return authentications; }
}
/** /**
* Get authentication for the given name. * Get authentication for the given name.
* *
* @param authName The authentication name * @param authName The authentication name
* @return The authentication, null if not found * @return The authentication, null if not found
*/ */
public Authentication getAuthentication(String authName) { public Authentication getAuthentication(String authName) {
return authentications.get(authName); return authentications.get(authName);
} }
/** /**
* Helper method to set username for the first HTTP basic authentication. * Helper method to set username for the first HTTP basic authentication.
*/ */
public void setUsername(String username) { public void setUsername(String username) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) { if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username); ((HttpBasicAuth) auth).setUsername(username);
return; return;
} }
} }
throw new RuntimeException("No HTTP basic authentication configured!"); throw new RuntimeException("No HTTP basic authentication configured!");
} }
/** /**
* Helper method to set password for the first HTTP basic authentication. * Helper method to set password for the first HTTP basic authentication.
*/ */
public void setPassword(String password) { public void setPassword(String password) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) { if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password); ((HttpBasicAuth) auth).setPassword(password);
return; return;
} }
} }
throw new RuntimeException("No HTTP basic authentication configured!"); throw new RuntimeException("No HTTP basic authentication configured!");
} }
/** /**
* Helper method to set API key value for the first API key authentication. * Helper method to set API key value for the first API key authentication.
*/ */
public void setApiKey(String apiKey) { public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) { if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey); ((ApiKeyAuth) auth).setApiKey(apiKey);
return; return;
} }
} }
throw new RuntimeException("No API key authentication configured!"); throw new RuntimeException("No API key authentication configured!");
} }
/** /**
* Helper method to set API key prefix for the first API key authentication. * Helper method to set API key prefix for the first API key authentication.
*/ */
public void setApiKeyPrefix(String apiKeyPrefix) { public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) { for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) { if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return; return;
} }
} }
throw new RuntimeException("No API key authentication configured!"); throw new RuntimeException("No API key authentication configured!");
} }
/** /**
* Set the User-Agent header's value (by adding to the default header map). * Set the User-Agent header's value (by adding to the default header map).
*/ */
public ApiClient setUserAgent(String userAgent) { public ApiClient setUserAgent(String userAgent) {
addDefaultHeader("User-Agent", userAgent); addDefaultHeader("User-Agent", userAgent);
return this; return this;
} }
/** /**
* Add a default header. * Add a default header.
* *
* @param key The header's key * @param key The header's key
* @param value The header's value * @param value The header's value
*/ */
public ApiClient addDefaultHeader(String key, String value) { public ApiClient addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value); defaultHeaderMap.put(key, value);
return this; return this;
} }
/** /**
* Check that whether debugging is enabled for this API client. * Check that whether debugging is enabled for this API client.
*/ */
public boolean isDebugging() { public boolean isDebugging() {
return debugging; return debugging;
} }
/** /**
* Enable/disable debugging for this API client. * Enable/disable debugging for this API client.
* *
* @param debugging To enable (true) or disable (false) debugging * @param debugging To enable (true) or disable (false) debugging
*/ */
public ApiClient setDebugging(boolean debugging) { public ApiClient setDebugging(boolean debugging) {
this.debugging = debugging; this.debugging = debugging;
return this; return this;
} }
/** /**
* Get the date format used to parse/format date parameters. * Get the date format used to parse/format date parameters.
*/ */
public DateFormat getDateFormat() { public DateFormat getDateFormat() {
return dateFormat; return dateFormat;
} }
/** /**
* Set the date format used to parse/format date parameters. * Set the date format used to parse/format date parameters.
*/ */
public ApiClient getDateFormat(DateFormat dateFormat) { public ApiClient getDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat; this.dateFormat = dateFormat;
return this; return this;
} }
/** /**
* Parse the given string into Date object. * Parse the given string into Date object.
*/ */
public Date parseDate(String str) { public Date parseDate(String str) {
try { try {
return dateFormat.parse(str); return dateFormat.parse(str);
} catch (java.text.ParseException e) { } catch (java.text.ParseException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
/** /**
* Format the given Date object into string. * Format the given Date object into string.
*/ */
public String formatDate(Date date) { public String formatDate(Date date) {
return dateFormat.format(date); return dateFormat.format(date);
} }
/** /**
* Format the given parameter object into string. * Format the given parameter object into string.
*/ */
public String parameterToString(Object param) { public String parameterToString(Object param) {
if (param == null) { if (param == null) {
return ""; return "";
} else if (param instanceof Date) { } else if (param instanceof Date) {
return formatDate((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) {
if(b.length() > 0) { if(b.length() > 0) {
b.append(","); b.append(",");
} }
b.append(String.valueOf(o)); b.append(String.valueOf(o));
} }
return b.toString(); return b.toString();
} else { } else {
return String.valueOf(param); return String.valueOf(param);
} }
} }
/** /**
* Select the Accept header's value from the given accepts array: * Select the Accept header's value from the given accepts array:
* if JSON exists in the given array, use it; * if JSON exists in the given array, use it;
* otherwise use all of them (joining into a string) * otherwise use all of them (joining into a string)
* *
* @param accepts The accepts array to select from * @param accepts The accepts array to select from
* @return The Accept header to use. If the given array is empty, * @return The Accept header to use. If the given array is empty,
* null will be returned (not to set the Accept header explicitly). * null will be returned (not to set the Accept header explicitly).
*/ */
public String selectHeaderAccept(String[] accepts) { public String selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) return null; if (accepts.length == 0) return null;
if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json";
return StringUtil.join(accepts, ","); return StringUtil.join(accepts, ",");
} }
/** /**
* Select the Content-Type header's value from the given array: * Select the Content-Type header's value from the given array:
* if JSON exists in the given array, use it; * if JSON exists in the given array, use it;
* otherwise use the first one of the array. * otherwise use the first one of the array.
* *
* @param contentTypes The Content-Type array to select from * @param contentTypes The Content-Type array to select from
* @return The Content-Type header to use. If the given array is empty, * @return The Content-Type header to use. If the given array is empty,
* JSON will be used. * JSON will be used.
*/ */
public String selectHeaderContentType(String[] contentTypes) { public String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) return "application/json"; if (contentTypes.length == 0) return "application/json";
if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json";
return contentTypes[0]; return contentTypes[0];
} }
/** /**
* Escape the given string to be used as URL query 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;
} }
} }
/** /**
* Deserialize the given JSON string to Java object. * Deserialize the given JSON string to Java object.
* *
* @param json The JSON string * @param json The JSON string
* @param containerType The container type, one of "list", "array" or "" * @param containerType The container type, one of "list", "array" or ""
* @param cls The type of the Java object * @param cls The type of the Java object
* @return The deserialized Java object * @return The deserialized Java object
*/ */
public Object deserialize(String json, String containerType, Class cls) throws ApiException { public Object deserialize(String json, String containerType, Class cls) throws ApiException {
if(null != containerType) { if(null != containerType) {
containerType = containerType.toLowerCase(); containerType = containerType.toLowerCase();
} }
try{ try{
if("list".equals(containerType) || "array".equals(containerType)) { if("list".equals(containerType) || "array".equals(containerType)) {
JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls); JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls);
List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo); List response = (List<?>) JsonUtil.getJsonMapper().readValue(json, typeInfo);
return response; return response;
} }
else if(String.class.equals(cls)) { else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 2); return json.substring(1, json.length() - 2);
else else
return json; return json;
} }
else { else {
return JsonUtil.getJsonMapper().readValue(json, cls); return JsonUtil.getJsonMapper().readValue(json, cls);
} }
} }
catch (IOException e) { catch (IOException e) {
throw new ApiException(500, e.getMessage(), null, json); throw new ApiException(500, e.getMessage(), null, json);
} }
} }
/** /**
* Serialize the given Java object into JSON string. * Serialize the given Java object into JSON string.
*/ */
public String serialize(Object obj) throws ApiException { 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);
else else
return null; return null;
} }
catch (Exception e) { catch (Exception e) {
throw new ApiException(500, e.getMessage()); throw new ApiException(500, e.getMessage());
} }
} }
/** /**
* Invoke API by sending HTTP request with the given options. * Invoke API by sending HTTP request with the given options.
* *
* @param path The sub-path of the HTTP URL * @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param queryParams The query parameters * @param queryParams The query parameters
* @param body The request body object * @param body The request body object
* @param headerParams The header parameters * @param headerParams The header parameters
* @param formParams The form parameters * @param formParams The form parameters
* @param accept The request's Accept header * @param accept The request's Accept header
* @param contentType The request's Content-Type header * @param contentType The request's Content-Type header
* @param authNames The authentications to apply * @param authNames The authentications to apply
* @return The response body in type of string * @return The response body in type of string
*/ */
public String invokeAPI(String path, String method, Map public String invokeAPI(String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String accept, String contentType, String[] authNames) throws ApiException {
<String, String> queryParams, Object body, Map updateParamsForAuth(authNames, queryParams, headerParams);
<String, String> headerParams, Map
<String, String> formParams, String accept, String contentType, String[] authNames) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
Client client = getClient(); Client client = getClient();
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
for(String key : queryParams.keySet()) { for(String key : queryParams.keySet()) {
String value = queryParams.get(key); String value = queryParams.get(key);
if (value != null){ if (value != null){
if(b.toString().length() == 0) if(b.toString().length() == 0)
b.append("?"); b.append("?");
else else
b.append("&"); b.append("&");
b.append(escapeString(key)).append("=").append(escapeString(value)); b.append(escapeString(key)).append("=").append(escapeString(value));
} }
} }
String querystring = b.toString(); String querystring = b.toString();
Builder builder; Builder builder;
if (accept == null) if (accept == null)
builder = client.resource(basePath + path + querystring).getRequestBuilder(); builder = client.resource(basePath + path + querystring).getRequestBuilder();
else else
builder = client.resource(basePath + path + querystring).accept(accept); builder = client.resource(basePath + path + querystring).accept(accept);
for(String key : headerParams.keySet()) { for(String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key)); builder = builder.header(key, headerParams.get(key));
} }
for(String key : defaultHeaderMap.keySet()) { for(String key : defaultHeaderMap.keySet()) {
if(!headerParams.containsKey(key)) { if(!headerParams.containsKey(key)) {
builder = builder.header(key, defaultHeaderMap.get(key)); builder = builder.header(key, defaultHeaderMap.get(key));
} }
} }
ClientResponse response = null; ClientResponse response = null;
if("GET".equals(method)) { if("GET".equals(method)) {
response = (ClientResponse) builder.get(ClientResponse.class); response = (ClientResponse) builder.get(ClientResponse.class);
} }
else if ("POST".equals(method)) { else if ("POST".equals(method)) {
if (contentType.startsWith("application/x-www-form-urlencoded")) { if (contentType.startsWith("application/x-www-form-urlencoded")) {
String encodedFormParams = this String encodedFormParams = this
.getXWWWFormUrlencodedParams(formParams); .getXWWWFormUrlencodedParams(formParams);
response = builder.type(contentType).post(ClientResponse.class, response = builder.type(contentType).post(ClientResponse.class,
encodedFormParams); encodedFormParams);
} else if (body == null) { } else if (body == null) {
response = builder.post(ClientResponse.class, null); response = builder.post(ClientResponse.class, null);
} else if(body instanceof FormDataMultiPart) { } else if(body instanceof FormDataMultiPart) {
response = builder.type(contentType).post(ClientResponse.class, body); response = builder.type(contentType).post(ClientResponse.class, body);
} }
else else
response = builder.type(contentType).post(ClientResponse.class, serialize(body)); response = builder.type(contentType).post(ClientResponse.class, serialize(body));
} }
else if ("PUT".equals(method)) { else if ("PUT".equals(method)) {
if ("application/x-www-form-urlencoded".equals(contentType)) { if ("application/x-www-form-urlencoded".equals(contentType)) {
String encodedFormParams = this String encodedFormParams = this
.getXWWWFormUrlencodedParams(formParams); .getXWWWFormUrlencodedParams(formParams);
response = builder.type(contentType).put(ClientResponse.class, response = builder.type(contentType).put(ClientResponse.class,
encodedFormParams); encodedFormParams);
} else if(body == null) { } else if(body == null) {
response = builder.put(ClientResponse.class, serialize(body)); response = builder.put(ClientResponse.class, serialize(body));
} else { } else {
response = builder.type(contentType).put(ClientResponse.class, serialize(body)); response = builder.type(contentType).put(ClientResponse.class, serialize(body));
} }
} }
else if ("DELETE".equals(method)) { else if ("DELETE".equals(method)) {
if ("application/x-www-form-urlencoded".equals(contentType)) { if ("application/x-www-form-urlencoded".equals(contentType)) {
String encodedFormParams = this String encodedFormParams = this
.getXWWWFormUrlencodedParams(formParams); .getXWWWFormUrlencodedParams(formParams);
response = builder.type(contentType).delete(ClientResponse.class, response = builder.type(contentType).delete(ClientResponse.class,
encodedFormParams); encodedFormParams);
} else if(body == null) { } else if(body == null) {
response = builder.delete(ClientResponse.class); response = builder.delete(ClientResponse.class);
} else { } else {
response = builder.type(contentType).delete(ClientResponse.class, serialize(body)); response = builder.type(contentType).delete(ClientResponse.class, serialize(body));
} }
} }
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;
} }
else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) { else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) {
if(response.hasEntity()) { if(response.hasEntity()) {
return (String) response.getEntity(String.class); return (String) response.getEntity(String.class);
} }
else { else {
return ""; return "";
} }
} }
else { else {
String message = "error"; String message = "error";
String respBody = null; String respBody = null;
if(response.hasEntity()) { if(response.hasEntity()) {
try{ try{
respBody = String.valueOf(response.getEntity(String.class)); respBody = String.valueOf(response.getEntity(String.class));
message = respBody; message = respBody;
} }
catch (RuntimeException e) { catch (RuntimeException e) {
// e.printStackTrace(); // e.printStackTrace();
} }
} }
throw new ApiException( throw new ApiException(
response.getClientResponseStatus().getStatusCode(), response.getClientResponseStatus().getStatusCode(),
message, message,
response.getHeaders(), response.getHeaders(),
respBody); respBody);
} }
} }
/** /**
* Update query and header parameters based on authentication settings. * Update query and header parameters based on authentication settings.
* *
* @param authNames The authentications to apply * @param authNames The authentications to apply
*/ */
private void updateParamsForAuth(String[] authNames, Map private void updateParamsForAuth(String[] authNames, Map<String, String> queryParams, Map<String, String> headerParams) {
<String, String> queryParams, Map for (String authName : authNames) {
<String, String> headerParams) { Authentication auth = authentications.get(authName);
for (String authName : authNames) { if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
Authentication auth = authentications.get(authName); auth.applyToParams(queryParams, headerParams);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); }
auth.applyToParams(queryParams, headerParams); }
}
}
/** /**
* Encode the given form parameters as request body. * Encode the given form parameters as request body.
*/ */
private String getXWWWFormUrlencodedParams(Map private String getXWWWFormUrlencodedParams(Map<String, String> formParams) {
<String, String> formParams) { StringBuilder formParamBuilder = new StringBuilder();
StringBuilder formParamBuilder = new StringBuilder();
for (Entry for (Entry<String, String> param : formParams.entrySet()) {
<String, String> param : formParams.entrySet()) { String keyStr = parameterToString(param.getKey());
String keyStr = parameterToString(param.getKey()); String valueStr = parameterToString(param.getValue());
String valueStr = parameterToString(param.getValue());
try { try {
formParamBuilder.append(URLEncoder.encode(keyStr, "utf8")) formParamBuilder.append(URLEncoder.encode(keyStr, "utf8"))
.append("=") .append("=")
.append(URLEncoder.encode(valueStr, "utf8")); .append(URLEncoder.encode(valueStr, "utf8"));
formParamBuilder.append("&"); formParamBuilder.append("&");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
// move on to next // move on to next
} }
} }
String encodedFormParams = formParamBuilder.toString(); String encodedFormParams = formParamBuilder.toString();
if (encodedFormParams.endsWith("&")) { if (encodedFormParams.endsWith("&")) {
encodedFormParams = encodedFormParams.substring(0, encodedFormParams = encodedFormParams.substring(0,
encodedFormParams.length() - 1); encodedFormParams.length() - 1);
} }
return encodedFormParams; return encodedFormParams;
} }
/** /**
* Get an existing client or create a new client to handle HTTP request. * Get an existing client or create a new client to handle HTTP request.
*/ */
private Client getClient() { private Client getClient() {
if(!hostMap.containsKey(basePath)) { if(!hostMap.containsKey(basePath)) {
Client client = Client.create(); Client client = Client.create();
if (debugging) if (debugging)
client.addFilter(new LoggingFilter()); client.addFilter(new LoggingFilter());
hostMap.put(basePath, client); hostMap.put(basePath, client);
} }
return hostMap.get(basePath); return hostMap.get(basePath);
} }
} }

View File

@ -1,21 +1,21 @@
package {{invokerPackage}}; package {{invokerPackage}};
public class Configuration { public class Configuration {
private static ApiClient defaultApiClient = new ApiClient(); private static ApiClient defaultApiClient = new ApiClient();
/** /**
* Get the default API client, which would be used when creating API * Get the default API client, which would be used when creating API
* instances without providing an API client. * instances without providing an API client.
*/ */
public static ApiClient getDefaultApiClient() { public static ApiClient getDefaultApiClient() {
return defaultApiClient; return defaultApiClient;
} }
/** /**
* Set the default API client, which would be used when creating API * Set the default API client, which would be used when creating API
* instances without providing an API client. * instances without providing an API client.
*/ */
public static void setDefaultApiClient(ApiClient apiClient) { public static void setDefaultApiClient(ApiClient apiClient) {
defaultApiClient = apiClient; defaultApiClient = apiClient;
} }
} }

View File

@ -8,16 +8,16 @@ import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.datatype.joda.*; import com.fasterxml.jackson.datatype.joda.*;
public class JsonUtil { public class JsonUtil {
public static ObjectMapper mapper; public static ObjectMapper mapper;
static { static {
mapper = new ObjectMapper(); mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.registerModule(new JodaModule()); mapper.registerModule(new JodaModule());
} }
public static ObjectMapper getJsonMapper() { public static ObjectMapper getJsonMapper() {
return mapper; return mapper;
} }
} }

View File

@ -1,41 +1,41 @@
package {{invokerPackage}}; package {{invokerPackage}};
public class StringUtil { public class StringUtil {
/** /**
* Check if the given array contains the given value (with case-insensitive comparison). * Check if the given array contains the given value (with case-insensitive comparison).
* *
* @param array The array * @param array The array
* @param value The value to search * @param value The value to search
* @return true if the array contains the value * @return true if the array contains the value
*/ */
public static boolean containsIgnoreCase(String[] array, String value) { public static boolean containsIgnoreCase(String[] array, String value) {
for (String str : array) { for (String str : array) {
if (value == null && str == null) return true; if (value == null && str == null) return true;
if (value != null && value.equalsIgnoreCase(str)) return true; if (value != null && value.equalsIgnoreCase(str)) return true;
} }
return false; return false;
} }
/** /**
* Join an array of strings with the given separator. * Join an array of strings with the given separator.
* <p> * <p>
* Note: This might be replaced by utility method from commons-lang or guava someday * Note: This might be replaced by utility method from commons-lang or guava someday
* if one of those libraries is added as dependency. * if one of those libraries is added as dependency.
* </p> * </p>
* *
* @param array The array of strings * @param array The array of strings
* @param separator The separator * @param separator The separator
* @return the resulting string * @return the resulting string
*/ */
public static String join(String[] array, String separator) { public static String join(String[] array, String separator) {
int len = array.length; int len = array.length;
if (len == 0) return ""; if (len == 0) return "";
StringBuilder out = new StringBuilder(); StringBuilder out = new StringBuilder();
out.append(array[0]); out.append(array[0]);
for (int i = 1; i < len; i++) { for (int i = 1; i < len; i++) {
out.append(separator).append(array[i]); out.append(separator).append(array[i]);
} }
return out.toString(); return out.toString();
} }
} }

View File

@ -21,7 +21,7 @@ import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
{{#operations}} {{#operations}}
public class {{classname}} { public class {{classname}} {
private ApiClient apiClient; private ApiClient apiClient;
public {{classname}}() { public {{classname}}() {
@ -44,8 +44,8 @@ import java.util.HashMap;
/** /**
* {{summary}} * {{summary}}
* {{notes}} * {{notes}}
{{#allParams}} * @param {{paramName}} {{description}} {{#allParams}} * @param {{paramName}} {{description}}
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/ */
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
@ -61,15 +61,9 @@ import java.util.HashMap;
.replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; .replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};
// query params // query params
Map Map<String, String> queryParams = new HashMap<String, String>();
<String, String> queryParams = new HashMap Map<String, String> headerParams = new HashMap<String, String>();
<String, String>(); Map<String, String> formParams = new HashMap<String, String>();
Map
<String, String> headerParams = new HashMap
<String, String>();
Map
<String, String> formParams = new HashMap
<String, String>();
{{#queryParams}}if ({{paramName}} != null) {{#queryParams}}if ({{paramName}} != null)
queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}}));
@ -127,5 +121,5 @@ import java.util.HashMap;
} }
} }
{{/operation}} {{/operation}}
} }
{{/operations}} {{/operations}}

View File

@ -4,11 +4,9 @@ import java.util.Map;
import java.util.List; import java.util.List;
public class ApiException extends Exception { public class ApiException extends Exception {
private int code = 0; private int code = 0;
private String message = null; private String message = null;
private Map private Map<String, List<String>> responseHeaders = null;
<String, List
<String>> responseHeaders = null;
private String responseBody = null; private String responseBody = null;
public ApiException() {} public ApiException() {}
@ -18,10 +16,7 @@ private Map
this.message = message; this.message = message;
} }
public ApiException(int code, String message, Map public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
<String
, List
<String>> responseHeaders, String responseBody) {
this.code = code; this.code = code;
this.message = message; this.message = message;
this.responseHeaders = responseHeaders; this.responseHeaders = responseHeaders;
@ -39,10 +34,7 @@ private Map
/** /**
* Get the HTTP response headers. * Get the HTTP response headers.
*/ */
public Map public Map<String, List<String>> getResponseHeaders() {
<String
, List
<String>> getResponseHeaders() {
return responseHeaders; return responseHeaders;
} }
@ -52,4 +44,4 @@ private Map
public String getResponseBody() { public String getResponseBody() {
return responseBody; return responseBody;
} }
} }

View File

@ -3,55 +3,53 @@ package {{invokerPackage}}.auth;
import java.util.Map; import java.util.Map;
public class ApiKeyAuth implements Authentication { public class ApiKeyAuth implements Authentication {
private final String location; private final String location;
private final String paramName; private final String paramName;
private String apiKey; private String apiKey;
private String apiKeyPrefix; private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) { public ApiKeyAuth(String location, String paramName) {
this.location = location; this.location = location;
this.paramName = paramName; this.paramName = paramName;
} }
public String getLocation() { public String getLocation() {
return location; return location;
} }
public String getParamName() { public String getParamName() {
return paramName; return paramName;
} }
public String getApiKey() { public String getApiKey() {
return apiKey; return apiKey;
} }
public void setApiKey(String apiKey) { public void setApiKey(String apiKey) {
this.apiKey = apiKey; this.apiKey = apiKey;
} }
public String getApiKeyPrefix() { public String getApiKeyPrefix() {
return apiKeyPrefix; return apiKeyPrefix;
} }
public void setApiKeyPrefix(String apiKeyPrefix) { public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix; this.apiKeyPrefix = apiKeyPrefix;
} }
@Override @Override
public void applyToParams(Map public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
<String, String> queryParams, Map String value;
<String, String> headerParams) { if (apiKeyPrefix != null) {
String value; value = apiKeyPrefix + " " + apiKey;
if (apiKeyPrefix != null) { } else {
value = apiKeyPrefix + " " + apiKey; value = apiKey;
} else { }
value = apiKey; if (location == "query") {
} queryParams.put(paramName, value);
if (location == "query") { } else if (location == "header") {
queryParams.put(paramName, value); headerParams.put(paramName, value);
} else if (location == "header") { }
headerParams.put(paramName, value); }
}
}
} }

View File

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

View File

@ -6,34 +6,32 @@ import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter; import javax.xml.bind.DatatypeConverter;
public class HttpBasicAuth implements Authentication { public class HttpBasicAuth implements Authentication {
private String username; private String username;
private String password; private String password;
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
@Override @Override
public void applyToParams(Map public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
<String, String> queryParams, Map String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
<String, String> headerParams) { try {
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8")));
try { } catch (UnsupportedEncodingException e) {
headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) { }
throw new RuntimeException(e); }
}
}
} }

View File

@ -3,10 +3,8 @@ package {{invokerPackage}}.auth;
import java.util.Map; import java.util.Map;
public class OAuth implements Authentication { public class OAuth implements Authentication {
@Override @Override
public void applyToParams(Map public void applyToParams(Map<String, String> queryParams, Map<String, String> headerParams) {
<String, String> queryParams, Map // TODO: support oauth
<String, String> headerParams) { }
// TODO: support oauth
}
} }

View File

@ -7,12 +7,12 @@ import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
{{#models}} {{#models}}
{{#model}}{{#description}} {{#model}}{{#description}}
/** /**
* {{description}} * {{description}}
**/{{/description}} **/{{/description}}
@ApiModel(description = "{{{description}}}") @ApiModel(description = "{{{description}}}")
public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {
{{#vars}}{{#isEnum}} {{#vars}}{{#isEnum}}
public enum {{datatypeWithEnum}} { public enum {{datatypeWithEnum}} {
{{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}}
@ -46,6 +46,6 @@ import com.fasterxml.jackson.annotation.JsonProperty;
{{/vars}}sb.append("}\n"); {{/vars}}sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }
{{/model}} {{/model}}
{{/models}} {{/models}}

View File

@ -77,8 +77,7 @@
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source> <source>src/main/java</source>
src/main/java</source>
</sources> </sources>
</configuration> </configuration>
</execution> </execution>
@ -90,8 +89,7 @@
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source> <source>src/test/java</source>
src/test/java</source>
</sources> </sources>
</configuration> </configuration>
</execution> </execution>
@ -102,8 +100,7 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source> <source>1.6</source>
1.6</source>
<target>1.6</target> <target>1.6</target>
</configuration> </configuration>
</plugin> </plugin>