Skip to content

Commit 3099aa2

Browse files
committed
Merge pull request #1853 from xhh/java-timeout
[Java] Support setting connect timeout for the default and jersey2 clients
2 parents 3c48202 + 3d65218 commit 3099aa2

File tree

4 files changed

+156
-64
lines changed

4 files changed

+156
-64
lines changed

modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache

Lines changed: 39 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,12 @@ import {{invokerPackage}}.auth.OAuth;
4343

4444
{{>generatedAnnotation}}
4545
public class ApiClient {
46-
private Map<String, Client> hostMap = new HashMap<String, Client>();
4746
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
48-
private boolean debugging = false;
4947
private String basePath = "{{basePath}}";
48+
private boolean debugging = false;
49+
private int connectionTimeout = 0;
50+
51+
private Client httpClient;
5052
private ObjectMapper mapper;
5153
5254
private Map<String, Authentication> authentications;
@@ -64,7 +66,9 @@ public class ApiClient {
6466
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
6567
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
6668
mapper.registerModule(new JodaModule());
67-
69+
70+
httpClient = buildHttpClient(debugging);
71+
6872
// Use RFC3339 format for date and datetime.
6973
// See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
7074
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
@@ -224,9 +228,29 @@ public class ApiClient {
224228
*/
225229
public ApiClient setDebugging(boolean debugging) {
226230
this.debugging = debugging;
231+
// Rebuild HTTP Client according to the new "debugging" value.
232+
this.httpClient = buildHttpClient(debugging);
227233
return this;
228234
}
229235

236+
/**
237+
* Connect timeout (in milliseconds).
238+
*/
239+
public int getConnectTimeout() {
240+
return connectionTimeout;
241+
}
242+
243+
/**
244+
* Set the connect timeout (in milliseconds).
245+
* A value of 0 means no timeout, otherwise values must be between 1 and
246+
* {@link Integer#MAX_VALUE}.
247+
*/
248+
public ApiClient setConnectTimeout(int connectionTimeout) {
249+
this.connectionTimeout = connectionTimeout;
250+
httpClient.setConnectTimeout(connectionTimeout);
251+
return this;
252+
}
253+
230254
/**
231255
* Get the date format used to parse/format date parameters.
232256
*/
@@ -436,8 +460,6 @@ public class ApiClient {
436460

437461
updateParamsForAuth(authNames, queryParams, headerParams);
438462

439-
Client client = getClient();
440-
441463
StringBuilder b = new StringBuilder();
442464
b.append("?");
443465
if (queryParams != null){
@@ -455,9 +477,9 @@ public class ApiClient {
455477

456478
Builder builder;
457479
if (accept == null)
458-
builder = client.resource(basePath + path + querystring).getRequestBuilder();
480+
builder = httpClient.resource(basePath + path + querystring).getRequestBuilder();
459481
else
460-
builder = client.resource(basePath + path + querystring).accept(accept);
482+
builder = httpClient.resource(basePath + path + querystring).accept(accept);
461483

462484
for (String key : headerParams.keySet()) {
463485
builder = builder.header(key, headerParams.get(key));
@@ -571,19 +593,17 @@ public class ApiClient {
571593
}
572594

573595
/**
574-
* Get an existing client or create a new client to handle HTTP request.
596+
* Build the Client used to make HTTP requests.
575597
*/
576-
private Client getClient() {
577-
if(!hostMap.containsKey(basePath)) {
578-
// Add the JSON serialization support to Jersey
579-
JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper);
580-
DefaultClientConfig conf = new DefaultClientConfig();
581-
conf.getSingletons().add(jsonProvider);
582-
Client client = Client.create(conf);
583-
if (debugging)
584-
client.addFilter(new LoggingFilter());
585-
hostMap.put(basePath, client);
598+
private Client buildHttpClient(boolean debugging) {
599+
// Add the JSON serialization support to Jersey
600+
JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper);
601+
DefaultClientConfig conf = new DefaultClientConfig();
602+
conf.getSingletons().add(jsonProvider);
603+
Client client = Client.create(conf);
604+
if (debugging) {
605+
client.addFilter(new LoggingFilter());
586606
}
587-
return hostMap.get(basePath);
607+
return client;
588608
}
589609
}

modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache

Lines changed: 37 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ import javax.ws.rs.core.Response;
1212
import javax.ws.rs.core.Response.Status;
1313

1414
import org.glassfish.jersey.client.ClientConfig;
15+
import org.glassfish.jersey.client.ClientProperties;
1516
import org.glassfish.jersey.filter.LoggingFilter;
17+
import org.glassfish.jersey.jackson.JacksonFeature;
1618
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
1719
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
1820
import org.glassfish.jersey.media.multipart.MultiPart;
@@ -43,12 +45,13 @@ import {{invokerPackage}}.auth.OAuth;
4345

4446
{{>generatedAnnotation}}
4547
public class ApiClient {
46-
private Client client;
47-
private Map<String, Client> hostMap = new HashMap<String, Client>();
4848
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
49-
private boolean debugging = false;
5049
private String basePath = "{{basePath}}";
51-
private JSON json = new JSON();
50+
private boolean debugging = false;
51+
private int connectionTimeout = 0;
52+
53+
private Client httpClient;
54+
private JSON json;
5255
5356
private Map<String, Authentication> authentications;
5457
@@ -58,6 +61,9 @@ public class ApiClient {
5861
private DateFormat dateFormat;
5962
6063
public ApiClient() {
64+
json = new JSON();
65+
httpClient = buildHttpClient(debugging);
66+
6167
// Use RFC3339 format for date and datetime.
6268
// See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
6369
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
@@ -70,8 +76,6 @@ public class ApiClient {
7076
// Set default User-Agent.
7177
setUserAgent("Java-Swagger");
7278
73-
buildClient();
74-
7579
// Setup authentications (key: authentication name, value: authentication).
7680
authentications = new HashMap<String, Authentication>();{{#authMethods}}{{#isBasic}}
7781
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
@@ -226,10 +230,29 @@ public class ApiClient {
226230
*/
227231
public ApiClient setDebugging(boolean debugging) {
228232
this.debugging = debugging;
229-
buildClient();
233+
// Rebuild HTTP Client according to the new "debugging" value.
234+
this.httpClient = buildHttpClient(debugging);
230235
return this;
231236
}
232237

238+
/**
239+
* Connect timeout (in milliseconds).
240+
*/
241+
public int getConnectTimeout() {
242+
return connectionTimeout;
243+
}
244+
245+
/**
246+
* Set the connect timeout (in milliseconds).
247+
* A value of 0 means no timeout, otherwise values must be between 1 and
248+
* {@link Integer#MAX_VALUE}.
249+
*/
250+
public ApiClient setConnectTimeout(int connectionTimeout) {
251+
this.connectionTimeout = connectionTimeout;
252+
httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout);
253+
return this;
254+
}
255+
233256
/**
234257
* Get the date format used to parse/format date parameters.
235258
*/
@@ -472,7 +495,7 @@ public class ApiClient {
472495
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
473496
updateParamsForAuth(authNames, queryParams, headerParams);
474497
475-
WebTarget target = client.target(this.basePath).path(path);
498+
WebTarget target = httpClient.target(this.basePath).path(path);
476499
477500
if (queryParams != null) {
478501
for (Pair queryParam : queryParams) {
@@ -545,15 +568,18 @@ public class ApiClient {
545568
}
546569
}
547570

548-
private void buildClient() {
571+
/**
572+
* Build the Client used to make HTTP requests.
573+
*/
574+
private Client buildHttpClient(boolean debugging) {
549575
final ClientConfig clientConfig = new ClientConfig();
550576
clientConfig.register(MultiPartFeature.class);
551577
clientConfig.register(json);
552-
clientConfig.register(org.glassfish.jersey.jackson.JacksonFeature.class);
578+
clientConfig.register(JacksonFeature.class);
553579
if (debugging) {
554580
clientConfig.register(LoggingFilter.class);
555581
}
556-
this.client = ClientBuilder.newClient(clientConfig);
582+
return ClientBuilder.newClient(clientConfig);
557583
}
558584

559585
private Map<String, List<String>> buildResponseHeaders(Response response) {

samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java

Lines changed: 41 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,14 @@
4141
import io.swagger.client.auth.ApiKeyAuth;
4242
import io.swagger.client.auth.OAuth;
4343

44-
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00")
44+
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-08T18:50:38.131+08:00")
4545
public class ApiClient {
46-
private Map<String, Client> hostMap = new HashMap<String, Client>();
4746
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
48-
private boolean debugging = false;
4947
private String basePath = "http://petstore.swagger.io/v2";
48+
private boolean debugging = false;
49+
private int connectionTimeout = 0;
50+
51+
private Client httpClient;
5052
private ObjectMapper mapper;
5153

5254
private Map<String, Authentication> authentications;
@@ -64,7 +66,9 @@ public ApiClient() {
6466
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
6567
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
6668
mapper.registerModule(new JodaModule());
67-
69+
70+
httpClient = buildHttpClient(debugging);
71+
6872
// Use RFC3339 format for date and datetime.
6973
// See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
7074
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
@@ -79,8 +83,8 @@ public ApiClient() {
7983

8084
// Setup authentications (key: authentication name, value: authentication).
8185
authentications = new HashMap<String, Authentication>();
82-
authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
8386
authentications.put("petstore_auth", new OAuth());
87+
authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
8488
// Prevent the authentications from being modified.
8589
authentications = Collections.unmodifiableMap(authentications);
8690
}
@@ -223,9 +227,29 @@ public boolean isDebugging() {
223227
*/
224228
public ApiClient setDebugging(boolean debugging) {
225229
this.debugging = debugging;
230+
// Rebuild HTTP Client according to the new "debugging" value.
231+
this.httpClient = buildHttpClient(debugging);
226232
return this;
227233
}
228234

235+
/**
236+
* Connect timeout (in milliseconds).
237+
*/
238+
public int getConnectTimeout() {
239+
return connectionTimeout;
240+
}
241+
242+
/**
243+
* Set the connect timeout (in milliseconds).
244+
* A value of 0 means no timeout, otherwise values must be between 1 and
245+
* {@link Integer#MAX_VALUE}.
246+
*/
247+
public ApiClient setConnectTimeout(int connectionTimeout) {
248+
this.connectionTimeout = connectionTimeout;
249+
httpClient.setConnectTimeout(connectionTimeout);
250+
return this;
251+
}
252+
229253
/**
230254
* Get the date format used to parse/format date parameters.
231255
*/
@@ -435,8 +459,6 @@ private ClientResponse getAPIResponse(String path, String method, List<Pair> que
435459

436460
updateParamsForAuth(authNames, queryParams, headerParams);
437461

438-
Client client = getClient();
439-
440462
StringBuilder b = new StringBuilder();
441463
b.append("?");
442464
if (queryParams != null){
@@ -454,9 +476,9 @@ private ClientResponse getAPIResponse(String path, String method, List<Pair> que
454476

455477
Builder builder;
456478
if (accept == null)
457-
builder = client.resource(basePath + path + querystring).getRequestBuilder();
479+
builder = httpClient.resource(basePath + path + querystring).getRequestBuilder();
458480
else
459-
builder = client.resource(basePath + path + querystring).accept(accept);
481+
builder = httpClient.resource(basePath + path + querystring).accept(accept);
460482

461483
for (String key : headerParams.keySet()) {
462484
builder = builder.header(key, headerParams.get(key));
@@ -570,19 +592,17 @@ private String getXWWWFormUrlencodedParams(Map<String, Object> formParams) {
570592
}
571593

572594
/**
573-
* Get an existing client or create a new client to handle HTTP request.
595+
* Build the Client used to make HTTP requests.
574596
*/
575-
private Client getClient() {
576-
if(!hostMap.containsKey(basePath)) {
577-
// Add the JSON serialization support to Jersey
578-
JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper);
579-
DefaultClientConfig conf = new DefaultClientConfig();
580-
conf.getSingletons().add(jsonProvider);
581-
Client client = Client.create(conf);
582-
if (debugging)
583-
client.addFilter(new LoggingFilter());
584-
hostMap.put(basePath, client);
597+
private Client buildHttpClient(boolean debugging) {
598+
// Add the JSON serialization support to Jersey
599+
JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper);
600+
DefaultClientConfig conf = new DefaultClientConfig();
601+
conf.getSingletons().add(jsonProvider);
602+
Client client = Client.create(conf);
603+
if (debugging) {
604+
client.addFilter(new LoggingFilter());
585605
}
586-
return hostMap.get(basePath);
606+
return client;
587607
}
588608
}

0 commit comments

Comments
 (0)