github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/java/libraries/retrofit2/play26/ApiClient.mustache (about)

     1  package {{invokerPackage}};
     2  
     3  import java.io.File;
     4  import java.io.IOException;
     5  import java.lang.annotation.Annotation;
     6  import java.lang.reflect.Type;
     7  import java.nio.file.Files;
     8  import java.nio.file.Paths;
     9  import java.util.*;
    10  
    11  import com.fasterxml.jackson.databind.ObjectMapper;
    12  import retrofit2.Converter;
    13  import retrofit2.Retrofit;
    14  import retrofit2.converter.scalars.ScalarsConverterFactory;
    15  import retrofit2.converter.jackson.JacksonConverterFactory;
    16  import org.openapitools.jackson.nullable.JsonNullableModule;
    17  
    18  import play.libs.Json;
    19  import play.libs.ws.WSClient;
    20  
    21  import {{invokerPackage}}.Play26CallAdapterFactory;
    22  import {{invokerPackage}}.Play26CallFactory;
    23  
    24  import okhttp3.Interceptor;
    25  import okhttp3.ResponseBody;
    26  import {{invokerPackage}}.auth.ApiKeyAuth;
    27  import {{invokerPackage}}.auth.Authentication;
    28  
    29  /**
    30   * API client
    31   */
    32  public class ApiClient {
    33  
    34      /** Underlying HTTP-client */
    35      private WSClient wsClient;
    36  
    37      /** Creates HTTP call instances */
    38      private Play26CallFactory callFactory;
    39  
    40      /** Create {@link java.util.concurrent.CompletionStage} instances from HTTP calls */
    41      private Play26CallAdapterFactory callAdapterFactory;
    42  
    43      /** Supported auths */
    44      private Map<String, Authentication> authentications;
    45  
    46      /** API base path */
    47      private String basePath = "{{{basePath}}}";
    48  
    49      /** Default ObjectMapper */
    50      private ObjectMapper defaultMapper;
    51  
    52      public ApiClient(WSClient wsClient) {
    53          this();
    54          this.wsClient = wsClient;
    55      }
    56  
    57      public ApiClient() {
    58          // Setup authentications (key: authentication name, value: authentication).
    59          authentications = new HashMap<>();{{#authMethods}}{{#isBasic}}
    60          // authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}}
    61          authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
    62          // authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
    63          // Prevent the authentications from being modified.
    64          authentications = Collections.unmodifiableMap(authentications);
    65      }
    66  
    67      /**
    68       * Creates a retrofit2 client for given API interface
    69       */
    70      public <S> S createService(Class<S> serviceClass) {
    71          if(!basePath.endsWith("/")) {
    72              basePath = basePath + "/";
    73          }
    74  
    75          Map<String, String> extraHeaders = new HashMap<>();
    76          Map<String, String> extraCookies = new HashMap<>();
    77          List<Pair> extraQueryParams = new ArrayList<>();
    78  
    79          for (String authName : authentications.keySet()) {
    80              Authentication auth = authentications.get(authName);
    81              if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
    82  
    83              auth.applyToParams(extraQueryParams, extraHeaders, extraCookies);
    84          }
    85  
    86          if (callFactory == null) {
    87              callFactory = new Play26CallFactory(wsClient, extraHeaders, extraCookies, extraQueryParams);
    88          }
    89          if (callAdapterFactory == null) {
    90              callAdapterFactory = new Play26CallAdapterFactory();
    91          }
    92          if (defaultMapper == null) {
    93              defaultMapper = Json.mapper();
    94              JsonNullableModule jnm = new JsonNullableModule();
    95              defaultMapper.registerModule(jnm);
    96          }
    97  
    98          return new Retrofit.Builder()
    99                          .baseUrl(basePath)
   100                          .addConverterFactory(new FileConverter())
   101                          .addConverterFactory(ScalarsConverterFactory.create())
   102                          .addConverterFactory(JacksonConverterFactory.create(defaultMapper))
   103                          .callFactory(callFactory)
   104                          .addCallAdapterFactory(callAdapterFactory)
   105                          .build()
   106                          .create(serviceClass);
   107      }
   108  
   109      /**
   110       * Helper method to set API base path
   111       */
   112      public ApiClient setBasePath(String basePath) {
   113          this.basePath = basePath;
   114          return this;
   115      }
   116  
   117      /**
   118       * Get authentications (key: authentication name, value: authentication).
   119       */
   120      public Map<String, Authentication> getAuthentications() {
   121          return authentications;
   122      }
   123  
   124      /**
   125       * Get authentication for the given name.
   126       *
   127       * @param authName The authentication name
   128       * @return The authentication, null if not found
   129       */
   130      public Authentication getAuthentication(String authName) {
   131          return authentications.get(authName);
   132      }
   133  
   134      /**
   135       * Helper method to set API key value for the first API key authentication.
   136       */
   137      public ApiClient setApiKey(String apiKey) {
   138          for (Authentication auth : authentications.values()) {
   139              if (auth instanceof ApiKeyAuth) {
   140                  ((ApiKeyAuth) auth).setApiKey(apiKey);
   141                  return this;
   142              }
   143          }
   144  
   145          throw new RuntimeException("No API key authentication configured!");
   146      }
   147  
   148      /**
   149       * Helper method to set API key prefix for the first API key authentication.
   150       */
   151      public ApiClient setApiKeyPrefix(String apiKeyPrefix) {
   152          for (Authentication auth : authentications.values()) {
   153              if (auth instanceof ApiKeyAuth) {
   154                  ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
   155                  return this;
   156              }
   157          }
   158  
   159          throw new RuntimeException("No API key authentication configured!");
   160      }
   161  
   162      /**
   163       * Helper method to set HTTP call instances factory
   164       */
   165      public ApiClient setCallFactory(Play26CallFactory callFactory) {
   166          this.callFactory = callFactory;
   167          return this;
   168      }
   169  
   170      /**
   171       * Helper method to set {@link java.util.concurrent.CompletionStage} instances factory
   172       */
   173      public ApiClient setCallAdapterFactory(Play26CallAdapterFactory callAdapterFactory) {
   174          this.callAdapterFactory = callAdapterFactory;
   175          return this;
   176      }
   177  
   178      /**
   179       * Helper method to set Jackson's {@link ObjectMapper}
   180       */
   181      public ApiClient setObjectMapper(ObjectMapper mapper) {
   182          this.defaultMapper = mapper;
   183          return this;
   184      }
   185  
   186      static class FileConverter extends Converter.Factory {
   187  
   188          @Override
   189          public Converter<ResponseBody, File> responseBodyConverter(Type type,
   190                  Annotation[] annotations, Retrofit retrofit) {
   191  
   192              if (!File.class.getTypeName().equals(type.getTypeName())) {
   193                  return null;
   194              }
   195  
   196              return new Converter<ResponseBody, File>() {
   197  
   198                  @Override
   199                  public File convert(ResponseBody value) throws IOException {
   200  
   201                      File file = File.createTempFile("retrofit-file", ".tmp");
   202                      Files.write(Paths.get(file.getPath()), value.bytes());
   203                      return file;
   204                  }
   205              };
   206          }
   207      }
   208  
   209  }