Skip to content

Develop 2.0 - support binary input and output #1065

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

Closed
wants to merge 1 commit into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

public class CodegenParameter {
public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam;
isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam, isBinary;
public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue;
public String jsonSchema;
public boolean isEnum;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public class CodegenResponse {
public Boolean primitiveType;
public Boolean isMapContainer;
public Boolean isListContainer;
public Boolean isBinary;
public Object schema;
public String jsonSchema;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import io.swagger.models.properties.AbstractNumericProperty;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.ByteArrayProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DecimalProperty;
Expand Down Expand Up @@ -308,6 +309,8 @@ public DefaultCodegen() {
typeMapping.put("double", "Double");
typeMapping.put("object", "Object");
typeMapping.put("integer", "Integer");
typeMapping.put("ByteArray", "byte[]");


instantiationTypes = new HashMap<String, String>();

Expand Down Expand Up @@ -444,6 +447,8 @@ public String getSwaggerType(Property p) {
String datatype = null;
if (p instanceof StringProperty) {
datatype = "string";
} else if (p instanceof ByteArrayProperty) {
datatype = "ByteArray";
} else if (p instanceof BooleanProperty) {
datatype = "boolean";
} else if (p instanceof DateProperty) {
Expand Down Expand Up @@ -525,6 +530,7 @@ public CodegenModel fromModel(String name, Model model, Map<String, Model> allDe
m.externalDocs = model.getExternalDocs();
if (model instanceof ArrayModel) {
ArrayModel am = (ArrayModel) model;
m.hasEnums = false; // otherwise causes NullPointerException in JavaClientCodegen.fromModel
ArrayProperty arrayProperty = new ArrayProperty(am.getItems());
addParentContainer(m, name, arrayProperty);
} else if (model instanceof RefModel) {
Expand Down Expand Up @@ -965,6 +971,7 @@ public CodegenResponse fromResponse(String responseCode, Response response) {
}
}
r.dataType = cm.datatype;
r.isBinary = cm.datatype.equals("byte[]");
if (cm.isContainer != null) {
r.simpleType = false;
r.containerType = cm.containerType;
Expand Down Expand Up @@ -1061,12 +1068,17 @@ public CodegenParameter fromParameter(Parameter param, Set<String> imports) {
p.dataType = getTypeDeclaration(cm.classname);
imports.add(p.dataType);
} else {
// TODO: missing format, so this will not always work
Property prop = PropertyBuilder.build(impl.getType(), null, null);
Property prop = PropertyBuilder.build(impl.getType(), impl.getFormat(), null);
prop.setRequired(bp.getRequired());
CodegenProperty cp = fromProperty("property", prop);
if (cp != null) {
p.dataType = cp.datatype;
if (p.dataType.equals("byte[]")) {
p.isBinary = true;
}
else {
p.isBinary = false;
}
}
}
} else if (model instanceof ArrayModel) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ public JavaClientCodegen() {
"Integer",
"Long",
"Float",
"Object")
"Object",
"byte[]")
);
instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap");
Expand Down Expand Up @@ -275,7 +276,7 @@ public String getSwaggerType(Property p) {
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
return type;
}
} else {
type = swaggerType;
Expand Down
110 changes: 92 additions & 18 deletions modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import java.net.URLEncoder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.DataInputStream;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
Expand Down Expand Up @@ -385,21 +386,12 @@ public class ApiClient {
}
}

/**
* Invoke API by sending HTTP request with the given options.
*
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param queryParams The query parameters
* @param body The request body object
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public String invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String accept, String contentType, String[] authNames) throws ApiException {
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, byte[] binaryBody, Map<String, String> headerParams, Map<String, String> formParams, String accept, String contentType, String[] authNames) throws ApiException {

if (body != null && binaryBody != null){
throw new ApiException(500, "either body or binaryBody must be null");
}

updateParamsForAuth(authNames, queryParams, headerParams);

Client client = getClient();
Expand Down Expand Up @@ -446,7 +438,10 @@ public class ApiClient {
response = builder.type(contentType).post(ClientResponse.class,
encodedFormParams);
} else if (body == null) {
response = builder.post(ClientResponse.class, null);
if(binaryBody == null)
response = builder.post(ClientResponse.class, null);
else
response = builder.type(contentType).post(ClientResponse.class, binaryBody);
} else if(body instanceof FormDataMultiPart) {
response = builder.type(contentType).post(ClientResponse.class, body);
}
Expand All @@ -460,7 +455,10 @@ public class ApiClient {
response = builder.type(contentType).put(ClientResponse.class,
encodedFormParams);
} else if(body == null) {
response = builder.put(ClientResponse.class, serialize(body));
if(binaryBody == null)
response = builder.put(ClientResponse.class, null);
else
response = builder.type(contentType).put(ClientResponse.class, binaryBody);
} else {
response = builder.type(contentType).put(ClientResponse.class, serialize(body));
}
Expand All @@ -472,14 +470,38 @@ public class ApiClient {
response = builder.type(contentType).delete(ClientResponse.class,
encodedFormParams);
} else if(body == null) {
response = builder.delete(ClientResponse.class);
if(binaryBody == null)
response = builder.delete(ClientResponse.class);
else
response = builder.type(contentType).delete(ClientResponse.class, binaryBody);
} else {
response = builder.type(contentType).delete(ClientResponse.class, serialize(body));
}
}
else {
throw new ApiException(500, "unknown method type " + method);
}
return response;
}

/**
* Invoke API by sending HTTP request with the given options.
*
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param queryParams The query parameters
* @param body The request body object - if it is not binary, otherwise null
* @param binaryBody The request body object - if it is binary, otherwise null
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public String invokeAPI(String path, String method, List<Pair> queryParams, Object body, byte[] binaryBody, Map<String, String> headerParams, Map<String, String> formParams, String accept, String contentType, String[] authNames) throws ApiException {

ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames);

if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) {
return null;
Expand Down Expand Up @@ -511,6 +533,58 @@ public class ApiClient {
respBody);
}
}
/**
* Invoke API by sending HTTP request with the given options - return binary result
*
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param queryParams The query parameters
* @param body The request body object - if it is not binary, otherwise null
* @param binaryBody The request body object - if it is binary, otherwise null
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public byte[] invokeBinaryAPI(String path, String method, List<Pair> queryParams, Object body, byte[] binaryBody, Map<String, String> headerParams, Map<String, String> formParams, String accept, String contentType, String[]authNames) throws ApiException {

ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames);

if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) {
return null;
}
else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
if(response.hasEntity()) {
DataInputStream stream = new DataInputStream(response.getEntityInputStream());
byte[] data = new byte[response.getLength()];
try {
stream.readFully(data);
} catch (IOException ex) {
throw new ApiException(500, "Error obtaining binary response data");
}
return data;
}
else {
return new byte[0];
}
}
else {
String message = "error";
if(response.hasEntity()) {
try{
message = String.valueOf(response.getEntity(String.class));
}
catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
message);
}
}

/**
* Update query and header parameters based on authentication settings.
Expand Down
45 changes: 30 additions & 15 deletions modules/swagger-codegen/src/main/resources/Java/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,16 @@ public class {{classname}} {
{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{^isBinary}}{{paramName}}{{/isBinary}}{{#isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
byte[] {{localVariablePrefix}}postBinaryBody = {{#bodyParam}}{{#isBinary}}{{paramName}}{{/isBinary}}{{^isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}");
}
{{/required}}{{/allParams}}

// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}");
}
{{/required}}{{/allParams}}
// create path and map variables
String {{localVariablePrefix}}path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}
String {{localVariablePrefix}}path = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};

// query params
Expand Down Expand Up @@ -110,14 +110,29 @@ public class {{classname}} {
}

try {

String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
String {{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames);
if({{localVariablePrefix}}response != null){
return {{#returnType}}({{{returnType}}}) {{localVariablePrefix}}apiClient.deserialize({{localVariablePrefix}}response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
}
else {
return {{#returnType}}null{{/returnType}};
}

{{#responses}}{{#isDefault}}
{{#isBinary}}
byte[] {{localVariablePrefix}}response = null;
{{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeBinaryAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams,{{localVariablePrefix}} postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames);
return {{localVariablePrefix}}response;

{{/isBinary}}
{{^isBinary}}

String {{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames);
if({{localVariablePrefix}}response != null){
return {{#returnType}}({{{returnType}}}) {{localVariablePrefix}}apiClient.deserialize({{localVariablePrefix}}response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
}
else {
return {{#returnType}}null{{/returnType}};
}
{{/isBinary}}
{{/isDefault}}
{{/responses}}

} catch (ApiException ex) {
throw ex;
}
Expand Down
15 changes: 15 additions & 0 deletions modules/swagger-codegen/src/test/scala/CodegenTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,19 @@ class CodegenTest extends FlatSpec with Matchers {
val op = codegen.fromOperation(path, "get", p, model.getDefinitions())
op.returnType should be("String")
}

it should "return byte array when response format is byte" in {
val model = new SwaggerParser()
.read("src/test/resources/2_0/binaryDataTest.json")
System.err.println("model is " + model);
val codegen = new DefaultCodegen()

val path = "/tests/binaryResponse"
val p = model.getPaths().get(path).getPost()
val op = codegen.fromOperation(path, "post", p, model.getDefinitions())
op.returnType should be("byte[]")
op.bodyParam.dataType should be ("byte[]")
op.bodyParam.isBinary should equal (true);
op.responses.get(0).isBinary should equal(true);
}
}
22 changes: 22 additions & 0 deletions modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,28 @@ class JavaModelTest extends FlatSpec with Matchers {
val vars = cm.vars
cm.classname should be("WithDots")
}

it should "convert a modelwith binary data" in {
val model = new ModelImpl()
.description("model with binary")
.property("inputBinaryData", new ByteArrayProperty());

val codegen = new JavaClientCodegen()
val cm = codegen.fromModel("sample", model)
val vars = cm.vars

vars.get(0).baseName should be ("inputBinaryData")
vars.get(0).getter should be ("getInputBinaryData")
vars.get(0).setter should be ("setInputBinaryData")
vars.get(0).datatype should be ("byte[]")
vars.get(0).name should be ("inputBinaryData")
vars.get(0).defaultValue should be ("null")
vars.get(0).baseType should be ("byte[]")
vars.get(0).hasMore should equal (null)
vars.get(0).required should equal (null)
vars.get(0).isNotContainer should equal (true)

}
}


Expand Down