Merge pull request #1703 from evigeant/feature/simple-jaxrs-serialization

Simplify Jersey and Jersey2 client serialization
This commit is contained in:
wing328 2015-12-16 11:32:11 +08:00
commit 0078dc11d1
26 changed files with 348 additions and 1005 deletions

View File

@ -234,7 +234,6 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
if (!("feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) {
supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java"));
supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java"));
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java"));
supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java"));
}
@ -244,6 +243,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
// the "okhttp-gson" library template requires "ApiCallback.mustache" for async call
supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java"));
supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java"));
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
supportingFiles.add(new SupportingFile("ProgressRequestBody.mustache", invokerFolder, "ProgressRequestBody.java"));
supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java"));
// "build.sbt" is for development with SBT
@ -251,8 +251,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
} else if ("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java"));
} else if (!"feign".equals(getLibrary())) {
supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java"));
} else if("jersey2".equals(getLibrary())) {
supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java"));
}
}

View File

@ -1,8 +1,13 @@
package {{invokerPackage}};
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.joda.*;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.api.client.WebResource.Builder;
@ -25,14 +30,11 @@ import java.util.TimeZone;
import java.net.URLEncoder;
import java.io.IOException;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.io.DataInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import {{invokerPackage}}.auth.Authentication;
import {{invokerPackage}}.auth.HttpBasicAuth;
@ -45,7 +47,7 @@ public class ApiClient {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private boolean debugging = false;
private String basePath = "{{basePath}}";
private JSON json = new JSON();
private ObjectMapper mapper;
private Map<String, Authentication> authentications;
@ -55,6 +57,14 @@ public class ApiClient {
private DateFormat dateFormat;
public ApiClient() {
mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.registerModule(new JodaModule());
// Use RFC3339 format for date and datetime.
// See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
@ -62,7 +72,7 @@ public class ApiClient {
// Use UTC as the default time zone.
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
this.json.setDateFormat((DateFormat) dateFormat.clone());
this.mapper.setDateFormat((DateFormat) dateFormat.clone());
// Set default User-Agent.
setUserAgent("Java-Swagger");
@ -76,13 +86,6 @@ public class ApiClient {
authentications = Collections.unmodifiableMap(authentications);
}
/**
* Gets the JSON instance to do JSON serialization and deserialization.
*/
public JSON getJSON() {
return json;
}
public String getBasePath() {
return basePath;
}
@ -237,7 +240,7 @@ public class ApiClient {
public ApiClient setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
// also set the date format for model (de)serialization with Date properties
this.json.setDateFormat((DateFormat) dateFormat.clone());
this.mapper.setDateFormat((DateFormat) dateFormat.clone());
return this;
}
@ -269,7 +272,7 @@ public class ApiClient {
return formatDate((Date) param);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection)param) {
for(Object o : (Collection<?>)param) {
if(b.length() > 0) {
b.append(",");
}
@ -290,9 +293,9 @@ public class ApiClient {
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
Collection valueCollection = null;
if (value instanceof Collection) {
valueCollection = (Collection) value;
Collection<?> valueCollection = null;
if (value instanceof Collection<?>) {
valueCollection = (Collection<?>) value;
} else {
params.add(new Pair(name, parameterToString(value)));
return params;
@ -405,49 +408,30 @@ public class ApiClient {
* Serialize the given Java object into string according the given
* Content-Type (only JSON is supported for now).
*/
public String serialize(Object obj, String contentType) throws ApiException {
if (isJsonMime(contentType)) {
return json.serialize(obj);
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
if (contentType.startsWith("multipart/form-data")) {
FormDataMultiPart mp = new FormDataMultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
} else {
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
}
}
return mp;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
return this.getXWWWFormUrlencodedParams(formParams);
} else {
throw new ApiException(400, "can not serialize object into Content-Type: " + contentType);
// We let Jersey attempt to serialize the body
return obj;
}
}
/**
* Deserialize response body to Java object according to the Content-Type.
*/
public <T> T deserialize(ClientResponse response, TypeRef returnType) throws ApiException {
String contentType = null;
List<String> contentTypes = response.getHeaders().get("Content-Type");
if (contentTypes != null && !contentTypes.isEmpty())
contentType = contentTypes.get(0);
if (contentType == null)
throw new ApiException(500, "missing Content-Type in response");
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
String body;
if (response.hasEntity())
body = (String) response.getEntity(String.class);
else
body = "";
if (isJsonMime(contentType)) {
return json.deserialize(body, returnType);
} else if (returnType.getType().equals(String.class)) {
// Expecting string, return the raw response body.
return (T) body;
} else {
throw new ApiException(
500,
"Content type \"" + contentType + "\" is not supported for type: "
+ returnType.getType()
);
}
}
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, byte[] binaryBody, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
if (body != null && binaryBody != null){
throw new ApiException(500, "either body or binaryBody must be null");
if (body != null && !formParams.isEmpty()){
throw new ApiException(500, "Cannot have body and form params");
}
updateParamsForAuth(authNames, queryParams, headerParams);
@ -484,61 +468,16 @@ public class ApiClient {
}
}
String encodedFormParams = null;
if (contentType.startsWith("multipart/form-data")) {
FormDataMultiPart mp = new FormDataMultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
} else {
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
}
}
body = mp;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
encodedFormParams = this.getXWWWFormUrlencodedParams(formParams);
}
ClientResponse response = null;
if ("GET".equals(method)) {
response = (ClientResponse) builder.get(ClientResponse.class);
} else if ("POST".equals(method)) {
if (encodedFormParams != null) {
response = builder.type(contentType).post(ClientResponse.class, encodedFormParams);
} else if (body == null) {
if(binaryBody == null)
response = builder.post(ClientResponse.class, null);
else
response = builder.type(contentType).post(ClientResponse.class, binaryBody);
} else if (body instanceof FormDataMultiPart) {
response = builder.type(contentType).post(ClientResponse.class, body);
} else {
response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType));
}
response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("PUT".equals(method)) {
if (encodedFormParams != null) {
response = builder.type(contentType).put(ClientResponse.class, encodedFormParams);
} else if(body == null) {
if(binaryBody == null)
response = builder.put(ClientResponse.class, null);
else
response = builder.type(contentType).put(ClientResponse.class, binaryBody);
} else {
response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType));
}
response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("DELETE".equals(method)) {
if (encodedFormParams != null) {
response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams);
} else if(body == null) {
if(binaryBody == null)
response = builder.delete(ClientResponse.class);
else
response = builder.type(contentType).delete(ClientResponse.class, binaryBody);
} else {
response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType));
}
response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams));
} else {
throw new ApiException(500, "unknown method type " + method);
}
@ -552,7 +491,6 @@ public class ApiClient {
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param queryParams The query parameters
* @param body The request body object - if it is not binary, otherwise null
* @param binaryBody The request body object - if it is binary, otherwise null
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
@ -560,9 +498,9 @@ public class ApiClient {
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, byte[] binaryBody, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException {
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames);
ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames);
statusCode = response.getStatusInfo().getStatusCode();
responseHeaders = response.getHeaders();
@ -573,13 +511,13 @@ public class ApiClient {
if (returnType == null)
return null;
else
return deserialize(response, returnType);
return response.getEntity(returnType);
} else {
String message = "error";
String respBody = null;
if (response.hasEntity()) {
try {
respBody = String.valueOf(response.getEntity(String.class));
respBody = response.getEntity(String.class);
message = respBody;
} catch (RuntimeException e) {
// e.printStackTrace();
@ -592,58 +530,6 @@ public class ApiClient {
respBody);
}
}
/**
* Invoke API by sending HTTP request with the given options - return binary result
*
* @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 - if it is not binary, otherwise null
* @param binaryBody The request body object - if it is binary, otherwise null
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public byte[] invokeBinaryAPI(String path, String method, List<Pair> queryParams, Object body, byte[] binaryBody, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[]authNames) throws ApiException {
ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames);
if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) {
return null;
}
else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
if(response.hasEntity()) {
DataInputStream stream = new DataInputStream(response.getEntityInputStream());
byte[] data = new byte[response.getLength()];
try {
stream.readFully(data);
} catch (IOException ex) {
throw new ApiException(500, "Error obtaining binary response data");
}
return data;
}
else {
return new byte[0];
}
}
else {
String message = "error";
if(response.hasEntity()) {
try{
message = String.valueOf(response.getEntity(String.class));
}
catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
message);
}
}
/**
* Update query and header parameters based on authentication settings.
@ -665,7 +551,6 @@ public class ApiClient {
StringBuilder formParamBuilder = new StringBuilder();
for (Entry<String, Object> param : formParams.entrySet()) {
String keyStr = param.getKey();
String valueStr = parameterToString(param.getValue());
try {
formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8"))
@ -690,7 +575,11 @@ public class ApiClient {
*/
private Client getClient() {
if(!hostMap.containsKey(basePath)) {
Client client = Client.create();
// Add the JSON serialization support to Jersey
JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper);
DefaultClientConfig conf = new DefaultClientConfig();
conf.getSingletons().add(jsonProvider);
Client client = Client.create(conf);
if (debugging)
client.addFilter(new LoggingFilter());
hostMap.put(basePath, client);

View File

@ -1,64 +0,0 @@
package {{invokerPackage}};
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.joda.*;
import java.text.DateFormat;
import java.io.IOException;
{{>generatedAnnotation}}
public class JSON {
private ObjectMapper mapper;
public JSON() {
mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.registerModule(new JodaModule());
}
/**
* Set the date format for JSON (de)serialization with Date properties.
*/
public void setDateFormat(DateFormat dateFormat) {
mapper.setDateFormat(dateFormat);
}
/**
* Serialize the given Java object into JSON string.
*/
public String serialize(Object obj) throws ApiException {
try {
if (obj != null)
return mapper.writeValueAsString(obj);
else
return null;
} catch (Exception e) {
throw new ApiException(400, e.getMessage());
}
}
/**
* Deserialize the given JSON string to Java object.
*
* @param body The JSON string
* @param returnType The type to deserialize inot
* @return The deserialized Java object
*/
public <T> T deserialize(String body, TypeRef returnType) throws ApiException {
JavaType javaType = mapper.constructType(returnType.getType());
try {
return mapper.readValue(body, javaType);
} catch (IOException e) {
if (returnType.getType().equals(String.class))
return (T) body;
else
throw new ApiException(500, e.getMessage(), null, body);
}
}
}

View File

@ -1,26 +0,0 @@
package {{invokerPackage}};
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
{{>generatedAnnotation}}
public class TypeRef<T> {
private final Type type;
public TypeRef() {
this.type = getGenericType(getClass());
}
private static Type getGenericType(Class<?> klass) {
Type superclass = klass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("No type parameter provided");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return parameterized.getActualTypeArguments()[0];
}
public Type getType() {
return type;
}
}

View File

@ -1,10 +1,11 @@
package {{package}};
import com.sun.jersey.api.client.GenericType;
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.ApiClient;
import {{invokerPackage}}.Configuration;
import {{invokerPackage}}.Pair;
import {{invokerPackage}}.TypeRef;
{{#imports}}import {{import}};
{{/imports}}
@ -42,8 +43,7 @@ public class {{classname}} {
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{^isBinary}}{{paramName}}{{/isBinary}}{{#isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
byte[] {{localVariablePrefix}}postBinaryBody = {{#bodyParam}}{{#isBinary}}{{paramName}}{{/isBinary}}{{^isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
@ -83,22 +83,12 @@ public class {{classname}} {
String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
{{#isResponseBinary}}
byte[] {{localVariablePrefix}}response = null;
{{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeBinaryAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams,{{localVariablePrefix}} postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames);
return {{localVariablePrefix}}response;
{{/isResponseBinary}}
{{^isResponseBinary}}
{{#returnType}}
TypeRef {{localVariablePrefix}}returnType = new TypeRef<{{{returnType}}}>() {};
return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType);
GenericType<{{{returnType}}}> {{localVariablePrefix}}returnType = new GenericType<{{{returnType}}}>() {};
return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType);
{{/returnType}}{{^returnType}}
{{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null);
{{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null);
{{/returnType}}
{{/isResponseBinary}}
}
{{/operation}}
}

View File

@ -6,6 +6,7 @@ import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@ -29,13 +30,11 @@ import java.util.TimeZone;
import java.net.URLEncoder;
import java.io.IOException;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import {{invokerPackage}}.auth.Authentication;
import {{invokerPackage}}.auth.HttpBasicAuth;
@ -412,18 +411,39 @@ public class ApiClient {
* Serialize the given Java object into string entity according the given
* Content-Type (only JSON is supported for now).
*/
public Entity<String> serialize(Object obj, String contentType) throws ApiException {
if (isJsonMime(contentType)) {
return Entity.json(json.serialize(obj));
public Entity<?> serialize(Object obj, Map<String, Object> formParams, String contentType) throws ApiException {
Entity<?> entity = null;
if (contentType.startsWith("multipart/form-data")) {
MultiPart multiPart = new MultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey())
.fileName(file.getName()).size(file.length()).build();
multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
} else {
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build();
multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue())));
}
}
entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE);
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
Form form = new Form();
for (Entry<String, Object> param: formParams.entrySet()) {
form.param(param.getKey(), parameterToString(param.getValue()));
}
entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
} else {
throw new ApiException(400, "can not serialize object into Content-Type: " + contentType);
// We let jersey handle the serialization
entity = Entity.entity(obj, contentType);
}
return entity;
}
/**
* Deserialize response body to Java object according to the Content-Type.
*/
public <T> T deserialize(Response response, TypeRef returnType) throws ApiException {
public <T> T deserialize(Response response, GenericType<T> returnType) throws ApiException {
String contentType = null;
List<Object> contentTypes = response.getHeaders().get("Content-Type");
if (contentTypes != null && !contentTypes.isEmpty())
@ -431,24 +451,7 @@ public class ApiClient {
if (contentType == null)
throw new ApiException(500, "missing Content-Type in response");
String body;
if (response.hasEntity())
body = (String) response.readEntity(String.class);
else
body = "";
if (isJsonMime(contentType)) {
return json.deserialize(body, returnType);
} else if (returnType.getType().equals(String.class)) {
// Expecting string, return the raw response body.
return (T) body;
} else {
throw new ApiException(
500,
"Content type \"" + contentType + "\" is not supported for type: "
+ returnType.getType()
);
}
return response.readEntity(returnType);
}
/**
@ -466,7 +469,7 @@ public class ApiClient {
* @param returnType The return type into which to deserialize the response
* @return The response body in type of string
*/
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException {
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
WebTarget target = client.target(this.basePath).path(path);
@ -497,50 +500,16 @@ public class ApiClient {
}
}
Entity<?> formEntity = null;
if (contentType.startsWith("multipart/form-data")) {
MultiPart multiPart = new MultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey())
.fileName(file.getName()).size(file.length()).build();
multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
} else {
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build();
multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue())));
}
}
formEntity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE);
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
Form form = new Form();
for (Entry<String, Object> param: formParams.entrySet()) {
form.param(param.getKey(), parameterToString(param.getValue()));
}
formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
}
Entity<?> entity = serialize(body, formParams, contentType);
Response response = null;
if ("GET".equals(method)) {
response = invocationBuilder.get();
} else if ("POST".equals(method)) {
if (formEntity != null) {
response = invocationBuilder.post(formEntity);
} else if (body == null) {
response = invocationBuilder.post(null);
} else {
response = invocationBuilder.post(serialize(body, contentType));
}
response = invocationBuilder.post(entity);
} else if ("PUT".equals(method)) {
if (formEntity != null) {
response = invocationBuilder.put(formEntity);
} else if (body == null) {
response = invocationBuilder.put(null);
} else {
response = invocationBuilder.put(serialize(body, contentType));
}
response = invocationBuilder.put(entity);
} else if ("DELETE".equals(method)) {
response = invocationBuilder.delete();
} else {
@ -579,6 +548,8 @@ public class ApiClient {
private void buildClient() {
final ClientConfig clientConfig = new ClientConfig();
clientConfig.register(MultiPartFeature.class);
clientConfig.register(json);
clientConfig.register(org.glassfish.jersey.jackson.JacksonFeature.class);
if (debugging) {
clientConfig.register(LoggingFilter.class);
}

View File

@ -0,0 +1,36 @@
package {{invokerPackage}};
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.joda.*;
import java.text.DateFormat;
import javax.ws.rs.ext.ContextResolver;
{{>generatedAnnotation}}
public class JSON implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper;
public JSON() {
mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.registerModule(new JodaModule());
}
/**
* Set the date format for JSON (de)serialization with Date properties.
*/
public void setDateFormat(DateFormat dateFormat) {
mapper.setDateFormat(dateFormat);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}

View File

@ -4,7 +4,8 @@ import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.ApiClient;
import {{invokerPackage}}.Configuration;
import {{invokerPackage}}.Pair;
import {{invokerPackage}}.TypeRef;
import javax.ws.rs.core.GenericType;
{{#imports}}import {{import}};
{{/imports}}
@ -83,7 +84,7 @@ public class {{classname}} {
String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
{{#returnType}}
TypeRef {{localVariablePrefix}}returnType = new TypeRef<{{{returnType}}}>() {};
GenericType<{{{returnType}}}> {{localVariablePrefix}}returnType = new GenericType<{{{returnType}}}>() {};
return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType);
{{/returnType}}{{^returnType}}
{{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null);

View File

@ -124,7 +124,12 @@
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.22.1</version>
</dependency>
<!-- JSON processing: jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>

View File

@ -137,6 +137,11 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>

View File

@ -137,6 +137,11 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>

View File

@ -1,8 +1,13 @@
package io.swagger.client;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.joda.*;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.api.client.WebResource.Builder;
@ -25,27 +30,24 @@ import java.util.TimeZone;
import java.net.URLEncoder;
import java.io.IOException;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.io.DataInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import io.swagger.client.auth.Authentication;
import io.swagger.client.auth.HttpBasicAuth;
import io.swagger.client.auth.ApiKeyAuth;
import io.swagger.client.auth.OAuth;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T16:17:57.986+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T22:51:50.471-05:00")
public class ApiClient {
private Map<String, Client> hostMap = new HashMap<String, Client>();
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private boolean debugging = false;
private String basePath = "http://petstore.swagger.io/v2";
private JSON json = new JSON();
private ObjectMapper mapper;
private Map<String, Authentication> authentications;
@ -55,6 +57,14 @@ public class ApiClient {
private DateFormat dateFormat;
public ApiClient() {
mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.registerModule(new JodaModule());
// Use RFC3339 format for date and datetime.
// See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
@ -62,7 +72,7 @@ public class ApiClient {
// Use UTC as the default time zone.
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
this.json.setDateFormat((DateFormat) dateFormat.clone());
this.mapper.setDateFormat((DateFormat) dateFormat.clone());
// Set default User-Agent.
setUserAgent("Java-Swagger");
@ -75,13 +85,6 @@ public class ApiClient {
authentications = Collections.unmodifiableMap(authentications);
}
/**
* Gets the JSON instance to do JSON serialization and deserialization.
*/
public JSON getJSON() {
return json;
}
public String getBasePath() {
return basePath;
}
@ -236,7 +239,7 @@ public class ApiClient {
public ApiClient setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
// also set the date format for model (de)serialization with Date properties
this.json.setDateFormat((DateFormat) dateFormat.clone());
this.mapper.setDateFormat((DateFormat) dateFormat.clone());
return this;
}
@ -268,7 +271,7 @@ public class ApiClient {
return formatDate((Date) param);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection)param) {
for(Object o : (Collection<?>)param) {
if(b.length() > 0) {
b.append(",");
}
@ -289,9 +292,9 @@ public class ApiClient {
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
Collection valueCollection = null;
if (value instanceof Collection) {
valueCollection = (Collection) value;
Collection<?> valueCollection = null;
if (value instanceof Collection<?>) {
valueCollection = (Collection<?>) value;
} else {
params.add(new Pair(name, parameterToString(value)));
return params;
@ -404,49 +407,30 @@ public class ApiClient {
* Serialize the given Java object into string according the given
* Content-Type (only JSON is supported for now).
*/
public String serialize(Object obj, String contentType) throws ApiException {
if (isJsonMime(contentType)) {
return json.serialize(obj);
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
if (contentType.startsWith("multipart/form-data")) {
FormDataMultiPart mp = new FormDataMultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
} else {
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
}
}
return mp;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
return this.getXWWWFormUrlencodedParams(formParams);
} else {
throw new ApiException(400, "can not serialize object into Content-Type: " + contentType);
// We let Jersey attempt to serialize the body
return obj;
}
}
/**
* Deserialize response body to Java object according to the Content-Type.
*/
public <T> T deserialize(ClientResponse response, TypeRef returnType) throws ApiException {
String contentType = null;
List<String> contentTypes = response.getHeaders().get("Content-Type");
if (contentTypes != null && !contentTypes.isEmpty())
contentType = contentTypes.get(0);
if (contentType == null)
throw new ApiException(500, "missing Content-Type in response");
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
String body;
if (response.hasEntity())
body = (String) response.getEntity(String.class);
else
body = "";
if (isJsonMime(contentType)) {
return json.deserialize(body, returnType);
} else if (returnType.getType().equals(String.class)) {
// Expecting string, return the raw response body.
return (T) body;
} else {
throw new ApiException(
500,
"Content type \"" + contentType + "\" is not supported for type: "
+ returnType.getType()
);
}
}
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, byte[] binaryBody, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
if (body != null && binaryBody != null){
throw new ApiException(500, "either body or binaryBody must be null");
if (body != null && !formParams.isEmpty()){
throw new ApiException(500, "Cannot have body and form params");
}
updateParamsForAuth(authNames, queryParams, headerParams);
@ -483,61 +467,16 @@ public class ApiClient {
}
}
String encodedFormParams = null;
if (contentType.startsWith("multipart/form-data")) {
FormDataMultiPart mp = new FormDataMultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
} else {
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
}
}
body = mp;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
encodedFormParams = this.getXWWWFormUrlencodedParams(formParams);
}
ClientResponse response = null;
if ("GET".equals(method)) {
response = (ClientResponse) builder.get(ClientResponse.class);
} else if ("POST".equals(method)) {
if (encodedFormParams != null) {
response = builder.type(contentType).post(ClientResponse.class, encodedFormParams);
} else if (body == null) {
if(binaryBody == null)
response = builder.post(ClientResponse.class, null);
else
response = builder.type(contentType).post(ClientResponse.class, binaryBody);
} else if (body instanceof FormDataMultiPart) {
response = builder.type(contentType).post(ClientResponse.class, body);
} else {
response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType));
}
response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("PUT".equals(method)) {
if (encodedFormParams != null) {
response = builder.type(contentType).put(ClientResponse.class, encodedFormParams);
} else if(body == null) {
if(binaryBody == null)
response = builder.put(ClientResponse.class, null);
else
response = builder.type(contentType).put(ClientResponse.class, binaryBody);
} else {
response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType));
}
response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("DELETE".equals(method)) {
if (encodedFormParams != null) {
response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams);
} else if(body == null) {
if(binaryBody == null)
response = builder.delete(ClientResponse.class);
else
response = builder.type(contentType).delete(ClientResponse.class, binaryBody);
} else {
response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType));
}
response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams));
} else {
throw new ApiException(500, "unknown method type " + method);
}
@ -551,7 +490,6 @@ public class ApiClient {
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param queryParams The query parameters
* @param body The request body object - if it is not binary, otherwise null
* @param binaryBody The request body object - if it is binary, otherwise null
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
@ -559,9 +497,9 @@ public class ApiClient {
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, byte[] binaryBody, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException {
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames);
ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames);
statusCode = response.getStatusInfo().getStatusCode();
responseHeaders = response.getHeaders();
@ -572,13 +510,13 @@ public class ApiClient {
if (returnType == null)
return null;
else
return deserialize(response, returnType);
return response.getEntity(returnType);
} else {
String message = "error";
String respBody = null;
if (response.hasEntity()) {
try {
respBody = String.valueOf(response.getEntity(String.class));
respBody = response.getEntity(String.class);
message = respBody;
} catch (RuntimeException e) {
// e.printStackTrace();
@ -591,58 +529,6 @@ public class ApiClient {
respBody);
}
}
/**
* Invoke API by sending HTTP request with the given options - return binary result
*
* @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 - if it is not binary, otherwise null
* @param binaryBody The request body object - if it is binary, otherwise null
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public byte[] invokeBinaryAPI(String path, String method, List<Pair> queryParams, Object body, byte[] binaryBody, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[]authNames) throws ApiException {
ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames);
if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) {
return null;
}
else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
if(response.hasEntity()) {
DataInputStream stream = new DataInputStream(response.getEntityInputStream());
byte[] data = new byte[response.getLength()];
try {
stream.readFully(data);
} catch (IOException ex) {
throw new ApiException(500, "Error obtaining binary response data");
}
return data;
}
else {
return new byte[0];
}
}
else {
String message = "error";
if(response.hasEntity()) {
try{
message = String.valueOf(response.getEntity(String.class));
}
catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
message);
}
}
/**
* Update query and header parameters based on authentication settings.
@ -664,7 +550,6 @@ public class ApiClient {
StringBuilder formParamBuilder = new StringBuilder();
for (Entry<String, Object> param : formParams.entrySet()) {
String keyStr = param.getKey();
String valueStr = parameterToString(param.getValue());
try {
formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8"))
@ -689,7 +574,11 @@ public class ApiClient {
*/
private Client getClient() {
if(!hostMap.containsKey(basePath)) {
Client client = Client.create();
// Add the JSON serialization support to Jersey
JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper);
DefaultClientConfig conf = new DefaultClientConfig();
conf.getSingletons().add(jsonProvider);
Client client = Client.create(conf);
if (debugging)
client.addFilter(new LoggingFilter());
hostMap.put(basePath, client);

View File

@ -1,64 +0,0 @@
package io.swagger.client;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.joda.*;
import java.text.DateFormat;
import java.io.IOException;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:25.953+08:00")
public class JSON {
private ObjectMapper mapper;
public JSON() {
mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.registerModule(new JodaModule());
}
/**
* Set the date format for JSON (de)serialization with Date properties.
*/
public void setDateFormat(DateFormat dateFormat) {
mapper.setDateFormat(dateFormat);
}
/**
* Serialize the given Java object into JSON string.
*/
public String serialize(Object obj) throws ApiException {
try {
if (obj != null)
return mapper.writeValueAsString(obj);
else
return null;
} catch (Exception e) {
throw new ApiException(400, e.getMessage());
}
}
/**
* Deserialize the given JSON string to Java object.
*
* @param body The JSON string
* @param returnType The type to deserialize inot
* @return The deserialized Java object
*/
public <T> T deserialize(String body, TypeRef returnType) throws ApiException {
JavaType javaType = mapper.constructType(returnType.getType());
try {
return mapper.readValue(body, javaType);
} catch (IOException e) {
if (returnType.getType().equals(String.class))
return (T) body;
else
throw new ApiException(500, e.getMessage(), null, body);
}
}
}

View File

@ -1,26 +0,0 @@
package io.swagger.client;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:25.953+08:00")
public class TypeRef<T> {
private final Type type;
public TypeRef() {
this.type = getGenericType(getClass());
}
private static Type getGenericType(Class<?> klass) {
Type superclass = klass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("No type parameter provided");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return parameterized.getActualTypeArguments()[0];
}
public Type getType() {
return type;
}
}

View File

@ -1,17 +1,18 @@
package io.swagger.client.api;
import com.sun.jersey.api.client.GenericType;
import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.Pair;
import io.swagger.client.TypeRef;
import io.swagger.client.model.Pet;
import java.io.File;
import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:25.953+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T22:51:50.471-05:00")
public class PetApi {
private ApiClient apiClient;
@ -38,9 +39,8 @@ public class PetApi {
* @param body Pet object that needs to be added to the store
* @return void
*/
public void updatePet (Pet body) throws ApiException {
public void updatePet(Pet body) throws ApiException {
Object postBody = body;
byte[] postBinaryBody = null;
// create path and map variables
String path = "/pet".replaceAll("\\{format\\}","json");
@ -69,14 +69,8 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "PUT", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
@ -85,9 +79,8 @@ public class PetApi {
* @param body Pet object that needs to be added to the store
* @return void
*/
public void addPet (Pet body) throws ApiException {
public void addPet(Pet body) throws ApiException {
Object postBody = body;
byte[] postBinaryBody = null;
// create path and map variables
String path = "/pet".replaceAll("\\{format\\}","json");
@ -116,14 +109,8 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
@ -132,9 +119,8 @@ public class PetApi {
* @param status Status values that need to be considered for filter
* @return List<Pet>
*/
public List<Pet> findPetsByStatus (List<String> status) throws ApiException {
public List<Pet> findPetsByStatus(List<String> status) throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// create path and map variables
String path = "/pet/findByStatus".replaceAll("\\{format\\}","json");
@ -165,15 +151,9 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" };
GenericType<List<Pet>> returnType = new GenericType<List<Pet>>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
TypeRef returnType = new TypeRef<List<Pet>>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
@ -182,9 +162,8 @@ public class PetApi {
* @param tags Tags to filter by
* @return List<Pet>
*/
public List<Pet> findPetsByTags (List<String> tags) throws ApiException {
public List<Pet> findPetsByTags(List<String> tags) throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// create path and map variables
String path = "/pet/findByTags".replaceAll("\\{format\\}","json");
@ -215,15 +194,9 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" };
GenericType<List<Pet>> returnType = new GenericType<List<Pet>>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
TypeRef returnType = new TypeRef<List<Pet>>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
@ -232,9 +205,8 @@ public class PetApi {
* @param petId ID of pet that needs to be fetched
* @return Pet
*/
public Pet getPetById (Long petId) throws ApiException {
public Pet getPetById(Long petId) throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
@ -269,15 +241,9 @@ public class PetApi {
String[] authNames = new String[] { "api_key" };
GenericType<Pet> returnType = new GenericType<Pet>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
TypeRef returnType = new TypeRef<Pet>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
@ -288,9 +254,8 @@ public class PetApi {
* @param status Updated status of the pet
* @return void
*/
public void updatePetWithForm (String petId, String name, String status) throws ApiException {
public void updatePetWithForm(String petId, String name, String status) throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
@ -329,14 +294,8 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
@ -346,9 +305,8 @@ public class PetApi {
* @param apiKey
* @return void
*/
public void deletePet (Long petId, String apiKey) throws ApiException {
public void deletePet(Long petId, String apiKey) throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
@ -385,14 +343,8 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
@ -403,9 +355,8 @@ public class PetApi {
* @param file file to upload
* @return void
*/
public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException {
public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
@ -444,14 +395,8 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
}

View File

@ -1,17 +1,18 @@
package io.swagger.client.api;
import com.sun.jersey.api.client.GenericType;
import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.Pair;
import io.swagger.client.TypeRef;
import java.util.Map;
import io.swagger.client.model.Order;
import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:25.953+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T22:51:50.471-05:00")
public class StoreApi {
private ApiClient apiClient;
@ -37,9 +38,8 @@ public class StoreApi {
* Returns a map of status codes to quantities
* @return Map<String, Integer>
*/
public Map<String, Integer> getInventory () throws ApiException {
public Map<String, Integer> getInventory() throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// create path and map variables
String path = "/store/inventory".replaceAll("\\{format\\}","json");
@ -68,15 +68,9 @@ public class StoreApi {
String[] authNames = new String[] { "api_key" };
GenericType<Map<String, Integer>> returnType = new GenericType<Map<String, Integer>>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
TypeRef returnType = new TypeRef<Map<String, Integer>>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
@ -85,9 +79,8 @@ public class StoreApi {
* @param body order placed for purchasing the pet
* @return Order
*/
public Order placeOrder (Order body) throws ApiException {
public Order placeOrder(Order body) throws ApiException {
Object postBody = body;
byte[] postBinaryBody = null;
// create path and map variables
String path = "/store/order".replaceAll("\\{format\\}","json");
@ -116,15 +109,9 @@ public class StoreApi {
String[] authNames = new String[] { };
GenericType<Order> returnType = new GenericType<Order>() {};
return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
TypeRef returnType = new TypeRef<Order>() {};
return apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
@ -133,9 +120,8 @@ public class StoreApi {
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
public Order getOrderById (String orderId) throws ApiException {
public Order getOrderById(String orderId) throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
@ -170,15 +156,9 @@ public class StoreApi {
String[] authNames = new String[] { };
GenericType<Order> returnType = new GenericType<Order>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
TypeRef returnType = new TypeRef<Order>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
@ -187,9 +167,8 @@ public class StoreApi {
* @param orderId ID of the order that needs to be deleted
* @return void
*/
public void deleteOrder (String orderId) throws ApiException {
public void deleteOrder(String orderId) throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
@ -224,14 +203,8 @@ public class StoreApi {
String[] authNames = new String[] { };
apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
}

View File

@ -1,17 +1,18 @@
package io.swagger.client.api;
import com.sun.jersey.api.client.GenericType;
import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.Pair;
import io.swagger.client.TypeRef;
import io.swagger.client.model.User;
import java.util.*;
import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:25.953+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T22:51:50.471-05:00")
public class UserApi {
private ApiClient apiClient;
@ -38,9 +39,8 @@ public class UserApi {
* @param body Created user object
* @return void
*/
public void createUser (User body) throws ApiException {
public void createUser(User body) throws ApiException {
Object postBody = body;
byte[] postBinaryBody = null;
// create path and map variables
String path = "/user".replaceAll("\\{format\\}","json");
@ -69,14 +69,8 @@ public class UserApi {
String[] authNames = new String[] { };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
@ -85,9 +79,8 @@ public class UserApi {
* @param body List of user object
* @return void
*/
public void createUsersWithArrayInput (List<User> body) throws ApiException {
public void createUsersWithArrayInput(List<User> body) throws ApiException {
Object postBody = body;
byte[] postBinaryBody = null;
// create path and map variables
String path = "/user/createWithArray".replaceAll("\\{format\\}","json");
@ -116,14 +109,8 @@ public class UserApi {
String[] authNames = new String[] { };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
@ -132,9 +119,8 @@ public class UserApi {
* @param body List of user object
* @return void
*/
public void createUsersWithListInput (List<User> body) throws ApiException {
public void createUsersWithListInput(List<User> body) throws ApiException {
Object postBody = body;
byte[] postBinaryBody = null;
// create path and map variables
String path = "/user/createWithList".replaceAll("\\{format\\}","json");
@ -163,14 +149,8 @@ public class UserApi {
String[] authNames = new String[] { };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
@ -180,9 +160,8 @@ public class UserApi {
* @param password The password for login in clear text
* @return String
*/
public String loginUser (String username, String password) throws ApiException {
public String loginUser(String username, String password) throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// create path and map variables
String path = "/user/login".replaceAll("\\{format\\}","json");
@ -215,15 +194,9 @@ public class UserApi {
String[] authNames = new String[] { };
GenericType<String> returnType = new GenericType<String>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
TypeRef returnType = new TypeRef<String>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
@ -231,9 +204,8 @@ public class UserApi {
*
* @return void
*/
public void logoutUser () throws ApiException {
public void logoutUser() throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// create path and map variables
String path = "/user/logout".replaceAll("\\{format\\}","json");
@ -262,14 +234,8 @@ public class UserApi {
String[] authNames = new String[] { };
apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
@ -278,9 +244,8 @@ public class UserApi {
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
public User getUserByName (String username) throws ApiException {
public User getUserByName(String username) throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// verify the required parameter 'username' is set
if (username == null) {
@ -315,15 +280,9 @@ public class UserApi {
String[] authNames = new String[] { };
GenericType<User> returnType = new GenericType<User>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
TypeRef returnType = new TypeRef<User>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
@ -333,9 +292,8 @@ public class UserApi {
* @param body Updated user object
* @return void
*/
public void updateUser (String username, User body) throws ApiException {
public void updateUser(String username, User body) throws ApiException {
Object postBody = body;
byte[] postBinaryBody = null;
// verify the required parameter 'username' is set
if (username == null) {
@ -370,14 +328,8 @@ public class UserApi {
String[] authNames = new String[] { };
apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "PUT", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
@ -386,9 +338,8 @@ public class UserApi {
* @param username The name that needs to be deleted
* @return void
*/
public void deleteUser (String username) throws ApiException {
public void deleteUser(String username) throws ApiException {
Object postBody = null;
byte[] postBinaryBody = null;
// verify the required parameter 'username' is set
if (username == null) {
@ -423,14 +374,8 @@ public class UserApi {
String[] authNames = new String[] { };
apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null);
}
}

View File

@ -1,52 +0,0 @@
package io.swagger.client;
import io.swagger.client.model.Order;
import java.lang.Exception;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.TimeZone;
import org.junit.*;
import static org.junit.Assert.*;
public class JSONTest {
JSON json = null;
Order order = null;
@Before
public void setup() {
json = new JSON();
order = new Order();
}
@Test
public void testDefaultDate() throws Exception {
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(dateFormat.parse(dateStr));
String str = json.serialize(order);
TypeRef typeRef = new TypeRef<Order>() { };
Order o = json.deserialize(str, typeRef);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@Test
public void testCustomDate() throws Exception {
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT-2"));
final String dateStr = "2015-11-07T14:11:05-02:00";
order.setShipDate(dateFormat.parse(dateStr));
json.setDateFormat(dateFormat);
String str = json.serialize(order);
TypeRef typeRef = new TypeRef<Order>() { };
Order o = json.deserialize(str, typeRef);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
}

View File

@ -124,7 +124,12 @@
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.22.1</version>
</dependency>
<!-- JSON processing: jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>

View File

@ -6,6 +6,7 @@ import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@ -29,20 +30,18 @@ import java.util.TimeZone;
import java.net.URLEncoder;
import java.io.IOException;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import io.swagger.client.auth.Authentication;
import io.swagger.client.auth.HttpBasicAuth;
import io.swagger.client.auth.ApiKeyAuth;
import io.swagger.client.auth.OAuth;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T16:27:55.818+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00")
public class ApiClient {
private Client client;
private Map<String, Client> hostMap = new HashMap<String, Client>();
@ -411,18 +410,39 @@ public class ApiClient {
* Serialize the given Java object into string entity according the given
* Content-Type (only JSON is supported for now).
*/
public Entity<String> serialize(Object obj, String contentType) throws ApiException {
if (isJsonMime(contentType)) {
return Entity.json(json.serialize(obj));
public Entity<?> serialize(Object obj, Map<String, Object> formParams, String contentType) throws ApiException {
Entity<?> entity = null;
if (contentType.startsWith("multipart/form-data")) {
MultiPart multiPart = new MultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey())
.fileName(file.getName()).size(file.length()).build();
multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
} else {
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build();
multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue())));
}
}
entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE);
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
Form form = new Form();
for (Entry<String, Object> param: formParams.entrySet()) {
form.param(param.getKey(), parameterToString(param.getValue()));
}
entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
} else {
throw new ApiException(400, "can not serialize object into Content-Type: " + contentType);
// We let jersey handle the serialization
entity = Entity.entity(obj, contentType);
}
return entity;
}
/**
* Deserialize response body to Java object according to the Content-Type.
*/
public <T> T deserialize(Response response, TypeRef returnType) throws ApiException {
public <T> T deserialize(Response response, GenericType<T> returnType) throws ApiException {
String contentType = null;
List<Object> contentTypes = response.getHeaders().get("Content-Type");
if (contentTypes != null && !contentTypes.isEmpty())
@ -430,24 +450,7 @@ public class ApiClient {
if (contentType == null)
throw new ApiException(500, "missing Content-Type in response");
String body;
if (response.hasEntity())
body = (String) response.readEntity(String.class);
else
body = "";
if (isJsonMime(contentType)) {
return json.deserialize(body, returnType);
} else if (returnType.getType().equals(String.class)) {
// Expecting string, return the raw response body.
return (T) body;
} else {
throw new ApiException(
500,
"Content type \"" + contentType + "\" is not supported for type: "
+ returnType.getType()
);
}
return response.readEntity(returnType);
}
/**
@ -465,7 +468,7 @@ public class ApiClient {
* @param returnType The return type into which to deserialize the response
* @return The response body in type of string
*/
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException {
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
WebTarget target = client.target(this.basePath).path(path);
@ -496,50 +499,16 @@ public class ApiClient {
}
}
Entity<?> formEntity = null;
if (contentType.startsWith("multipart/form-data")) {
MultiPart multiPart = new MultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey())
.fileName(file.getName()).size(file.length()).build();
multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
} else {
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build();
multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue())));
}
}
formEntity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE);
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
Form form = new Form();
for (Entry<String, Object> param: formParams.entrySet()) {
form.param(param.getKey(), parameterToString(param.getValue()));
}
formEntity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
}
Entity<?> entity = serialize(body, formParams, contentType);
Response response = null;
if ("GET".equals(method)) {
response = invocationBuilder.get();
} else if ("POST".equals(method)) {
if (formEntity != null) {
response = invocationBuilder.post(formEntity);
} else if (body == null) {
response = invocationBuilder.post(null);
} else {
response = invocationBuilder.post(serialize(body, contentType));
}
response = invocationBuilder.post(entity);
} else if ("PUT".equals(method)) {
if (formEntity != null) {
response = invocationBuilder.put(formEntity);
} else if (body == null) {
response = invocationBuilder.put(null);
} else {
response = invocationBuilder.put(serialize(body, contentType));
}
response = invocationBuilder.put(entity);
} else if ("DELETE".equals(method)) {
response = invocationBuilder.delete();
} else {
@ -578,6 +547,8 @@ public class ApiClient {
private void buildClient() {
final ClientConfig clientConfig = new ClientConfig();
clientConfig.register(MultiPartFeature.class);
clientConfig.register(json);
clientConfig.register(org.glassfish.jersey.jackson.JacksonFeature.class);
if (debugging) {
clientConfig.register(LoggingFilter.class);
}

View File

@ -6,10 +6,10 @@ import com.fasterxml.jackson.datatype.joda.*;
import java.text.DateFormat;
import java.io.IOException;
import javax.ws.rs.ext.ContextResolver;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00")
public class JSON {
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00")
public class JSON implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper;
public JSON() {
@ -29,36 +29,8 @@ public class JSON {
mapper.setDateFormat(dateFormat);
}
/**
* Serialize the given Java object into JSON string.
*/
public String serialize(Object obj) throws ApiException {
try {
if (obj != null)
return mapper.writeValueAsString(obj);
else
return null;
} catch (Exception e) {
throw new ApiException(400, e.getMessage());
}
}
/**
* Deserialize the given JSON string to Java object.
*
* @param body The JSON string
* @param returnType The type to deserialize inot
* @return The deserialized Java object
*/
public <T> T deserialize(String body, TypeRef returnType) throws ApiException {
JavaType javaType = mapper.constructType(returnType.getType());
try {
return mapper.readValue(body, javaType);
} catch (IOException e) {
if (returnType.getType().equals(String.class))
return (T) body;
else
throw new ApiException(500, e.getMessage(), null, body);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}

View File

@ -1,26 +0,0 @@
package io.swagger.client;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00")
public class TypeRef<T> {
private final Type type;
public TypeRef() {
this.type = getGenericType(getClass());
}
private static Type getGenericType(Class<?> klass) {
Type superclass = klass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("No type parameter provided");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return parameterized.getActualTypeArguments()[0];
}
public Type getType() {
return type;
}
}

View File

@ -4,14 +4,15 @@ import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.Pair;
import io.swagger.client.TypeRef;
import javax.ws.rs.core.GenericType;
import io.swagger.client.model.Pet;
import java.io.File;
import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00")
public class PetApi {
private ApiClient apiClient;
@ -38,7 +39,7 @@ public class PetApi {
* @param body Pet object that needs to be added to the store
* @return void
*/
public void updatePet (Pet body) throws ApiException {
public void updatePet(Pet body) throws ApiException {
Object postBody = body;
// create path and map variables
@ -78,7 +79,7 @@ public class PetApi {
* @param body Pet object that needs to be added to the store
* @return void
*/
public void addPet (Pet body) throws ApiException {
public void addPet(Pet body) throws ApiException {
Object postBody = body;
// create path and map variables
@ -118,7 +119,7 @@ public class PetApi {
* @param status Status values that need to be considered for filter
* @return List<Pet>
*/
public List<Pet> findPetsByStatus (List<String> status) throws ApiException {
public List<Pet> findPetsByStatus(List<String> status) throws ApiException {
Object postBody = null;
// create path and map variables
@ -150,7 +151,7 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" };
TypeRef returnType = new TypeRef<List<Pet>>() {};
GenericType<List<Pet>> returnType = new GenericType<List<Pet>>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
@ -161,7 +162,7 @@ public class PetApi {
* @param tags Tags to filter by
* @return List<Pet>
*/
public List<Pet> findPetsByTags (List<String> tags) throws ApiException {
public List<Pet> findPetsByTags(List<String> tags) throws ApiException {
Object postBody = null;
// create path and map variables
@ -193,7 +194,7 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" };
TypeRef returnType = new TypeRef<List<Pet>>() {};
GenericType<List<Pet>> returnType = new GenericType<List<Pet>>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
@ -204,7 +205,7 @@ public class PetApi {
* @param petId ID of pet that needs to be fetched
* @return Pet
*/
public Pet getPetById (Long petId) throws ApiException {
public Pet getPetById(Long petId) throws ApiException {
Object postBody = null;
// verify the required parameter 'petId' is set
@ -240,7 +241,7 @@ public class PetApi {
String[] authNames = new String[] { "api_key" };
TypeRef returnType = new TypeRef<Pet>() {};
GenericType<Pet> returnType = new GenericType<Pet>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
@ -253,7 +254,7 @@ public class PetApi {
* @param status Updated status of the pet
* @return void
*/
public void updatePetWithForm (String petId, String name, String status) throws ApiException {
public void updatePetWithForm(String petId, String name, String status) throws ApiException {
Object postBody = null;
// verify the required parameter 'petId' is set
@ -304,7 +305,7 @@ public class PetApi {
* @param apiKey
* @return void
*/
public void deletePet (Long petId, String apiKey) throws ApiException {
public void deletePet(Long petId, String apiKey) throws ApiException {
Object postBody = null;
// verify the required parameter 'petId' is set
@ -354,7 +355,7 @@ public class PetApi {
* @param file file to upload
* @return void
*/
public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException {
public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException {
Object postBody = null;
// verify the required parameter 'petId' is set

View File

@ -4,14 +4,15 @@ import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.Pair;
import io.swagger.client.TypeRef;
import javax.ws.rs.core.GenericType;
import java.util.Map;
import io.swagger.client.model.Order;
import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00")
public class StoreApi {
private ApiClient apiClient;
@ -37,7 +38,7 @@ public class StoreApi {
* Returns a map of status codes to quantities
* @return Map<String, Integer>
*/
public Map<String, Integer> getInventory () throws ApiException {
public Map<String, Integer> getInventory() throws ApiException {
Object postBody = null;
// create path and map variables
@ -67,7 +68,7 @@ public class StoreApi {
String[] authNames = new String[] { "api_key" };
TypeRef returnType = new TypeRef<Map<String, Integer>>() {};
GenericType<Map<String, Integer>> returnType = new GenericType<Map<String, Integer>>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
@ -78,7 +79,7 @@ public class StoreApi {
* @param body order placed for purchasing the pet
* @return Order
*/
public Order placeOrder (Order body) throws ApiException {
public Order placeOrder(Order body) throws ApiException {
Object postBody = body;
// create path and map variables
@ -108,7 +109,7 @@ public class StoreApi {
String[] authNames = new String[] { };
TypeRef returnType = new TypeRef<Order>() {};
GenericType<Order> returnType = new GenericType<Order>() {};
return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
@ -119,7 +120,7 @@ public class StoreApi {
* @param orderId ID of pet that needs to be fetched
* @return Order
*/
public Order getOrderById (String orderId) throws ApiException {
public Order getOrderById(String orderId) throws ApiException {
Object postBody = null;
// verify the required parameter 'orderId' is set
@ -155,7 +156,7 @@ public class StoreApi {
String[] authNames = new String[] { };
TypeRef returnType = new TypeRef<Order>() {};
GenericType<Order> returnType = new GenericType<Order>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
@ -166,7 +167,7 @@ public class StoreApi {
* @param orderId ID of the order that needs to be deleted
* @return void
*/
public void deleteOrder (String orderId) throws ApiException {
public void deleteOrder(String orderId) throws ApiException {
Object postBody = null;
// verify the required parameter 'orderId' is set

View File

@ -4,14 +4,15 @@ import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.Pair;
import io.swagger.client.TypeRef;
import javax.ws.rs.core.GenericType;
import io.swagger.client.model.User;
import java.util.*;
import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-11-29T00:18:01.946+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-12-09T12:31:44.572-05:00")
public class UserApi {
private ApiClient apiClient;
@ -38,7 +39,7 @@ public class UserApi {
* @param body Created user object
* @return void
*/
public void createUser (User body) throws ApiException {
public void createUser(User body) throws ApiException {
Object postBody = body;
// create path and map variables
@ -78,7 +79,7 @@ public class UserApi {
* @param body List of user object
* @return void
*/
public void createUsersWithArrayInput (List<User> body) throws ApiException {
public void createUsersWithArrayInput(List<User> body) throws ApiException {
Object postBody = body;
// create path and map variables
@ -118,7 +119,7 @@ public class UserApi {
* @param body List of user object
* @return void
*/
public void createUsersWithListInput (List<User> body) throws ApiException {
public void createUsersWithListInput(List<User> body) throws ApiException {
Object postBody = body;
// create path and map variables
@ -159,7 +160,7 @@ public class UserApi {
* @param password The password for login in clear text
* @return String
*/
public String loginUser (String username, String password) throws ApiException {
public String loginUser(String username, String password) throws ApiException {
Object postBody = null;
// create path and map variables
@ -193,7 +194,7 @@ public class UserApi {
String[] authNames = new String[] { };
TypeRef returnType = new TypeRef<String>() {};
GenericType<String> returnType = new GenericType<String>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
@ -203,7 +204,7 @@ public class UserApi {
*
* @return void
*/
public void logoutUser () throws ApiException {
public void logoutUser() throws ApiException {
Object postBody = null;
// create path and map variables
@ -243,7 +244,7 @@ public class UserApi {
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
public User getUserByName (String username) throws ApiException {
public User getUserByName(String username) throws ApiException {
Object postBody = null;
// verify the required parameter 'username' is set
@ -279,7 +280,7 @@ public class UserApi {
String[] authNames = new String[] { };
TypeRef returnType = new TypeRef<User>() {};
GenericType<User> returnType = new GenericType<User>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
@ -291,7 +292,7 @@ public class UserApi {
* @param body Updated user object
* @return void
*/
public void updateUser (String username, User body) throws ApiException {
public void updateUser(String username, User body) throws ApiException {
Object postBody = body;
// verify the required parameter 'username' is set
@ -337,7 +338,7 @@ public class UserApi {
* @param username The name that needs to be deleted
* @return void
*/
public void deleteUser (String username) throws ApiException {
public void deleteUser(String username) throws ApiException {
Object postBody = null;
// verify the required parameter 'username' is set

View File

@ -4,9 +4,7 @@ import io.swagger.client.model.Order;
import java.lang.Exception;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.TimeZone;
import org.junit.*;
@ -30,9 +28,8 @@ public class JSONTest {
final String dateStr = "2015-11-07T14:11:05.267Z";
order.setShipDate(dateFormat.parse(dateStr));
String str = json.serialize(order);
TypeRef typeRef = new TypeRef<Order>() { };
Order o = json.deserialize(str, typeRef);
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
@ -44,9 +41,8 @@ public class JSONTest {
order.setShipDate(dateFormat.parse(dateStr));
json.setDateFormat(dateFormat);
String str = json.serialize(order);
TypeRef typeRef = new TypeRef<Order>() { };
Order o = json.deserialize(str, typeRef);
String str = json.getContext(null).writeValueAsString(order);
Order o = json.getContext(null).readValue(str, Order.class);
assertEquals(dateStr, dateFormat.format(o.getShipDate()));
}
}