Skip to content

[Java okhttp-gson] Support "binary" (byte array) for body parameter and response #1898

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 21, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 38 additions & 21 deletions modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

if (body != null && !formParams.isEmpty()){
throw new ApiException(500, "Cannot have body and form params");
/**
* 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 (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));
}
}
}

updateParamsForAuth(authNames, queryParams, headerParams);
return url.toString();
}

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

String querystring = b.substring(0, b.length() - 1);
updateParamsForAuth(authNames, queryParams, headerParams);

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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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) {
Expand All @@ -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");
}
Expand Down Expand Up @@ -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;
Expand All @@ -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();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
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";
Expand Down Expand Up @@ -451,34 +451,51 @@ public Object serialize(Object obj, String contentType, Map<String, Object> form
}
}

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");
/**
* 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 (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));
}
}
}

updateParamsForAuth(authNames, queryParams, headerParams);
return url.toString();
}

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

String querystring = b.substring(0, b.length() - 1);
updateParamsForAuth(authNames, queryParams, headerParams);

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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,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 PetApi {
private ApiClient apiClient;

Expand Down Expand Up @@ -395,6 +395,93 @@ public void uploadFile(Long petId, String additionalMetadata, File file) throws
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);

}
Expand Down
Loading