Merge branch 'master' into java-imports

Conflicts:
	modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java
This commit is contained in:
xhh
2016-01-29 11:16:14 +08:00
356 changed files with 11850 additions and 3863 deletions

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

@@ -895,4 +895,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

@@ -0,0 +1,17 @@
package io.swagger;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
public class TestUtils {
private static final AtomicLong atomicId = createAtomicId();
public static long nextId() {
return atomicId.getAndIncrement();
}
private static AtomicLong createAtomicId() {
int baseId = new Random(System.currentTimeMillis()).nextInt(1000000) + 20000;
return new AtomicLong((long) baseId);
}
}

View File

@@ -1,5 +1,9 @@
package io.swagger.petstore.test;
import com.google.gson.reflect.TypeToken;
import io.swagger.TestUtils;
import io.swagger.client.*;
import io.swagger.client.api.*;
import io.swagger.client.auth.*;
@@ -8,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;
@@ -67,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();
@@ -312,7 +334,7 @@ public class PetApiTest {
private Pet createRandomPet() {
Pet pet = new Pet();
pet.setId(System.currentTimeMillis());
pet.setId(TestUtils.nextId());
pet.setName("gorilla");
Category category = new Category();
@@ -325,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);
}
}

View File

@@ -1,5 +1,6 @@
package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.ApiException;
import io.swagger.client.*;
@@ -67,7 +68,7 @@ public class StoreApiTest {
private Order createOrder() {
Order order = new Order();
order.setId(new Long(System.currentTimeMillis()));
order.setId(TestUtils.nextId());
order.setPetId(new Long(200));
order.setQuantity(new Integer(13));
order.setShipDate(new java.util.Date());

View File

@@ -1,5 +1,7 @@
package io.swagger.petstore.test;
import io.swagger.TestUtils;
import io.swagger.client.api.*;
import io.swagger.client.auth.*;
import io.swagger.client.model.*;
@@ -33,9 +35,9 @@ public class UserApiTest {
@Test
public void testCreateUsersWithArray() throws Exception {
User user1 = createUser();
user1.setUsername("abc123");
user1.setUsername("user" + user1.getId());
User user2 = createUser();
user2.setUsername("123abc");
user2.setUsername("user" + user2.getId());
api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2}));
@@ -46,9 +48,9 @@ public class UserApiTest {
@Test
public void testCreateUsersWithList() throws Exception {
User user1 = createUser();
user1.setUsername("abc123");
user1.setUsername("user" + user1.getId());
User user2 = createUser();
user2.setUsername("123abc");
user2.setUsername("user" + user2.getId());
api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2}));
@@ -72,7 +74,7 @@ public class UserApiTest {
private User createUser() {
User user = new User();
user.setId(System.currentTimeMillis());
user.setId(TestUtils.nextId());
user.setUsername("fred" + user.getId());
user.setFirstName("Fred");
user.setLastName("Meyer");