[REQ] Enhance configurability of the OkHttpClient used by Java+retrofit2
Created by: marcoaltieri
Description
The class ApiClient generated for Java+retrofit2 is not easily configurable. The default constructor of the class calls the method createDefaultAdapter(). This method configures the "adapter builder" that is later used go create the services as shown below:
public void createDefaultAdapter() {
json = new JSON();
okBuilder = new OkHttpClient.Builder();
String baseUrl = "https://localhost/someco/contracts-api";
if (!baseUrl.endsWith("/"))
baseUrl = baseUrl + "/";
adapterBuilder = new Retrofit
.Builder()
.baseUrl(baseUrl)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonCustomConverterFactory.create(json.getGson()));
}
public <S> S createService(Class<S> serviceClass) {
return adapterBuilder
.client(okBuilder.build())
.build()
.create(serviceClass);
}
Swagger-codegen version
swagger-codegen-maven-plugin 2.3.1
Command line used for generation
<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<output>${project.basedir}</output>
<!-- specify the swagger yaml -->
<inputSpec>${project.basedir}/api-editor/api/swagger/swagger.yaml</inputSpec>
<!-- target to generate java client code -->
<language>java</language>
<generateApiTests>true</generateApiTests>
<generateModelTests>true</generateModelTests>
<configOptions>
<dateLibrary>joda</dateLibrary>
<invokerPackage>com.someco.client.invoker</invokerPackage>
<apiPackage>com.someco.client.api</apiPackage>
<modelPackage>com.someco.client.model</modelPackage>
<sourceFolder>src/gen/java</sourceFolder>
<serializableModel>true</serializableModel>
<hideGenerationTimestamp>true</hideGenerationTimestamp>
</configOptions>
<!-- override the default library to retrofit2 -->
<library>retrofit2</library>
</configuration>
</execution>
</executions>
</plugin>
Steps to reproduce
Generate the client code using maven and the configuration above
Suggest a fix/enhancement
With the current implementation it seems impossible, for example, to configure a reusable OkHttpClient that is configured with a proper connection pool. Because the method createDefaultAdapter() needs to configure private members, it cannot be overridden by a super class and so its behaviour cannot be modified using inheritance.
It could be good to allow the execution of something like the following snippet:
ConnectionPool pool = new ConnectionPool(poolSize, keepAlive, TimeUnit.SECONDS);
OkHttpClient client = apiClient.getOkBuilder().connectionPool(pool).build();
apiClient.getAdapterBuilder().baseUrl(apiPath).client(client);
apiClient.build(); // this builds the adapter (a "Retrofit" object) using the adapterBuilder.