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

     1  package {{invokerPackage}};
     2  
     3  import okhttp3.*;
     4  import okio.Buffer;
     5  import okio.BufferedSource;
     6  import play.libs.F;
     7  import play.libs.ws.WSClient;
     8  import play.libs.ws.WSRequest;
     9  import play.libs.ws.WSResponse;
    10  import play.libs.ws.WSCookie;
    11  
    12  import java.io.IOException;
    13  import java.net.MalformedURLException;
    14  import java.net.URI;
    15  import java.net.URISyntaxException;
    16  import java.util.ArrayList;
    17  import java.util.HashMap;
    18  import java.util.List;
    19  import java.util.Map;
    20  import java.util.Optional;
    21  
    22  /**
    23   * Creates {@link Call} instances that invoke underlying {@link WSClient}
    24   */
    25  public class Play24CallFactory implements okhttp3.Call.Factory {
    26  
    27      /** PlayWS http client */
    28      private final WSClient wsClient;
    29  
    30      /** Extra headers to add to request */
    31      private Map<String, String> extraHeaders = new HashMap<>();
    32  
    33      /** Extra cookies to add to request */
    34      private Map<String, String> extraCookies = new HashMap<>();
    35  
    36      /** Extra query parameters to add to request */
    37      private List<Pair> extraQueryParams = new ArrayList<>();
    38  
    39      public Play24CallFactory(WSClient wsClient) {
    40          this.wsClient = wsClient;
    41      }
    42  
    43      public Play24CallFactory(WSClient wsClient, Map<String, String> extraHeaders,
    44          Map<String, String> extraCookies,
    45          List<Pair> extraQueryParams) {
    46          this.wsClient = wsClient;
    47  
    48          this.extraHeaders.putAll(extraHeaders);
    49          this.extraCookies.putAll(extraCookies);
    50          this.extraQueryParams.addAll(extraQueryParams);
    51      }
    52  
    53      @Override
    54      public Call newCall(Request request) {
    55          // add extra headers
    56          Request.Builder rb = request.newBuilder();
    57          for (Map.Entry<String, String> header : this.extraHeaders.entrySet()) {
    58              rb.addHeader(header.getKey(), header.getValue());
    59          }
    60          for (Map.Entry<String, String> cookie : this.extraCookies.entrySet()) {
    61              rb.addHeader("Cookie", String.format("%s=%s", cookie.getKey(), cookie.getValue()));
    62          }
    63  
    64          // add extra query params
    65          if (!this.extraQueryParams.isEmpty()) {
    66              String newQuery = request.url().uri().getQuery();
    67              for (Pair queryParam : this.extraQueryParams) {
    68                  String param = String.format("%s=%s", queryParam.getName(), queryParam.getValue());
    69                  if (newQuery == null) {
    70                      newQuery = param;
    71                  } else {
    72                      newQuery += "&" + param;
    73                  }
    74              }
    75  
    76              URI newUri;
    77              try {
    78                  newUri = new URI(request.url().uri().getScheme(), request.url().uri().getAuthority(),
    79                          request.url().uri().getPath(), newQuery, request.url().uri().getFragment());
    80                  rb.url(newUri.toURL());
    81              } catch (MalformedURLException | URISyntaxException e) {
    82                  throw new RuntimeException("Error while updating an url", e);
    83              }
    84          }
    85  
    86          return new PlayWSCall(wsClient, rb.build());
    87      }
    88  
    89      /**
    90       * Call implementation that delegates to Play WS Client
    91       */
    92      static class PlayWSCall implements Call {
    93  
    94          private final WSClient wsClient;
    95          private WSRequest wsRequest;
    96  
    97          private final Request request;
    98  
    99          public PlayWSCall(WSClient wsClient, Request request) {
   100              this.wsClient = wsClient;
   101              this.request = request;
   102          }
   103  
   104          @Override
   105          public Request request() {
   106              return request;
   107          }
   108  
   109          @Override
   110          public void enqueue(final okhttp3.Callback responseCallback) {
   111              final Call call = this;
   112              final F.Promise<WSResponse> promise = executeAsync();
   113  
   114              promise.onRedeem(new F.Callback<WSResponse>() {
   115  
   116                  @Override
   117                  public void invoke(WSResponse wsResponse) throws Throwable {
   118                      responseCallback.onResponse(call, PlayWSCall.this.toWSResponse(wsResponse));
   119                  }
   120  
   121              });
   122  
   123              promise.onFailure(new F.Callback<Throwable>() {
   124  
   125                  @Override
   126                  public void invoke(Throwable throwable) throws Throwable {
   127                      if (throwable instanceof IOException) {
   128                          responseCallback.onFailure(call, (IOException) throwable);
   129                      } else {
   130                          responseCallback.onFailure(call, new IOException(throwable));
   131                      }
   132                  }
   133  
   134              });
   135  
   136          }
   137  
   138          F.Promise<WSResponse> executeAsync() {
   139              try {
   140                  wsRequest = wsClient.url(request.url().uri().toString());
   141                  addHeaders(wsRequest);
   142                  addCookies(wsRequest);
   143                  if (request.body() != null) {
   144                      addBody(wsRequest);
   145                  }
   146  
   147                  return wsRequest.execute(request.method());
   148              } catch (Exception e) {
   149                  throw new RuntimeException(e.getMessage(), e);
   150              }
   151          }
   152  
   153          private void addHeaders(WSRequest wsRequest) {
   154              for(Map.Entry<String, List<String>> entry : request.headers().toMultimap().entrySet()) {
   155                  List<String> values = entry.getValue();
   156                  for (String value : values) {
   157                      wsRequest.setHeader(entry.getKey(), value);
   158                  }
   159              }
   160          }
   161  
   162          private void addCookies(WSRequest wsRequest) {
   163              final List<String> cookies = request.headers("Cookie");
   164              if (!cookies.isEmpty()) {
   165                  String delimiter = "";
   166                  final StringBuilder cookieHeader = new StringBuilder();
   167                  for (final String cookie : cookies) {
   168                      cookieHeader.append(String.format("%s%s", delimiter, cookie));
   169                      delimiter = "; ";
   170                  }
   171                  wsRequest.setHeader("Cookie", cookieHeader.toString());
   172              }
   173          }
   174  
   175          private void addBody(WSRequest wsRequest) throws IOException {
   176              Buffer buffer = new Buffer();
   177              request.body().writeTo(buffer);
   178              wsRequest.setBody(buffer.inputStream());
   179              wsRequest.setContentType(request.body().contentType().toString());
   180          }
   181  
   182          private Response toWSResponse(final WSResponse r) {
   183              final Response.Builder builder = new Response.Builder();
   184              builder.request(request)
   185                     .code(r.getStatus())
   186                     .body(new ResponseBody() {
   187  
   188                         @Override
   189                         public MediaType contentType() {
   190                             return Optional.ofNullable(r.getHeader("Content-Type"))
   191                                            .map(MediaType::parse)
   192                                            .orElse(null);
   193                         }
   194  
   195                         @Override
   196                         public long contentLength() {
   197                             return r.asByteArray().length;
   198                         }
   199  
   200                         @Override
   201                         public BufferedSource source() {
   202                             return new Buffer().write(r.asByteArray());
   203                         }
   204  
   205                     });
   206  
   207              for (Map.Entry<String, List<String>> entry : r.getAllHeaders().entrySet()) {
   208                  for (String value : entry.getValue()) {
   209                      builder.addHeader(entry.getKey(), value);
   210                  }
   211              }
   212              for (final WSCookie cookie : r.getCookies()) {
   213                  builder.addHeader("Cookie", String.format("%s=%s", cookie.getName(), cookie.getValue()));
   214              }
   215  
   216              builder.protocol(Protocol.HTTP_1_1);
   217              return builder.build();
   218          }
   219  
   220          @Override
   221          public Response execute() throws IOException {
   222              throw new UnsupportedOperationException("Not supported");
   223          }
   224  
   225          @Override
   226          public void cancel() {
   227              throw new UnsupportedOperationException("Not supported");
   228          }
   229  
   230          @Override
   231          public PlayWSCall clone() {
   232              throw new UnsupportedOperationException("Not supported");
   233          }
   234  
   235          @Override
   236          public boolean isExecuted() {
   237              return false;
   238          }
   239  
   240          @Override
   241          public boolean isCanceled() {
   242              return false;
   243          }
   244      }
   245  }