From a3024a3553f773da1fe4ebf725ce37046c43313f Mon Sep 17 00:00:00 2001 From: evigeant Date: Wed, 9 Dec 2015 12:37:12 -0500 Subject: [PATCH] Updated PetStore sample for java client jersey2 --- samples/client/petstore/java/jersey2/pom.xml | 7 +- .../java/io/swagger/client/ApiClient.java | 99 +++++++------------ .../src/main/java/io/swagger/client/JSON.java | 40 ++------ .../main/java/io/swagger/client/TypeRef.java | 26 ----- .../java/io/swagger/client/api/PetApi.java | 27 ++--- .../java/io/swagger/client/api/StoreApi.java | 19 ++-- .../java/io/swagger/client/api/UserApi.java | 25 ++--- .../test/java/io/swagger/client/JSONTest.java | 12 +-- 8 files changed, 88 insertions(+), 167 deletions(-) delete mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index 0881cc29374..6b0ba2cba08 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -124,7 +124,12 @@ jersey-media-multipart ${jersey-version} - + + org.glassfish.jersey.media + jersey-media-json-jackson + 2.22.1 + + com.fasterxml.jackson.core diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index c5c74cc11e4..4ca24fbabb0 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -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 hostMap = new HashMap(); @@ -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 serialize(Object obj, String contentType) throws ApiException { - if (isJsonMime(contentType)) { - return Entity.json(json.serialize(obj)); + public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { + Entity entity = null; + if (contentType.startsWith("multipart/form-data")) { + MultiPart multiPart = new MultiPart(); + for (Entry 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 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 deserialize(Response response, TypeRef returnType) throws ApiException { + public T deserialize(Response response, GenericType returnType) throws ApiException { String contentType = null; List 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 invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType 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 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 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); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java index 9116d366308..aab2d27e463 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -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 { 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 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; } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java deleted file mode 100644 index 9c97f34cd79..00000000000 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java +++ /dev/null @@ -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 { - 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; - } -} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index a645de12c71..ab33fca7c79 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -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 */ - public List findPetsByStatus (List status) throws ApiException { + public List findPetsByStatus(List 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>() {}; + GenericType> returnType = new GenericType>() {}; 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 */ - public List findPetsByTags (List tags) throws ApiException { + public List findPetsByTags(List 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>() {}; + GenericType> returnType = new GenericType>() {}; 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() {}; + GenericType returnType = new GenericType() {}; 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 diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java index 7253d1909b6..5dfdbcc3e62 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -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 */ - public Map getInventory () throws ApiException { + public Map 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>() {}; + GenericType> returnType = new GenericType>() {}; 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() {}; + GenericType returnType = new GenericType() {}; 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() {}; + GenericType returnType = new GenericType() {}; 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 diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java index d6115d939fc..0424382e7c3 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -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 body) throws ApiException { + public void createUsersWithArrayInput(List 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 body) throws ApiException { + public void createUsersWithListInput(List 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() {}; + GenericType returnType = new GenericType() {}; 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() {}; + GenericType returnType = new GenericType() {}; 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 diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java index 1250a135078..f10909ab9e7 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/JSONTest.java @@ -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 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 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())); } } \ No newline at end of file