Skip to content

Commit

Permalink
Better code format for Java (okhttp-gson) client (OpenAPITools#971)
Browse files Browse the repository at this point in the history
* better code format for java okhttp client

* update java petstore samples
  • Loading branch information
wing328 authored Sep 6, 2018
1 parent 3abeb82 commit 39c734f
Show file tree
Hide file tree
Showing 56 changed files with 1,055 additions and 709 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4700,6 +4700,6 @@ private void setParameterNullable(CodegenParameter parameter, CodegenProperty pr
* @param fileType file type
*/
public void postProcessFile(File file, String fileType) {
LOGGER.info("Post processing file {} ({})", file, fileType);
LOGGER.debug("Post processing file {} ({})", file, fileType);
}
}
46 changes: 25 additions & 21 deletions modules/openapi-generator/src/main/resources/Java/JSON.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -61,20 +61,24 @@ public class JSON {

public static GsonBuilder createGson() {
GsonFireBuilder fireBuilder = new GsonFireBuilder()
{{#models}}{{#model}}{{#discriminator}} .registerTypeSelector({{classname}}.class, new TypeSelector() {
@Override
public Class getClassForElement(JsonElement readElement) {
Map classByDiscriminatorValue = new HashMap();
{{#mappedModels}}
classByDiscriminatorValue.put("{{mappingName}}".toUpperCase(Locale.ROOT), {{modelName}}.class);
{{/mappedModels}}
classByDiscriminatorValue.put("{{classname}}".toUpperCase(Locale.ROOT), {{classname}}.class);
return getClassByDiscriminator(
classByDiscriminatorValue,
getDiscriminatorValue(readElement, "{{{propertyName}}}"));
}
{{#models}}
{{#model}}
{{#discriminator}}
.registerTypeSelector({{classname}}.class, new TypeSelector() {
@Override
public Class getClassForElement(JsonElement readElement) {
Map classByDiscriminatorValue = new HashMap();
{{#mappedModels}}
classByDiscriminatorValue.put("{{mappingName}}".toUpperCase(Locale.ROOT), {{modelName}}.class);
{{/mappedModels}}
classByDiscriminatorValue.put("{{classname}}".toUpperCase(Locale.ROOT), {{classname}}.class);
return getClassByDiscriminator(classByDiscriminatorValue,
getDiscriminatorValue(readElement, "{{{propertyName}}}"));
}
})
{{/discriminator}}{{/model}}{{/models}}
{{/discriminator}}
{{/model}}
{{/models}}
;
GsonBuilder builder = fireBuilder.createGsonBuilder();
{{#disableHtmlEscaping}}
Expand All @@ -85,15 +89,15 @@ public class JSON {

private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) {
JsonElement element = readElement.getAsJsonObject().get(discriminatorField);
if(null == element) {
if (null == element) {
throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">");
}
return element.getAsString();
}

private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) {
Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue.toUpperCase(Locale.ROOT));
if(null == clazz) {
if (null == clazz) {
throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">");
}
return clazz;
Expand Down Expand Up @@ -172,9 +176,11 @@ public class JSON {
} catch (JsonParseException e) {
// Fallback processing when failed to parse JSON form response body:
// return the response body string directly for the String return type;
if (returnType.equals(String.class))
if (returnType.equals(String.class)) {
return (T) body;
else throw (e);
} else {
throw (e);
}
}
}

Expand Down Expand Up @@ -408,8 +414,7 @@ public class JSON {
private DateFormat dateFormat;
public SqlDateTypeAdapter() {
}
public SqlDateTypeAdapter() {}

public SqlDateTypeAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
Expand Down Expand Up @@ -462,8 +467,7 @@ public class JSON {
private DateFormat dateFormat;
public DateTypeAdapter() {
}
public DateTypeAdapter() {}

public DateTypeAdapter(DateFormat dateFormat) {
this.dateFormat = dateFormat;
Expand Down
17 changes: 13 additions & 4 deletions modules/openapi-generator/src/main/resources/Java/Pair.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,17 @@ public class Pair {
}

private void setName(String name) {
if (!isValidString(name)) return;
if (!isValidString(name)) {
return;
}

this.name = name;
}

private void setValue(String value) {
if (!isValidString(value)) return;
if (!isValidString(value)) {
return;
}

this.value = value;
}
Expand All @@ -33,8 +37,13 @@ public class Pair {
}

private boolean isValidString(String arg) {
if (arg == null) return false;
if (arg.trim().isEmpty()) return false;
if (arg == null) {
return false;
}

if (arg.trim().isEmpty()) {
return false;
}

return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,12 @@ public class StringUtil {
*/
public static boolean containsIgnoreCase(String[] array, String value) {
for (String str : array) {
if (value == null && str == null) return true;
if (value != null && value.equalsIgnoreCase(str)) return true;
if (value == null && str == null) {
return true;
}
if (value != null && value.equalsIgnoreCase(str)) {
return true;
}
}
return false;
}
Expand All @@ -32,7 +36,9 @@ public class StringUtil {
*/
public static String join(String[] array, String separator) {
int len = array.length;
if (len == 0) return "";
if (len == 0) {
return "";
}

StringBuilder out = new StringBuilder();
out.append(array[0]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ public class ApiClient {
return jsonStr.substring(1, jsonStr.length() - 1);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for (Object o : (Collection)param) {
for (Object o : (Collection) param) {
if (b.length() > 0) {
b.append(",");
}
Expand All @@ -542,7 +542,9 @@ public class ApiClient {
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null || value instanceof Collection) return params;
if (name == null || name.isEmpty() || value == null || value instanceof Collection) {
return params;
}
params.add(new Pair(name, parameterToString(value)));
return params;
Expand Down Expand Up @@ -587,7 +589,7 @@ public class ApiClient {
delimiter = escapeString("|");
}
StringBuilder sb = new StringBuilder() ;
StringBuilder sb = new StringBuilder();
for (Object item : value) {
sb.append(delimiter);
sb.append(escapeString(parameterToString(item)));
Expand Down Expand Up @@ -657,7 +659,7 @@ public class ApiClient {
*/
public String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0 || contentTypes[0].equals("*/*")) {
return "application/json";
return "application/json";
}
for (String contentType : contentTypes) {
if (isJsonMime(contentType)) {
Expand Down Expand Up @@ -981,7 +983,7 @@ public class ApiClient {
* @param formParams The form parameters
* @param authNames The authentications to apply
* @param progressRequestListener Progress request listener
* @return The HTTP request
* @return The HTTP request
* @throws ApiException If fail to serialize the request body object
*/
public Request buildRequest(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Expand Down Expand Up @@ -1098,13 +1100,15 @@ public class ApiClient {
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
*/
public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
if (auth == null) {
throw new RuntimeException("Authentication undefined: " + authName);
}
auth.applyToParams(queryParams, headerParams);
}
}
Expand All @@ -1116,7 +1120,7 @@ public class ApiClient {
* @return RequestBody
*/
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
FormEncodingBuilder formBuilder = new FormEncodingBuilder();
FormEncodingBuilder formBuilder = new FormEncodingBuilder();
for (Entry<String, Object> param : formParams.entrySet()) {
formBuilder.add(param.getKey(), parameterToString(param.getValue()));
}
Expand Down Expand Up @@ -1179,10 +1183,12 @@ public class ApiClient {
public X509Certificate[] getAcceptedIssuers() { return null; }
};
SSLContext sslContext = SSLContext.getInstance("TLS");
trustManagers = new TrustManager[]{ trustAll };
trustManagers = new TrustManager[] {trustAll};
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) { return true; }
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
} else if (sslCaCert != null) {
char[] password = null; // Any password will work.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import java.io.IOException;
* Taken from https://github.com/square/okhttp/issues/350
*/
class GzipRequestInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
Expand Down Expand Up @@ -52,19 +53,22 @@ class GzipRequestInterceptor implements Interceptor {

private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override public MediaType contentType() {
@Override
public MediaType contentType() {
return body.contentType();
}

@Override public long contentLength() {
@Override
public long contentLength() {
return -1; // We don't know the compressed length in advance!
}
@Override public void writeTo(BufferedSink sink) throws IOException {
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -89,31 +89,42 @@ public class {{classname}} {
.replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}};

{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarCollectionQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();{{#queryParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}{{#collectionFormat}}localVarCollectionQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{{collectionFormat}}}", {{/collectionFormat}}{{^collectionFormat}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPair({{/collectionFormat}}"{{baseName}}", {{paramName}}));{{/queryParams}}
{{javaUtilPrefix}}List<Pair> {{localVariablePrefix}}localVarCollectionQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
{{#queryParams}}
if ({{paramName}} != null) {
{{localVariablePrefix}}{{#collectionFormat}}localVarCollectionQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{{collectionFormat}}}", {{/collectionFormat}}{{^collectionFormat}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPair({{/collectionFormat}}"{{baseName}}", {{paramName}}));
}

{{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();{{#headerParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}}
{{/queryParams}}
{{javaUtilPrefix}}Map<String, String> {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();
{{#headerParams}}
if ({{paramName}} != null) {
{{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));
}

{{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();{{#formParams}}
if ({{paramName}} != null)
{{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}}
{{/headerParams}}
{{javaUtilPrefix}}Map<String, Object> {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();
{{#formParams}}
if ({{paramName}} != null) {
{{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});
}

{{/formParams}}
final String[] {{localVariablePrefix}}localVarAccepts = {
{{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}}
};
final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts);
if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept);
if ({{localVariablePrefix}}localVarAccept != null) {
{{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept);
}

final String[] {{localVariablePrefix}}localVarContentTypes = {
{{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}
};
final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes);
{{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType);

if(progressListener != null) {
if (progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
Expand Down Expand Up @@ -265,4 +276,4 @@ public class {{classname}} {
}
{{/operation}}
}
{{/operations}}
{{/operations}}
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,12 @@ public class StringUtil {
*/
public static boolean containsIgnoreCase(String[] array, String value) {
for (String str : array) {
if (value == null && str == null) return true;
if (value != null && value.equalsIgnoreCase(str)) return true;
if (value == null && str == null) {
return true;
}
if (value != null && value.equalsIgnoreCase(str)) {
return true;
}
}
return false;
}
Expand All @@ -43,7 +47,9 @@ public static boolean containsIgnoreCase(String[] array, String value) {
*/
public static String join(String[] array, String separator) {
int len = array.length;
if (len == 0) return "";
if (len == 0) {
return "";
}

StringBuilder out = new StringBuilder();
out.append(array[0]);
Expand Down
Loading

0 comments on commit 39c734f

Please sign in to comment.