Skip to content

Commit

Permalink
Add 'useRxJava' option to retrofit2 java client generator
Browse files Browse the repository at this point in the history
This still uses retrofit 2.0.0-beta2 because the api
in beta3 has changed and the package
has been renamed to retrofit2.*

Change retrofit-rx to be a library option
  • Loading branch information
kungfoo committed Jan 21, 2016
1 parent 0bfc99d commit 1ba22dc
Show file tree
Hide file tree
Showing 9 changed files with 135 additions and 75 deletions.
Original file line number Diff line number Diff line change
@@ -1,26 +1,55 @@
package io.swagger.codegen.languages;

import com.google.common.base.Strings;
import io.swagger.codegen.*;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Swagger;
import io.swagger.models.parameters.FormParameter;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.properties.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.*;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.BooleanProperty;
import io.swagger.models.properties.DoubleProperty;
import io.swagger.models.properties.FloatProperty;
import io.swagger.models.properties.IntegerProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.StringProperty;

public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class);
public static final String FULL_JAVA_UTIL = "fullJavaUtil";
public static final String DEFAULT_LIBRARY = "<default>";
public static final String DATE_LIBRARY = "dateLibrary";
public static final String USE_RX_JAVA = "useRxJava";

public static final String RETROFIT_1 = "retrofit";
public static final String RETROFIT_2 = "retrofit2";

protected String dateLibrary = "default";
protected String invokerPackage = "io.swagger.client";
Expand All @@ -34,6 +63,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String javaUtilPrefix = "";
protected Boolean serializableModel = false;
protected boolean serializeBigDecimalAsString = false;
protected boolean useRxJava = false;

public JavaClientCodegen() {
super();
Expand Down Expand Up @@ -87,13 +117,15 @@ public JavaClientCodegen() {
cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, CodegenConstants
.SERIALIZE_BIG_DECIMAL_AS_STRING_DESC));
cliOptions.add(CliOption.newBoolean(FULL_JAVA_UTIL, "whether to use fully qualified name for classes under java.util"));
cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library."));

supportedLibraries.put(DEFAULT_LIBRARY, "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2");
supportedLibraries.put("feign", "HTTP client: Netflix Feign 8.1.1");
supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6");
supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1");
supportedLibraries.put("retrofit", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
supportedLibraries.put("retrofit2", "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2)");
supportedLibraries.put(RETROFIT_1, "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 2.5.0. JSON processing: Gson 2.4 (Retrofit 2.0.0-beta2). Enable the RxJava adapter using '-DuseRxJava=true'.");

CliOption library = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use");
library.setDefault(DEFAULT_LIBRARY);
library.setEnum(supportedLibraries);
Expand Down Expand Up @@ -182,6 +214,10 @@ public void processOpts() {
if (additionalProperties.containsKey(FULL_JAVA_UTIL)) {
this.setFullJavaUtil(Boolean.valueOf(additionalProperties.get(FULL_JAVA_UTIL).toString()));
}

if (additionalProperties.containsKey(USE_RX_JAVA)) {
this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString()));
}
if (fullJavaUtil) {
javaUtilPrefix = "java.util.";
}
Expand Down Expand Up @@ -239,7 +275,7 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java"));
supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java"));

