Skip to content

Commit 57bf692

Browse files
authored
[Java] Make Java ApiClient extendable (#21251)
* Make all Java ApiClients in templates extendable * Make all Java ApiClients in samples extendable * Fix compilation of enum constructor * Fix compilation of enum constructor in templates
1 parent be17698 commit 57bf692

File tree

89 files changed

+1251
-1251
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

89 files changed

+1251
-1251
lines changed

modules/openapi-generator/src/main/resources/Java/ApiClient.mustache

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,9 @@ import {{invokerPackage}}.auth.OAuth;
6565

6666
{{>generatedAnnotation}}
6767
public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
68-
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
69-
private Map<String, String> defaultCookieMap = new HashMap<String, String>();
70-
private String basePath = "{{{basePath}}}";
68+
protected Map<String, String> defaultHeaderMap = new HashMap<String, String>();
69+
protected Map<String, String> defaultCookieMap = new HashMap<String, String>();
70+
protected String basePath = "{{{basePath}}}";
7171
protected List<ServerConfiguration> servers = new ArrayList<ServerConfiguration>({{#servers}}{{#-first}}Arrays.asList(
7272
{{/-first}} new ServerConfiguration(
7373
"{{{url}}}",
@@ -95,18 +95,18 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
9595
){{/-last}}{{/servers}});
9696
protected Integer serverIndex = 0;
9797
protected Map<String, String> serverVariables = null;
98-
private boolean debugging = false;
99-
private int connectionTimeout = 0;
98+
protected boolean debugging = false;
99+
protected int connectionTimeout = 0;
100100

101-
private Client httpClient;
102-
private ObjectMapper objectMapper;
101+
protected Client httpClient;
102+
protected ObjectMapper objectMapper;
103103

104-
private Map<String, Authentication> authentications;
104+
protected Map<String, Authentication> authentications;
105105

106-
private int statusCode;
107-
private Map<String, List<String>> responseHeaders;
106+
protected int statusCode;
107+
protected Map<String, List<String>> responseHeaders;
108108

109-
private DateFormat dateFormat;
109+
protected DateFormat dateFormat;
110110

111111
public ApiClient() {
112112
objectMapper = new ObjectMapper();
@@ -688,7 +688,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
688688
* @param collectionQueryParams The collection query parameters
689689
* @return The full URL
690690
*/
691-
private String buildUrl(String path, List<Pair> queryParams, List<Pair> collectionQueryParams) {
691+
protected String buildUrl(String path, List<Pair> queryParams, List<Pair> collectionQueryParams) {
692692
String baseURL;
693693
if (serverIndex != null) {
694694
if (serverIndex < 0 || serverIndex >= servers.size()) {
@@ -741,7 +741,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
741741
return url.toString();
742742
}
743743

744-
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
744+
protected ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, String> cookieParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
745745
if (body != null && !formParams.isEmpty()) {
746746
throw new ApiException(500, "Cannot have body and form params");
747747
}
@@ -854,7 +854,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
854854
* @param headerParams Header parameters
855855
* @param cookieParams Cookie parameters
856856
*/
857-
private void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) {
857+
protected void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) {
858858
for (String authName : authNames) {
859859
Authentication auth = authentications.get(authName);
860860
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
@@ -867,7 +867,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
867867
* @param formParams Form parameters
868868
* @return HTTP form encoded parameters
869869
*/
870-
private String getXWWWFormUrlencodedParams(Map<String, Object> formParams) {
870+
protected String getXWWWFormUrlencodedParams(Map<String, Object> formParams) {
871871
StringBuilder formParamBuilder = new StringBuilder();
872872
873873
for (Entry<String, Object> param : formParams.entrySet()) {

modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/ApiClient.mustache

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,9 @@ import {{invokerPackage}}.auth.OAuth;
8787

8888
{{>generatedAnnotation}}
8989
public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
90-
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
91-
private Map<String, String> defaultCookieMap = new HashMap<String, String>();
92-
private String basePath = "{{{basePath}}}";
90+
protected Map<String, String> defaultHeaderMap = new HashMap<String, String>();
91+
protected Map<String, String> defaultCookieMap = new HashMap<String, String>();
92+
protected String basePath = "{{{basePath}}}";
9393
protected List<ServerConfiguration> servers = new ArrayList<ServerConfiguration>({{#servers}}{{#-first}}Arrays.asList(
9494
{{/-first}} new ServerConfiguration(
9595
"{{{url}}}",
@@ -117,22 +117,22 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
117117
){{/-last}}{{/servers}});
118118
protected Integer serverIndex = 0;
119119
protected Map<String, String> serverVariables = null;
120-
private boolean debugging = false;
121-
private int connectionTimeout = 0;
120+
protected boolean debugging = false;
121+
protected int connectionTimeout = 0;
122122

123-
private CloseableHttpClient httpClient;
124-
private ObjectMapper objectMapper;
123+
protected CloseableHttpClient httpClient;
124+
protected ObjectMapper objectMapper;
125125
protected String tempFolderPath = null;
126126

127-
private Map<String, Authentication> authentications;
127+
protected Map<String, Authentication> authentications;
128128

129-
private Map<Long, Integer> lastStatusCodeByThread = new ConcurrentHashMap<>();
130-
private Map<Long, Map<String, List<String>>> lastResponseHeadersByThread = new ConcurrentHashMap<>();
129+
protected Map<Long, Integer> lastStatusCodeByThread = new ConcurrentHashMap<>();
130+
protected Map<Long, Map<String, List<String>>> lastResponseHeadersByThread = new ConcurrentHashMap<>();
131131

132-
private DateFormat dateFormat;
132+
protected DateFormat dateFormat;
133133

134134
// Methods that can have a request body
135-
private static List<String> bodyMethods = Arrays.asList("POST", "PUT", "DELETE", "PATCH");
135+
protected static List<String> bodyMethods = Arrays.asList("POST", "PUT", "DELETE", "PATCH");
136136

137137
public ApiClient(CloseableHttpClient httpClient) {
138138
objectMapper = new ObjectMapper();
@@ -757,7 +757,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
757757
/**
758758
* Parse content type object from header value
759759
*/
760-
private ContentType getContentType(String headerValue) throws ApiException {
760+
protected ContentType getContentType(String headerValue) throws ApiException {
761761
try {
762762
return ContentType.parse(headerValue);
763763
} catch (UnsupportedCharsetException e) {
@@ -768,7 +768,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
768768
/**
769769
* Get content type of a response or null if one was not provided
770770
*/
771-
private String getResponseMimeType(HttpResponse response) throws ApiException {
771+
protected String getResponseMimeType(HttpResponse response) throws ApiException {
772772
Header contentTypeHeader = response.getFirstHeader("Content-Type");
773773
if (contentTypeHeader != null) {
774774
return getContentType(contentTypeHeader.getValue()).getMimeType();
@@ -877,7 +877,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
877877
}
878878
}
879879

880-
private File downloadFileFromResponse(CloseableHttpResponse response) throws IOException {
880+
protected File downloadFileFromResponse(CloseableHttpResponse response) throws IOException {
881881
Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
882882
String contentDisposition = contentDispositionHeader == null ? null : contentDispositionHeader.getValue();
883883
File file = prepareDownloadFile(contentDisposition);
@@ -948,7 +948,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
948948
* @param urlQueryDeepObject URL query string of the deep object parameters
949949
* @return The full URL
950950
*/
951-
private String buildUrl(String path, List<Pair> queryParams, List<Pair> collectionQueryParams, String urlQueryDeepObject) {
951+
protected String buildUrl(String path, List<Pair> queryParams, List<Pair> collectionQueryParams, String urlQueryDeepObject) {
952952
String baseURL = getBaseURL();
953953
954954
final StringBuilder url = new StringBuilder();
@@ -1127,7 +1127,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
11271127
* @param headerParams Header parameters
11281128
* @param cookieParams Cookie parameters
11291129
*/
1130-
private void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) {
1130+
protected void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) {
11311131
for (String authName : authNames) {
11321132
Authentication auth = authentications.get(authName);
11331133
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);

modules/openapi-generator/src/main/resources/Java/libraries/feign/ApiClient.mustache

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -54,16 +54,16 @@ import feign.Retryer;
5454

5555
{{>generatedAnnotation}}
5656
public class ApiClient {
57-
private static final Logger log = Logger.getLogger(ApiClient.class.getName());
57+
protected static final Logger log = Logger.getLogger(ApiClient.class.getName());
5858
5959
public interface Api {}
6060

6161
{{#jackson}}
6262
protected ObjectMapper objectMapper;
6363
{{/jackson}}
64-
private String basePath = "{{{basePath}}}";
65-
private Map<String, RequestInterceptor> apiAuthorizations;
66-
private Feign.Builder feignBuilder;
64+
protected String basePath = "{{{basePath}}}";
65+
protected Map<String, RequestInterceptor> apiAuthorizations;
66+
protected Feign.Builder feignBuilder;
6767

6868
public ApiClient() {
6969
apiAuthorizations = new LinkedHashMap<String, RequestInterceptor>();
@@ -167,7 +167,7 @@ public class ApiClient {
167167
}
168168

169169
{{#jackson}}
170-
private ObjectMapper createObjectMapper() {
170+
protected ObjectMapper createObjectMapper() {
171171
ObjectMapper objectMapper = new ObjectMapper();
172172
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
173173
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
@@ -194,7 +194,7 @@ public class ApiClient {
194194
{{/jackson}}
195195

196196
{{#hasOAuthMethods}}
197-
private RequestInterceptor buildOauthRequestInterceptor(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
197+
protected RequestInterceptor buildOauthRequestInterceptor(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) {
198198
switch (flow) {
199199
case PASSWORD:
200200
return new OauthPasswordGrant(tokenUrl, scopes);
@@ -375,7 +375,7 @@ public class ApiClient {
375375
feignBuilder.requestInterceptor(authorization);
376376
}
377377

378-
private <T extends RequestInterceptor> T getAuthorization(Class<T> type) {
378+
protected <T extends RequestInterceptor> T getAuthorization(Class<T> type) {
379379
return (T) apiAuthorizations.values()
380380
.stream()
381381
.filter(requestInterceptor -> type.isAssignableFrom(requestInterceptor.getClass()))

modules/openapi-generator/src/main/resources/Java/libraries/google-api-client/ApiClient.mustache

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,14 @@ import java.io.OutputStream;
2525

2626
{{>generatedAnnotation}}
2727
public class ApiClient {
28-
private final String basePath;
29-
private final HttpRequestFactory httpRequestFactory;
30-
private final ObjectMapper objectMapper;
28+
protected final String basePath;
29+
protected final HttpRequestFactory httpRequestFactory;
30+
protected final ObjectMapper objectMapper;
3131
32-
private static final String defaultBasePath = "{{basePath}}";
32+
protected static final String defaultBasePath = "{{basePath}}";
3333
3434
// A reasonable default object mapper. Client can pass in a chosen ObjectMapper anyway, this is just for reasonable defaults.
35-
private static ObjectMapper createDefaultObjectMapper() {
35+
protected static ObjectMapper createDefaultObjectMapper() {
3636
ObjectMapper objectMapper = new ObjectMapper()
3737
{{#failOnUnknownProperties}}
3838
.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
@@ -84,7 +84,7 @@ public class ApiClient {
8484

8585
public class JacksonJsonHttpContent extends AbstractHttpContent {
8686
/* A POJO that can be serialized with a com.fasterxml Jackson ObjectMapper */
87-
private final Object data;
87+
protected final Object data;
8888
8989
public JacksonJsonHttpContent(Object data) {
9090
super(Json.MEDIA_TYPE);

modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -85,13 +85,13 @@ import {{invokerPackage}}.auth.OAuth;
8585
*/
8686
{{>generatedAnnotation}}
8787
public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
88-
private static final Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$");
88+
protected static final Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$");
8989
9090
protected Map<String, String> defaultHeaderMap = new HashMap<>();
9191
protected Map<String, String> defaultCookieMap = new HashMap<>();
9292
protected String basePath = "{{{basePath}}}";
9393
protected String userAgent;
94-
private static final Logger log = Logger.getLogger(ApiClient.class.getName());
94+
protected static final Logger log = Logger.getLogger(ApiClient.class.getName());
9595
9696
protected List<ServerConfiguration> servers = new ArrayList<>({{#servers}}{{#-first}}Arrays.asList(
9797
{{/-first}} new ServerConfiguration(
@@ -175,7 +175,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
175175
protected boolean debugging = false;
176176
protected ClientConfig clientConfig;
177177
protected int connectionTimeout = 0;
178-
private int readTimeout = 0;
178+
protected int readTimeout = 0;
179179

180180
protected Client httpClient;
181181
protected JSON json;
@@ -373,14 +373,14 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
373373
return this;
374374
}
375375

376-
private void updateBasePath() {
376+
protected void updateBasePath() {
377377
if (serverIndex != null) {
378378
setBasePath(servers.get(serverIndex).URL(serverVariables));
379379
}
380380
}
381381

382382
{{#hasOAuthMethods}}
383-
private void setOauthBasePath(String basePath) {
383+
protected void setOauthBasePath(String basePath) {
384384
for(Authentication auth : authentications.values()) {
385385
if (auth instanceof OAuth) {
386386
((OAuth) auth).setBasePath(basePath);
@@ -1029,7 +1029,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
10291029
* @param key Key of the object
10301030
* @param multiPart MultiPart to add the form param to
10311031
*/
1032-
private void addParamToMultipart(Object value, String key, MultiPart multiPart) {
1032+
protected void addParamToMultipart(Object value, String key, MultiPart multiPart) {
10331033
if (value instanceof File) {
10341034
File file = (File) value;
10351035
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key)
@@ -1350,7 +1350,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
13501350
}
13511351
}
13521352

1353-
private Response sendRequest(String method, Invocation.Builder invocationBuilder, Entity<?> entity) {
1353+
protected Response sendRequest(String method, Invocation.Builder invocationBuilder, Entity<?> entity) {
13541354
Response response;
13551355
if ("POST".equals(method)) {
13561356
response = invocationBuilder.post(entity);
@@ -1412,7 +1412,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
14121412
return clientConfig;
14131413
}
14141414

1415-
private void applyDebugSetting(ClientConfig clientConfig) {
1415+
protected void applyDebugSetting(ClientConfig clientConfig) {
14161416
if (debugging) {
14171417
clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */));
14181418
clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY);

modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -85,13 +85,13 @@ import {{invokerPackage}}.auth.OAuth;
8585
*/
8686
{{>generatedAnnotation}}
8787
public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
88-
private static final Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$");
88+
protected static final Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$");
8989
9090
protected Map<String, String> defaultHeaderMap = new HashMap<>();
9191
protected Map<String, String> defaultCookieMap = new HashMap<>();
9292
protected String basePath = "{{{basePath}}}";
9393
protected String userAgent;
94-
private static final Logger log = Logger.getLogger(ApiClient.class.getName());
94+
protected static final Logger log = Logger.getLogger(ApiClient.class.getName());
9595
9696
protected List<ServerConfiguration> servers = new ArrayList<>({{#servers}}{{#-first}}Arrays.asList(
9797
{{/-first}} new ServerConfiguration(
@@ -175,7 +175,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
175175
protected boolean debugging = false;
176176
protected ClientConfig clientConfig;
177177
protected int connectionTimeout = 0;
178-
private int readTimeout = 0;
178+
protected int readTimeout = 0;
179179

180180
protected Client httpClient;
181181
protected JSON json;
@@ -373,14 +373,14 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
373373
return this;
374374
}
375375

376-
private void updateBasePath() {
376+
protected void updateBasePath() {
377377
if (serverIndex != null) {
378378
setBasePath(servers.get(serverIndex).URL(serverVariables));
379379
}
380380
}
381381

382382
{{#hasOAuthMethods}}
383-
private void setOauthBasePath(String basePath) {
383+
protected void setOauthBasePath(String basePath) {
384384
for(Authentication auth : authentications.values()) {
385385
if (auth instanceof OAuth) {
386386
((OAuth) auth).setBasePath(basePath);
@@ -1029,7 +1029,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
10291029
* @param key Key of the object
10301030
* @param multiPart MultiPart to add the form param to
10311031
*/
1032-
private void addParamToMultipart(Object value, String key, MultiPart multiPart) {
1032+
protected void addParamToMultipart(Object value, String key, MultiPart multiPart) {
10331033
if (value instanceof File) {
10341034
File file = (File) value;
10351035
FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key)
@@ -1350,7 +1350,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
13501350
}
13511351
}
13521352

1353-
private Response sendRequest(String method, Invocation.Builder invocationBuilder, Entity<?> entity) {
1353+
protected Response sendRequest(String method, Invocation.Builder invocationBuilder, Entity<?> entity) {
13541354
Response response;
13551355
if ("POST".equals(method)) {
13561356
response = invocationBuilder.post(entity);
@@ -1412,7 +1412,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} {
14121412
return clientConfig;
14131413
}
14141414

1415-
private void applyDebugSetting(ClientConfig clientConfig) {
1415+
protected void applyDebugSetting(ClientConfig clientConfig) {
14161416
if (debugging) {
14171417
clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */));
14181418
clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY);

0 commit comments

Comments
 (0)