github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/java/libraries/retrofit2/ApiClient.mustache (about) 1 package {{invokerPackage}}; 2 3 import com.google.gson.Gson; 4 import com.google.gson.JsonParseException; 5 import com.google.gson.JsonElement; 6 import okhttp3.Interceptor; 7 import okhttp3.OkHttpClient; 8 import okhttp3.RequestBody; 9 import okhttp3.ResponseBody; 10 {{#hasOAuthMethods}} 11 import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; 12 import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; 13 {{/hasOAuthMethods}} 14 {{#joda}} 15 import org.joda.time.format.DateTimeFormatter; 16 {{/joda}} 17 {{#threetenbp}} 18 import org.threeten.bp.format.DateTimeFormatter; 19 {{/threetenbp}} 20 import retrofit2.Converter; 21 import retrofit2.Retrofit; 22 {{#useRxJava}} 23 import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; 24 {{/useRxJava}} 25 {{#useRxJava2}} 26 import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; 27 {{/useRxJava2}} 28 import retrofit2.converter.gson.GsonConverterFactory; 29 import retrofit2.converter.scalars.ScalarsConverterFactory; 30 import {{invokerPackage}}.auth.HttpBasicAuth; 31 import {{invokerPackage}}.auth.HttpBearerAuth; 32 import {{invokerPackage}}.auth.ApiKeyAuth; 33 {{#hasOAuthMethods}} 34 import {{invokerPackage}}.auth.OAuth; 35 import {{invokerPackage}}.auth.OAuth.AccessTokenListener; 36 import {{invokerPackage}}.auth.OAuthFlow; 37 {{/hasOAuthMethods}} 38 39 import java.io.IOException; 40 import java.lang.annotation.Annotation; 41 import java.lang.reflect.Type; 42 import java.text.DateFormat; 43 {{#java8}} 44 import java.time.format.DateTimeFormatter; 45 {{/java8}} 46 import java.util.LinkedHashMap; 47 import java.util.Map; 48 import java.util.HashMap; 49 50 public class ApiClient { 51 52 private Map<String, Interceptor> apiAuthorizations; 53 private OkHttpClient.Builder okBuilder; 54 private Retrofit.Builder adapterBuilder; 55 private JSON json; 56 57 public ApiClient() { 58 apiAuthorizations = new LinkedHashMap<String, Interceptor>(); 59 createDefaultAdapter(); 60 } 61 62 public ApiClient(String[] authNames) { 63 this(); 64 for(String authName : authNames) { 65 {{#hasAuthMethods}} 66 Interceptor auth; 67 {{#authMethods}}if ("{{name}}".equals(authName)) { 68 {{#isBasic}}{{#isBasicBasic}} 69 auth = new HttpBasicAuth(); 70 {{/isBasicBasic}}{{^isBasicBasic}} 71 auth = new HttpBearerAuth("{{scheme}}"); 72 {{/isBasicBasic}}{{/isBasic}} 73 {{#isApiKey}} 74 auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"); 75 {{/isApiKey}} 76 {{#isOAuth}} 77 auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{^-last}}, {{/-last}}{{/scopes}}"); 78 {{/isOAuth}} 79 } else {{/authMethods}}{ 80 throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); 81 } 82 83 addAuthorization(authName, auth); 84 {{/hasAuthMethods}} 85 {{^hasAuthMethods}} 86 throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); 87 {{/hasAuthMethods}} 88 } 89 } 90 91 /** 92 * Basic constructor for single auth name 93 * @param authName Authentication name 94 */ 95 public ApiClient(String authName) { 96 this(new String[]{authName}); 97 } 98 99 /** 100 * Helper constructor for single api key 101 * @param authName Authentication name 102 * @param apiKey API key 103 */ 104 public ApiClient(String authName, String apiKey) { 105 this(authName); 106 this.setApiKey(apiKey); 107 } 108 109 /** 110 * Helper constructor for single basic auth or password oauth2 111 * @param authName Authentication name 112 * @param username Username 113 * @param password Password 114 */ 115 public ApiClient(String authName, String username, String password) { 116 this(authName); 117 this.setCredentials(username, password); 118 } 119 120 {{#hasOAuthMethods}} 121 /** 122 * Helper constructor for single password oauth2 123 * @param authName Authentication name 124 * @param clientId Client ID 125 * @param secret Client Secret 126 * @param username Username 127 * @param password Password 128 */ 129 public ApiClient(String authName, String clientId, String secret, String username, String password) { 130 this(authName); 131 this.getTokenEndPoint() 132 .setClientId(clientId) 133 .setClientSecret(secret) 134 .setUsername(username) 135 .setPassword(password); 136 } 137 138 {{/hasOAuthMethods}} 139 public void createDefaultAdapter() { 140 json = new JSON(); 141 okBuilder = new OkHttpClient.Builder(); 142 143 String baseUrl = "{{{basePath}}}"; 144 if (!baseUrl.endsWith("/")) 145 baseUrl = baseUrl + "/"; 146 147 adapterBuilder = new Retrofit 148 .Builder() 149 .baseUrl(baseUrl) 150 {{#useRxJava}} 151 .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) 152 {{/useRxJava}}{{#useRxJava2}} 153 .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) 154 {{/useRxJava2}} 155 .addConverterFactory(ScalarsConverterFactory.create()) 156 .addConverterFactory(GsonCustomConverterFactory.create(json.getGson())); 157 } 158 159 public <S> S createService(Class<S> serviceClass) { 160 return adapterBuilder 161 .client(okBuilder.build()) 162 .build() 163 .create(serviceClass); 164 } 165 166 public ApiClient setDateFormat(DateFormat dateFormat) { 167 this.json.setDateFormat(dateFormat); 168 return this; 169 } 170 171 public ApiClient setSqlDateFormat(DateFormat dateFormat) { 172 this.json.setSqlDateFormat(dateFormat); 173 return this; 174 } 175 176 {{#joda}} 177 public ApiClient setDateTimeFormat(DateTimeFormatter dateFormat) { 178 this.json.setDateTimeFormat(dateFormat); 179 return this; 180 } 181 182 public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { 183 this.json.setLocalDateFormat(dateFormat); 184 return this; 185 } 186 187 {{/joda}} 188 {{#jsr310}} 189 public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { 190 this.json.setOffsetDateTimeFormat(dateFormat); 191 return this; 192 } 193 194 public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { 195 this.json.setLocalDateFormat(dateFormat); 196 return this; 197 } 198 199 {{/jsr310}} 200 201 /** 202 * Helper method to configure the first api key found 203 * @param apiKey API key 204 * @return ApiClient 205 */ 206 public ApiClient setApiKey(String apiKey) { 207 for(Interceptor apiAuthorization : apiAuthorizations.values()) { 208 if (apiAuthorization instanceof ApiKeyAuth) { 209 ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; 210 keyAuth.setApiKey(apiKey); 211 return this; 212 } 213 } 214 return this; 215 } 216 217 /** 218 * Helper method to set token for the first Http Bearer authentication found. 219 * @param bearerToken Bearer token 220 * @return ApiClient 221 */ 222 public ApiClient setBearerToken(String bearerToken) { 223 for (Interceptor apiAuthorization : apiAuthorizations.values()) { 224 if (apiAuthorization instanceof HttpBearerAuth) { 225 ((HttpBearerAuth) apiAuthorization).setBearerToken(bearerToken); 226 return this; 227 } 228 } 229 return this; 230 } 231 232 /** 233 * Helper method to configure the username/password for basic auth or password oauth 234 * @param username Username 235 * @param password Password 236 * @return ApiClient 237 */ 238 public ApiClient setCredentials(String username, String password) { 239 for(Interceptor apiAuthorization : apiAuthorizations.values()) { 240 if (apiAuthorization instanceof HttpBasicAuth) { 241 HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; 242 basicAuth.setCredentials(username, password); 243 return this; 244 } 245 {{#hasOAuthMethods}} 246 if (apiAuthorization instanceof OAuth) { 247 OAuth oauth = (OAuth) apiAuthorization; 248 oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); 249 return this; 250 } 251 {{/hasOAuthMethods}} 252 } 253 return this; 254 } 255 256 {{#hasOAuthMethods}} 257 /** 258 * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) 259 * @return Token request builder 260 */ 261 public TokenRequestBuilder getTokenEndPoint() { 262 for(Interceptor apiAuthorization : apiAuthorizations.values()) { 263 if (apiAuthorization instanceof OAuth) { 264 OAuth oauth = (OAuth) apiAuthorization; 265 return oauth.getTokenRequestBuilder(); 266 } 267 } 268 return null; 269 } 270 271 /** 272 * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) 273 * @return Authentication request builder 274 */ 275 public AuthenticationRequestBuilder getAuthorizationEndPoint() { 276 for(Interceptor apiAuthorization : apiAuthorizations.values()) { 277 if (apiAuthorization instanceof OAuth) { 278 OAuth oauth = (OAuth) apiAuthorization; 279 return oauth.getAuthenticationRequestBuilder(); 280 } 281 } 282 return null; 283 } 284 285 /** 286 * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) 287 * @param accessToken Access token 288 * @return ApiClient 289 */ 290 public ApiClient setAccessToken(String accessToken) { 291 for(Interceptor apiAuthorization : apiAuthorizations.values()) { 292 if (apiAuthorization instanceof OAuth) { 293 OAuth oauth = (OAuth) apiAuthorization; 294 oauth.setAccessToken(accessToken); 295 return this; 296 } 297 } 298 return this; 299 } 300 301 /** 302 * Helper method to configure the oauth accessCode/implicit flow parameters 303 * @param clientId Client ID 304 * @param clientSecret Client secret 305 * @param redirectURI Redirect URI 306 * @return ApiClient 307 */ 308 public ApiClient configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { 309 for(Interceptor apiAuthorization : apiAuthorizations.values()) { 310 if (apiAuthorization instanceof OAuth) { 311 OAuth oauth = (OAuth) apiAuthorization; 312 oauth.getTokenRequestBuilder() 313 .setClientId(clientId) 314 .setClientSecret(clientSecret) 315 .setRedirectURI(redirectURI); 316 oauth.getAuthenticationRequestBuilder() 317 .setClientId(clientId) 318 .setRedirectURI(redirectURI); 319 return this; 320 } 321 } 322 return this; 323 } 324 325 /** 326 * Configures a listener which is notified when a new access token is received. 327 * @param accessTokenListener Access token listener 328 * @return ApiClient 329 */ 330 public ApiClient registerAccessTokenListener(AccessTokenListener accessTokenListener) { 331 for(Interceptor apiAuthorization : apiAuthorizations.values()) { 332 if (apiAuthorization instanceof OAuth) { 333 OAuth oauth = (OAuth) apiAuthorization; 334 oauth.registerAccessTokenListener(accessTokenListener); 335 return this; 336 } 337 } 338 return this; 339 } 340 {{/hasOAuthMethods}} 341 342 /** 343 * Adds an authorization to be used by the client 344 * @param authName Authentication name 345 * @param authorization Authorization interceptor 346 * @return ApiClient 347 */ 348 public ApiClient addAuthorization(String authName, Interceptor authorization) { 349 if (apiAuthorizations.containsKey(authName)) { 350 throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); 351 } 352 apiAuthorizations.put(authName, authorization); 353 okBuilder.addInterceptor(authorization); 354 return this; 355 } 356 357 public Map<String, Interceptor> getApiAuthorizations() { 358 return apiAuthorizations; 359 } 360 361 public ApiClient setApiAuthorizations(Map<String, Interceptor> apiAuthorizations) { 362 this.apiAuthorizations = apiAuthorizations; 363 return this; 364 } 365 366 public Retrofit.Builder getAdapterBuilder() { 367 return adapterBuilder; 368 } 369 370 public ApiClient setAdapterBuilder(Retrofit.Builder adapterBuilder) { 371 this.adapterBuilder = adapterBuilder; 372 return this; 373 } 374 375 public OkHttpClient.Builder getOkBuilder() { 376 return okBuilder; 377 } 378 379 public void addAuthsToOkBuilder(OkHttpClient.Builder okBuilder) { 380 for(Interceptor apiAuthorization : apiAuthorizations.values()) { 381 okBuilder.addInterceptor(apiAuthorization); 382 } 383 } 384 385 /** 386 * Clones the okBuilder given in parameter, adds the auth interceptors and uses it to configure the Retrofit 387 * @param okClient An instance of OK HTTP client 388 */ 389 public void configureFromOkclient(OkHttpClient okClient) { 390 this.okBuilder = okClient.newBuilder(); 391 addAuthsToOkBuilder(this.okBuilder); 392 } 393 } 394 395 /** 396 * This wrapper is to take care of this case: 397 * when the deserialization fails due to JsonParseException and the 398 * expected type is String, then just return the body string. 399 */ 400 class GsonResponseBodyConverterToString<T> implements Converter<ResponseBody, T> { 401 private final Gson gson; 402 private final Type type; 403 404 GsonResponseBodyConverterToString(Gson gson, Type type) { 405 this.gson = gson; 406 this.type = type; 407 } 408 409 @Override public T convert(ResponseBody value) throws IOException { 410 String returned = value.string(); 411 try { 412 return gson.fromJson(returned, type); 413 } 414 catch (JsonParseException e) { 415 return (T) returned; 416 } 417 } 418 } 419 420 class GsonCustomConverterFactory extends Converter.Factory 421 { 422 private final Gson gson; 423 private final GsonConverterFactory gsonConverterFactory; 424 425 public static GsonCustomConverterFactory create(Gson gson) { 426 return new GsonCustomConverterFactory(gson); 427 } 428 429 private GsonCustomConverterFactory(Gson gson) { 430 if (gson == null) 431 throw new NullPointerException("gson == null"); 432 this.gson = gson; 433 this.gsonConverterFactory = GsonConverterFactory.create(gson); 434 } 435 436 @Override 437 public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { 438 if (type.equals(String.class)) 439 return new GsonResponseBodyConverterToString<Object>(gson, type); 440 else 441 return gsonConverterFactory.responseBodyConverter(type, annotations, retrofit); 442 } 443 444 @Override 445 public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { 446 return gsonConverterFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit); 447 } 448 }