if (!("feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) {
if (!("feign".equals(getLibrary()) || usesAnyRetrofitLibrary())) {
supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java"));
supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java"));
supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java"));
Expand All @@ -256,7 +292,7 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java"));
// "build.sbt" is for development with SBT
supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt"));
} else if ("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) {
} else if (usesAnyRetrofitLibrary()) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java"));
} else if("jersey2".equals(getLibrary())) {
Expand Down Expand Up @@ -284,6 +320,14 @@ else if ("java8".equals(dateLibrary)) {
}
}

private boolean usesAnyRetrofitLibrary() {
return getLibrary() != null && getLibrary().contains(RETROFIT_1);
}

private boolean usesRetrofit2Library() {
return getLibrary() != null && getLibrary().contains(RETROFIT_2);
}

private void sanitizeConfig() {
// Sanitize any config options here. We also have to update the additionalProperties because
// the whole additionalProperties object is injected into the main object passed to the mustache layer
Expand Down Expand Up @@ -597,7 +641,7 @@ public Map<String, Object> postProcessModels(Map<String, Object> objs) {

@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
if("retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary())) {
if(usesAnyRetrofitLibrary()) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
Expand All @@ -613,7 +657,7 @@ public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
if (operation.returnType == null) {
operation.returnType = "Void";
}
if ("retrofit2".equals(getLibrary()) && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/"))
if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/"))
operation.path = operation.path.substring(1);
}
}
Expand Down Expand Up @@ -791,6 +835,10 @@ public void setFullJavaUtil(boolean fullJavaUtil) {
this.fullJavaUtil = fullJavaUtil;
}

public void setUseRxJava(boolean useRxJava) {
this.useRxJava = useRxJava;
}

public void setDateLibrary(String library) {
this.dateLibrary = library;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuil
import retrofit.Converter;
import retrofit.Retrofit;
import retrofit.GsonConverterFactory;
{{#useRxJava}}import retrofit.RxJavaCallAdapterFactory;{{/useRxJava}}

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
Expand All @@ -22,6 +23,7 @@ import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.ResponseBody;


import {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.auth.ApiKeyAuth;
import {{invokerPackage}}.auth.OAuth;
Expand Down Expand Up @@ -117,6 +119,7 @@ public class ApiClient {
.Builder()
.baseUrl(baseUrl)
.client(okClient)
{{#useRxJava}}.addCallAdapterFactory(RxJavaCallAdapterFactory.create()){{/useRxJava}}
.addConverterFactory(GsonCustomConverterFactory.create(gson));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package {{package}};

import {{invokerPackage}}.CollectionFormats.*;

import retrofit.Call;
{{#useRxJava}}import rx.Observable;{{/useRxJava}}
{{^useRxJava}}import retrofit.Call;{{/useRxJava}}
import retrofit.http.*;

import com.squareup.okhttp.RequestBody;

{{#imports}}import {{import}};
Expand All @@ -25,7 +27,7 @@ public interface {{classname}} {
{{#formParams}}{{#-first}}
{{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}}
@{{httpMethod}}("{{path}}")
Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}}
{{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}}
{{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}
);{{/hasMore}}{{/allParams}}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,26 @@ ext {
gson_version = "2.4"
swagger_annotations_version = "1.5.0"
junit_version = "4.12"
{{#useRxJava}}
rx_java_version = "1.0.15"
{{/useRxJava}}
{{^useRxJava}}{{/useRxJava}}
}

dependencies {
compile "com.squareup.okhttp:okhttp:$okhttp_version"
compile "com.squareup.retrofit:retrofit:$retrofit_version"
compile "com.google.code.gson:gson:$gson_version"
compile "com.squareup.retrofit:converter-gson:$retrofit_version"
{{#useRxJava}}
compile "com.squareup.retrofit:adapter-rxjava:$retrofit_version"
compile "io.reactivex:rxjava:$rx_java_version"
{{/useRxJava}}
{{^useRxJava}}{{/useRxJava}}

compile "com.google.code.gson:gson:$gson_version"
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version"

testCompile "junit:junit:$junit_version"
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ protected void setExpectations() {
times = 1;
clientCodegen.setSerializableModel(Boolean.valueOf(JavaInflectorServerOptionsProvider.SERIALIZABLE_MODEL_VALUE));
times = 1;
clientCodegen.setLibrary(JavaInflectorServerOptionsProvider.LIBRARY_VALUE);
clientCodegen.setLibrary(JavaInflectorServerOptionsProvider.DEFAULT_LIBRARY_VALUE);
times = 1;
clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaInflectorServerOptionsProvider.FULL_JAVA_UTIL_VALUE));
times = 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ protected void setExpectations() {
times = 1;
clientCodegen.setSerializableModel(Boolean.valueOf(JavaOptionsProvider.SERIALIZABLE_MODEL_VALUE));
times = 1;
clientCodegen.setLibrary(JavaOptionsProvider.LIBRARY_VALUE);
clientCodegen.setLibrary(JavaOptionsProvider.DEFAULT_LIBRARY_VALUE);
times = 1;
clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaOptionsProvider.FULL_JAVA_UTIL_VALUE));
times = 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ protected void setExpectations() {
times = 1;
clientCodegen.setSerializableModel(Boolean.valueOf(JaxRSServerOptionsProvider.SERIALIZABLE_MODEL_VALUE));
times = 1;
clientCodegen.setLibrary(JaxRSServerOptionsProvider.LIBRARY_VALUE);
clientCodegen.setLibrary(JaxRSServerOptionsProvider.DEFAULT_LIBRARY_VALUE);
times = 1;
clientCodegen.setFullJavaUtil(Boolean.valueOf(JaxRSServerOptionsProvider.FULL_JAVA_UTIL_VALUE));
times = 1;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.swagger.codegen.options;

import io.swagger.codegen.Codegen;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.languages.JavaClientCodegen;

Expand All @@ -17,15 +18,19 @@ public class JavaOptionsProvider implements OptionsProvider {
public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT";
public static final String SOURCE_FOLDER_VALUE = "src/main/java/test";
public static final String LOCAL_PREFIX_VALUE = "tst";
public static final String LIBRARY_VALUE = "jersey2";
public static final String DEFAULT_LIBRARY_VALUE = "jersey2";
public static final String SERIALIZABLE_MODEL_VALUE = "false";
public static final String FULL_JAVA_UTIL_VALUE = "true";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";

@Override
public Map<String, String> createOptions() {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE)
private ImmutableMap<String, String> options;

/**
* Create an options provider with the default options.
*/
public JavaOptionsProvider() {
options = new ImmutableMap.Builder<String, String>()
.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE)
.put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE)
.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
Expand All @@ -37,12 +42,28 @@ public Map<String, String> createOptions() {
.put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE)
.put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE)
.put(JavaClientCodegen.FULL_JAVA_UTIL, FULL_JAVA_UTIL_VALUE)
.put(CodegenConstants.LIBRARY, LIBRARY_VALUE)
.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE)
.put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true")
.put(JavaClientCodegen.USE_RX_JAVA, "false")
.put(JavaClientCodegen.DATE_LIBRARY, "joda")
.build();
}

/**
* Use the default options, but override the ones found in additionalOptions.
*/
public JavaOptionsProvider(Map<String, String> additionalOptions) {
options = new ImmutableMap.Builder<String, String>()
.putAll(options)
.putAll(additionalOptions)
.build();
}

@Override
public Map<String, String> createOptions() {
return options;
}

@Override
public boolean isServer() {
return false;
Expand Down
Loading

0 comments on commit 1ba22dc

Please sign in to comment.