Merge pull request #1898 from xhh/java-binary-support

[Java okhttp-gson] Support "binary" (byte array) for body parameter and response
This commit is contained in:
wing328 2016-01-22 00:03:14 +08:00
commit 53abd8a8fb
22 changed files with 751 additions and 147 deletions

View File

@ -452,34 +452,51 @@ public class ApiClient {
}
}
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 {
/**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param path The sub path
* @param queryParams The query parameters
* @return The full URL
*/
private String buildUrl(String path, List<Pair> queryParams) {
final StringBuilder url = new StringBuilder();
url.append(basePath).append(path);
if (body != null && !formParams.isEmpty()){
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return url.toString();
}
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 {
if (body != null && !formParams.isEmpty()) {
throw new ApiException(500, "Cannot have body and form params");
}
updateParamsForAuth(authNames, queryParams, headerParams);
StringBuilder b = new StringBuilder();
b.append("?");
if (queryParams != null){
for (Pair queryParam : queryParams){
if (!queryParam.getName().isEmpty()) {
b.append(escapeString(queryParam.getName()));
b.append("=");
b.append(escapeString(queryParam.getValue()));
b.append("&");
}
}
}
String querystring = b.substring(0, b.length() - 1);
final String url = buildUrl(path, queryParams);
Builder builder;
if (accept == null)
builder = httpClient.resource(basePath + path + querystring).getRequestBuilder();
else
builder = httpClient.resource(basePath + path + querystring).accept(accept);
if (accept == null) {
builder = httpClient.resource(url).getRequestBuilder();
} else {
builder = httpClient.resource(url).accept(accept);
}
for (String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key));

View File

@ -495,7 +495,9 @@ public class ApiClient {
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 = httpClient.target(this.basePath).path(path);
// Not using `.target(this.basePath).path(path)` below,
// to support (constant) query string in `path`, e.g. "/posts?draft=1"
WebTarget target = httpClient.target(this.basePath + path);
if (queryParams != null) {
for (Pair queryParam : queryParams) {

View File

@ -657,8 +657,8 @@ public class ApiClient {
}
/**
* Deserialize response body to Java object, according to the Content-Type
* response header.
* Deserialize response body to Java object, according to the return type and
* the Content-Type response header.
*
* @param response HTTP response
* @param returnType The type of the Java object
@ -667,12 +667,21 @@ public class ApiClient {
* or the Content-Type of the response is not supported.
*/
public <T> T deserialize(Response response, Type returnType) throws ApiException {
if (response == null || returnType == null)
if (response == null || returnType == null) {
return null;
}
// Handle file downloading.
if (returnType.equals(File.class))
if ("byte[]".equals(returnType.toString())) {
// Handle binary response (byte array).
try {
return (T) response.body().bytes();
} catch (IOException e) {
throw new ApiException(e);
}
} else if (returnType.equals(File.class)) {
// Handle file downloading.
return (T) downloadFileFromResponse(response);
}
String respBody;
try {
@ -684,8 +693,9 @@ public class ApiClient {
throw new ApiException(e);
}
if (respBody == null || "".equals(respBody))
if (respBody == null || "".equals(respBody)) {
return null;
}
String contentType = response.headers().get("Content-Type");
if (contentType == null) {
@ -707,20 +717,29 @@ public class ApiClient {
}
/**
* Serialize the given Java object into request body string, according to the
* request Content-Type.
* Serialize the given Java object into request body according to the object's
* class and the request Content-Type.
*
* @param obj The Java object
* @param contentType The request Content-Type
* @return The serialized string
* @return The serialized request body
* @throws ApiException If fail to serialize the given object
*/
public String serialize(Object obj, String contentType) throws ApiException {
if (isJsonMime(contentType)) {
if (obj != null)
return json.serialize(obj);
else
return null;
public RequestBody serialize(Object obj, String contentType) throws ApiException {
if (obj instanceof byte[]) {
// Binary (byte array) body parameter support.
return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
} else if (obj instanceof File) {
// File body parameter support.
return RequestBody.create(MediaType.parse(contentType), (File) obj);
} else if (isJsonMime(contentType)) {
String content;
if (obj != null) {
content = json.serialize(obj);
} else {
content = null;
}
return RequestBody.create(MediaType.parse(contentType), content);
} else {
throw new ApiException("Content type \"" + contentType + "\" is not supported");
}
@ -909,7 +928,7 @@ public class ApiClient {
reqBody = RequestBody.create(MediaType.parse(contentType), "");
}
} else {
reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType));
reqBody = serialize(body, contentType);
}
Request request = null;
@ -932,20 +951,27 @@ public class ApiClient {
* @return The full URL
*/
public String buildUrl(String path, List<Pair> queryParams) {
StringBuilder query = new StringBuilder();
if (queryParams != null) {
final StringBuilder url = new StringBuilder();
url.append(basePath).append(path);
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (query.toString().length() == 0)
query.append("?");
else
query.append("&");
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
query.append(escapeString(param.getName())).append("=").append(escapeString(value));
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return basePath + path + query.toString();
return url.toString();
}
/**

View File

@ -41,7 +41,7 @@ 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 = "2016-01-08T18:50:38.131+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class ApiClient {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private String basePath = "http://petstore.swagger.io/v2";
@ -451,34 +451,51 @@ public class ApiClient {
}
}
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 {
/**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param path The sub path
* @param queryParams The query parameters
* @return The full URL
*/
private String buildUrl(String path, List<Pair> queryParams) {
final StringBuilder url = new StringBuilder();
url.append(basePath).append(path);
if (body != null && !formParams.isEmpty()){
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return url.toString();
}
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 {
if (body != null && !formParams.isEmpty()) {
throw new ApiException(500, "Cannot have body and form params");
}
updateParamsForAuth(authNames, queryParams, headerParams);
StringBuilder b = new StringBuilder();
b.append("?");
if (queryParams != null){
for (Pair queryParam : queryParams){
if (!queryParam.getName().isEmpty()) {
b.append(escapeString(queryParam.getName()));
b.append("=");
b.append(escapeString(queryParam.getValue()));
b.append("&");
}
}
}
String querystring = b.substring(0, b.length() - 1);
final String url = buildUrl(path, queryParams);
Builder builder;
if (accept == null)
builder = httpClient.resource(basePath + path + querystring).getRequestBuilder();
else
builder = httpClient.resource(basePath + path + querystring).accept(accept);
if (accept == null) {
builder = httpClient.resource(url).getRequestBuilder();
} else {
builder = httpClient.resource(url).accept(accept);
}
for (String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key));

View File

@ -12,7 +12,7 @@ import java.io.File;
import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class PetApi {
private ApiClient apiClient;
@ -395,6 +395,93 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return byte[]
*/
public byte[] getPetByIdWithByteArray(Long petId) throws ApiException {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetByIdWithByteArray");
}
// create path and map variables
String path = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "api_key" };
GenericType<byte[]> returnType = new GenericType<byte[]>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param body Pet object in the form of byte array
* @return void
*/
public void addPetUsingByteArray(byte[] body) throws ApiException {
Object postBody = body;
// create path and map variables
String path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json", "application/xml"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
}

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class Category {
private Long id = null;
@ -45,7 +45,7 @@ public class Category {
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -53,8 +53,10 @@ public class Category {
return false;
}
Category category = (Category) o;
return Objects.equals(id, category.id) &&
Objects.equals(name, category.name);
return true && Objects.equals(id, category.id) &&
Objects.equals(name, category.name)
;
}
@Override
@ -77,7 +79,7 @@ public class Category {
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -11,7 +11,7 @@ import java.util.Date;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class Order {
private Long id = null;
@ -123,7 +123,7 @@ public class Order {
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -131,12 +131,14 @@ public class Order {
return false;
}
Order order = (Order) o;
return Objects.equals(id, order.id) &&
return true && Objects.equals(id, order.id) &&
Objects.equals(petId, order.petId) &&
Objects.equals(quantity, order.quantity) &&
Objects.equals(shipDate, order.shipDate) &&
Objects.equals(status, order.status) &&
Objects.equals(complete, order.complete);
Objects.equals(complete, order.complete)
;
}
@Override
@ -163,7 +165,7 @@ public class Order {
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -13,7 +13,7 @@ import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class Pet {
private Long id = null;
@ -125,7 +125,7 @@ public class Pet {
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -133,12 +133,14 @@ public class Pet {
return false;
}
Pet pet = (Pet) o;
return Objects.equals(id, pet.id) &&
return true && Objects.equals(id, pet.id) &&
Objects.equals(category, pet.category) &&
Objects.equals(name, pet.name) &&
Objects.equals(photoUrls, pet.photoUrls) &&
Objects.equals(tags, pet.tags) &&
Objects.equals(status, pet.status);
Objects.equals(status, pet.status)
;
}
@Override
@ -165,7 +167,7 @@ public class Pet {
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class Tag {
private Long id = null;
@ -45,7 +45,7 @@ public class Tag {
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -53,8 +53,10 @@ public class Tag {
return false;
}
Tag tag = (Tag) o;
return Objects.equals(id, tag.id) &&
Objects.equals(name, tag.name);
return true && Objects.equals(id, tag.id) &&
Objects.equals(name, tag.name)
;
}
@Override
@ -77,7 +79,7 @@ public class Tag {
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:19:23.415+08:00")
public class User {
private Long id = null;
@ -130,7 +130,7 @@ public class User {
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -138,14 +138,16 @@ public class User {
return false;
}
User user = (User) o;
return Objects.equals(id, user.id) &&
return true && Objects.equals(id, user.id) &&
Objects.equals(username, user.username) &&
Objects.equals(firstName, user.firstName) &&
Objects.equals(lastName, user.lastName) &&
Objects.equals(email, user.email) &&
Objects.equals(password, user.password) &&
Objects.equals(phone, user.phone) &&
Objects.equals(userStatus, user.userStatus);
Objects.equals(userStatus, user.userStatus)
;
}
@Override
@ -174,7 +176,7 @@ public class User {
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -1,5 +1,9 @@
package io.swagger.petstore.test;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.joda.*;
import io.swagger.TestUtils;
import io.swagger.client.*;
@ -18,7 +22,8 @@ import org.junit.*;
import static org.junit.Assert.*;
public class PetApiTest {
PetApi api = null;
private PetApi api;
private ObjectMapper mapper;
@Before
public void setup() {
@ -67,6 +72,20 @@ public class PetApiTest {
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testCreateAndGetPetWithByteArray() throws Exception {
Pet pet = createRandomPet();
byte[] bytes = serializeJson(pet).getBytes();
api.addPetUsingByteArray(bytes);
byte[] fetchedBytes = api.getPetByIdWithByteArray(pet.getId());
Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class);
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testUpdatePet() throws Exception {
Pet pet = createRandomPet();
@ -215,4 +234,37 @@ public class PetApiTest {
return pet;
}
private String serializeJson(Object o) {
if (mapper == null) {
mapper = createObjectMapper();
}
try {
return mapper.writeValueAsString(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private <T> T deserializeJson(String json, Class<T> klass) {
if (mapper == null) {
mapper = createObjectMapper();
}
try {
return mapper.readValue(json, klass);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private ObjectMapper createObjectMapper() {
ObjectMapper 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());
return mapper;
}
}

View File

@ -43,7 +43,7 @@ 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 = "2016-01-08T18:51:26.068+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class ApiClient {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private String basePath = "http://petstore.swagger.io/v2";
@ -494,7 +494,9 @@ public class ApiClient {
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 = httpClient.target(this.basePath).path(path);
// Not using `.target(this.basePath).path(path)` below,
// to support (constant) query string in `path`, e.g. "/posts?draft=1"
WebTarget target = httpClient.target(this.basePath + path);
if (queryParams != null) {
for (Pair queryParam : queryParams) {

View File

@ -12,7 +12,7 @@ import java.io.File;
import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class PetApi {
private ApiClient apiClient;
@ -395,6 +395,93 @@ public class PetApi {
String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
}
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return byte[]
*/
public byte[] getPetByIdWithByteArray(Long petId) throws ApiException {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetByIdWithByteArray");
}
// create path and map variables
String path = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
// query params
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "api_key" };
GenericType<byte[]> returnType = new GenericType<byte[]>() {};
return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param body Pet object in the form of byte array
* @return void
*/
public void addPetUsingByteArray(byte[] body) throws ApiException {
Object postBody = body;
// create path and map variables
String path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json");
// query params
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json", "application/xml"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null);
}

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class Category {
private Long id = null;
@ -45,7 +45,7 @@ public class Category {
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -53,8 +53,10 @@ public class Category {
return false;
}
Category category = (Category) o;
return Objects.equals(id, category.id) &&
Objects.equals(name, category.name);
return true && Objects.equals(id, category.id) &&
Objects.equals(name, category.name)
;
}
@Override
@ -77,7 +79,7 @@ public class Category {
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -11,7 +11,7 @@ import java.util.Date;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class Order {
private Long id = null;
@ -123,7 +123,7 @@ public class Order {
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -131,12 +131,14 @@ public class Order {
return false;
}
Order order = (Order) o;
return Objects.equals(id, order.id) &&
return true && Objects.equals(id, order.id) &&
Objects.equals(petId, order.petId) &&
Objects.equals(quantity, order.quantity) &&
Objects.equals(shipDate, order.shipDate) &&
Objects.equals(status, order.status) &&
Objects.equals(complete, order.complete);
Objects.equals(complete, order.complete)
;
}
@Override
@ -163,7 +165,7 @@ public class Order {
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -13,7 +13,7 @@ import java.util.*;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class Pet {
private Long id = null;
@ -125,7 +125,7 @@ public class Pet {
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -133,12 +133,14 @@ public class Pet {
return false;
}
Pet pet = (Pet) o;
return Objects.equals(id, pet.id) &&
return true && Objects.equals(id, pet.id) &&
Objects.equals(category, pet.category) &&
Objects.equals(name, pet.name) &&
Objects.equals(photoUrls, pet.photoUrls) &&
Objects.equals(tags, pet.tags) &&
Objects.equals(status, pet.status);
Objects.equals(status, pet.status)
;
}
@Override
@ -165,7 +167,7 @@ public class Pet {
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class Tag {
private Long id = null;
@ -45,7 +45,7 @@ public class Tag {
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -53,8 +53,10 @@ public class Tag {
return false;
}
Tag tag = (Tag) o;
return Objects.equals(id, tag.id) &&
Objects.equals(name, tag.name);
return true && Objects.equals(id, tag.id) &&
Objects.equals(name, tag.name)
;
}
@Override
@ -77,7 +79,7 @@ public class Tag {
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00")
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-15T19:00:52.199+08:00")
public class User {
private Long id = null;
@ -130,7 +130,7 @@ public class User {
@Override
public boolean equals(Object o) {
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
@ -138,14 +138,16 @@ public class User {
return false;
}
User user = (User) o;
return Objects.equals(id, user.id) &&
return true && Objects.equals(id, user.id) &&
Objects.equals(username, user.username) &&
Objects.equals(firstName, user.firstName) &&
Objects.equals(lastName, user.lastName) &&
Objects.equals(email, user.email) &&
Objects.equals(password, user.password) &&
Objects.equals(phone, user.phone) &&
Objects.equals(userStatus, user.userStatus);
Objects.equals(userStatus, user.userStatus)
;
}
@Override
@ -174,7 +176,7 @@ public class User {
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.TestUtils;
import io.swagger.client.*;
@ -67,6 +69,20 @@ public class PetApiTest {
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testCreateAndGetPetWithByteArray() throws Exception {
Pet pet = createRandomPet();
byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes();
api.addPetUsingByteArray(bytes);
byte[] fetchedBytes = api.getPetByIdWithByteArray(pet.getId());
Pet fetched = deserializeJson(new String(fetchedBytes), Pet.class, api.getApiClient());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testUpdatePet() throws Exception {
Pet pet = createRandomPet();
@ -215,4 +231,22 @@ public class PetApiTest {
return pet;
}
private String serializeJson(Object o, ApiClient apiClient) {
ObjectMapper mapper = apiClient.getJSON().getContext(null);
try {
return mapper.writeValueAsString(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private <T> T deserializeJson(String json, Class<T> klass, ApiClient apiClient) {
ObjectMapper mapper = apiClient.getJSON().getContext(null);
try {
return mapper.readValue(json, klass);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@ -656,8 +656,8 @@ public class ApiClient {
}
/**
* Deserialize response body to Java object, according to the Content-Type
* response header.
* Deserialize response body to Java object, according to the return type and
* the Content-Type response header.
*
* @param response HTTP response
* @param returnType The type of the Java object
@ -666,12 +666,21 @@ public class ApiClient {
* or the Content-Type of the response is not supported.
*/
public <T> T deserialize(Response response, Type returnType) throws ApiException {
if (response == null || returnType == null)
if (response == null || returnType == null) {
return null;
}
// Handle file downloading.
if (returnType.equals(File.class))
if ("byte[]".equals(returnType.toString())) {
// Handle binary response (byte array).
try {
return (T) response.body().bytes();
} catch (IOException e) {
throw new ApiException(e);
}
} else if (returnType.equals(File.class)) {
// Handle file downloading.
return (T) downloadFileFromResponse(response);
}
String respBody;
try {
@ -683,8 +692,9 @@ public class ApiClient {
throw new ApiException(e);
}
if (respBody == null || "".equals(respBody))
if (respBody == null || "".equals(respBody)) {
return null;
}
String contentType = response.headers().get("Content-Type");
if (contentType == null) {
@ -706,20 +716,29 @@ public class ApiClient {
}
/**
* Serialize the given Java object into request body string, according to the
* request Content-Type.
* Serialize the given Java object into request body according to the object's
* class and the request Content-Type.
*
* @param obj The Java object
* @param contentType The request Content-Type
* @return The serialized string
* @return The serialized request body
* @throws ApiException If fail to serialize the given object
*/
public String serialize(Object obj, String contentType) throws ApiException {
if (isJsonMime(contentType)) {
if (obj != null)
return json.serialize(obj);
else
return null;
public RequestBody serialize(Object obj, String contentType) throws ApiException {
if (obj instanceof byte[]) {
// Binary (byte array) body parameter support.
return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
} else if (obj instanceof File) {
// File body parameter support.
return RequestBody.create(MediaType.parse(contentType), (File) obj);
} else if (isJsonMime(contentType)) {
String content;
if (obj != null) {
content = json.serialize(obj);
} else {
content = null;
}
return RequestBody.create(MediaType.parse(contentType), content);
} else {
throw new ApiException("Content type \"" + contentType + "\" is not supported");
}
@ -908,7 +927,7 @@ public class ApiClient {
reqBody = RequestBody.create(MediaType.parse(contentType), "");
}
} else {
reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType));
reqBody = serialize(body, contentType);
}
Request request = null;
@ -931,20 +950,27 @@ public class ApiClient {
* @return The full URL
*/
public String buildUrl(String path, List<Pair> queryParams) {
StringBuilder query = new StringBuilder();
if (queryParams != null) {
final StringBuilder url = new StringBuilder();
url.append(basePath).append(path);
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (query.toString().length() == 0)
query.append("?");
else
query.append("&");
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
query.append(escapeString(param.getName())).append("=").append(escapeString(value));
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return basePath + path + query.toString();
return url.toString();
}
/**

View File

@ -892,4 +892,210 @@ public class PetApi {
return call;
}
/* Build call for getPetByIdWithByteArray */
private Call getPetByIdWithByteArrayCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw new ApiException("Missing the required parameter 'petId' when calling getPetByIdWithByteArray(Async)");
}
// create path and map variables
String path = "/pet/{petId}?testing_byte_array=true".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
if (accept != null) headerParams.put("Accept", accept);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
headerParams.put("Content-Type", contentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] authNames = new String[] { "api_key" };
return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener);
}
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return byte[]
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public byte[] getPetByIdWithByteArray(Long petId) throws ApiException {
ApiResponse<byte[]> resp = getPetByIdWithByteArrayWithHttpInfo(petId);
return resp.getData();
}
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @return ApiResponse<byte[]>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<byte[]> getPetByIdWithByteArrayWithHttpInfo(Long petId) throws ApiException {
Call call = getPetByIdWithByteArrayCall(petId, null, null);
Type returnType = new TypeToken<byte[]>(){}.getType();
return apiClient.execute(call, returnType);
}
/**
* Fake endpoint to test byte array return by &#39;Find pet by ID&#39; (asynchronously)
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public Call getPetByIdWithByteArrayAsync(Long petId, final ApiCallback<byte[]> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
Call call = getPetByIdWithByteArrayCall(petId, progressListener, progressRequestListener);
Type returnType = new TypeToken<byte[]>(){}.getType();
apiClient.executeAsync(call, returnType, callback);
return call;
}
/* Build call for addPetUsingByteArray */
private Call addPetUsingByteArrayCall(byte[] body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object postBody = body;
// create path and map variables
String path = "/pet?testing_byte_array=true".replaceAll("\\{format\\}","json");
List<Pair> queryParams = new ArrayList<Pair>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, Object> formParams = new HashMap<String, Object>();
final String[] accepts = {
"application/json", "application/xml"
};
final String accept = apiClient.selectHeaderAccept(accepts);
if (accept != null) headerParams.put("Accept", accept);
final String[] contentTypes = {
"application/json", "application/xml"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
headerParams.put("Content-Type", contentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] authNames = new String[] { "petstore_auth" };
return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames, progressRequestListener);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param body Pet object in the form of byte array
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void addPetUsingByteArray(byte[] body) throws ApiException {
addPetUsingByteArrayWithHttpInfo(body);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store
*
* @param body Pet object in the form of byte array
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> addPetUsingByteArrayWithHttpInfo(byte[] body) throws ApiException {
Call call = addPetUsingByteArrayCall(body, null, null);
return apiClient.execute(call);
}
/**
* Fake endpoint to test byte array in body parameter for adding a new pet to the store (asynchronously)
*
* @param body Pet object in the form of byte array
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public Call addPetUsingByteArrayAsync(byte[] body, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
Call call = addPetUsingByteArrayCall(body, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
}

View File

@ -1,5 +1,7 @@
package io.swagger.petstore.test;
import com.google.gson.reflect.TypeToken;
import io.swagger.TestUtils;
import io.swagger.client.*;
@ -10,6 +12,7 @@ import io.swagger.client.model.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@ -69,6 +72,23 @@ public class PetApiTest {
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testCreateAndGetPetWithByteArray() throws Exception {
Pet pet = createRandomPet();
System.out.println(serializeJson(pet, api.getApiClient()));
byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes();
api.addPetUsingByteArray(bytes);
byte[] fetchedBytes = api.getPetByIdWithByteArray(pet.getId());
System.out.println(new String(fetchedBytes));
Type type = new TypeToken<Pet>(){}.getType();
Pet fetched = deserializeJson(new String(fetchedBytes), type, api.getApiClient());
assertNotNull(fetched);
assertEquals(pet.getId(), fetched.getId());
assertNotNull(fetched.getCategory());
assertEquals(fetched.getCategory().getName(), pet.getCategory().getName());
}
@Test
public void testCreateAndGetPetWithHttpInfo() throws Exception {
Pet pet = createRandomPet();
@ -327,4 +347,12 @@ public class PetApiTest {
return pet;
}
private String serializeJson(Object o, ApiClient apiClient) {
return apiClient.getJSON().serialize(o);
}
private <T> T deserializeJson(String json, Type type, ApiClient apiClient) {
return (T) apiClient.getJSON().deserialize(json, type);
}
}