Post prefetch request

@param request The request containing all of the URLs to be prefetched.
@return Result of the prefetch operation returned by the service.
421905
public PrefetchResponse prefetch(PrefetchRequest request) {
        InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST, CACHE, "prefetch");
        this.attachRequestToBody(request, internalRequest);
        return this.invokeHttpClient(internalRequest, PrefetchResponse.class);
    }
770519
private void addPostParams(final Request request) {
        if (data != null) {
            request.addPostParam("Data", Converter.mapToJson(data));
        }

        if (ttl != null) {
            request.addPostParam("Ttl", ttl.toString());
        }

        if (itemTtl != null) {
            request.addPostParam("ItemTtl", itemTtl.toString());
        }

        if (collectionTtl != null) {
            request.addPostParam("CollectionTtl", collectionTtl.toString());
        }
    }
659230
private void addPostParams(final Request request) {
        if (to != null) {
            request.addPostParam("To", to.toString());
        }

        if (from != null) {
            request.addPostParam("From", from.toString());
        }

        if (parameters != null) {
            request.addPostParam("Parameters", Converter.mapToJson(parameters));
        }
    }
1133947
private void addPostParams(final Request request) {
        if (code != null) {
            request.addPostParam("Code", code);
        }

        if (to != null) {
            request.addPostParam("To", to);
        }
    }
340667
private CompletableFuture<PrimaryBackupServiceContext> getService(PrimitiveRequest request) {
    return services.computeIfAbsent(request.primitive().name(), n -> {
      PrimitiveType primitiveType = primitiveTypes.getPrimitiveType(request.primitive().type());
      PrimaryBackupServiceContext service = new PrimaryBackupServiceContext(
          serverName,
          PrimitiveId.from(request.primitive().name()),
          primitiveType,
          request.primitive(),
          threadContextFactory.createContext(),
          clusterMembershipService,
          memberGroupService,
          protocol,
          primaryElection);

      OrderedFuture<PrimaryBackupServiceContext> newOrderFuture = new OrderedFuture<>();
      service.open().whenComplete((v, e) -> {
        if (e != null) {
          newOrderFuture.completeExceptionally(e);
        } else {
          newOrderFuture.complete(service);
        }
      });
      return newOrderFuture;
    });
  }
359833
public Response api(Request request) throws IOException {
    Request req = new Request();
    req.setMethod(request.getMethod());
    req.setBaseUri(this.host);
    req.setEndpoint("/" + version + "/" + request.getEndpoint());
    req.setBody(request.getBody());
    for (Map.Entry<String, String> header : this.requestHeaders.entrySet()) {
      req.addHeader(header.getKey(), header.getValue());
    }
    for (Map.Entry<String, String> queryParam : request.getQueryParams().entrySet()) {
      req.addQueryParam(queryParam.getKey(), queryParam.getValue());
    }

    return makeCall(req);
  }
1285478
private static void request(final Request request) {
        if (null == request) {
            WonderPush.logError("Request with null request.");
            return;
        }

        WonderPush.safeDefer(new Runnable() {
            @Override
            public void run() {
                // Decorate parameters
                WonderPushRequestParamsDecorator.decorate(request.getResource(), request.getParams());

                // Generate signature
                BasicHeader authorizationHeader = request.getAuthorizationHeader();

                // Headers
                BasicHeader[] headers = null;
                if (null != authorizationHeader) {
                    headers = new BasicHeader[1];
                    headers[0] = authorizationHeader;
                }

                String url = WonderPushUriHelper.getAbsoluteUrl(request.getResource());
                WonderPush.logDebug("requesting url: " + request.getMethod() + " " + url + "?" + request.getParams().getURLEncodedString());
                // TODO: support other contentTypes such as "application/json"
                String contentType = "application/x-www-form-urlencoded";

                // Handler
                final ResponseHandler handler = request.getHandler();
                HttpEntity entity = null;
                if (request.getParams() != null) {
                    try {
                        entity = request.getParams() != null ? request.getParams().getEntity(null) : null;
                    } catch (IOException ex) {
                        WonderPush.logError("Failed to create HttpEntity from params " + request.getParams(), ex);
                        if (handler != null) {
                            handler.onFailure(ex, new Response(""));
                        }
                        return;
                    }
                }
                final long sendDate = SystemClock.elapsedRealtime();
                JsonHttpResponseHandler jsonHandler = new JsonHttpResponseHandler() {
                    @Override
                    public void onProgress(long bytesWritten, long totalSize) {
                        // mute this
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        syncTime(response);
                        WonderPush.setNetworkAvailable(true);
                        if (handler != null) {
                            handler.onSuccess(statusCode, new Response(response));
                        }
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                        WonderPush.logError("Unexpected JSONArray answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + response.length() + ") " + response.toString());
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        WonderPush.logError("Error answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: " + errorResponse);
                        syncTime(errorResponse);
                        WonderPush.logDebug("Request Error: " + errorResponse);
                        WonderPush.setNetworkAvailable(errorResponse != null);
                        if (handler != null) {
                            handler.onFailure(throwable, new Response(errorResponse));
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                        WonderPush.logError("Unexpected JSONArray error answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + errorResponse.length() + ") " + errorResponse.toString());
                        this.onFailure(statusCode, headers, errorResponse.toString(), throwable);
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        WonderPush.logError("Unexpected string error answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + responseString.length() + ") \"" + responseString + "\"");
                        WonderPush.setNetworkAvailable(false);
                        if (handler != null) {
                            handler.onFailure(throwable, new Response(responseString));
                        }
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String responseString) {
                        WonderPush.logError("Unexpected string answer: " + statusCode + " headers: " + Arrays.toString(headers) + " response: (" + responseString.length() + ") \"" + responseString + "\"");
                    }

                    private void syncTime(JSONObject data) {
                        long recvDate = SystemClock.elapsedRealtime();
                        if (data == null || !data.has("_serverTime")) {
                            return;
                        }
                        TimeSync.syncTimeWithServer(sendDate, recvDate, data.optLong("_serverTime"), data.optLong("_serverTook"));
                    }
                };
                // NO UNNECESSARY WORK HERE, because of timed request
                switch (request.getMethod()) {
                    case GET:
                        sClient.get(null, url, headers, request.getParams(), jsonHandler);
                        break;
                    case PUT:
                        sClient.put(null, url, headers, entity, contentType, jsonHandler);
                        break;
                    case POST:
                        sClient.post(null, url, headers, entity, contentType, jsonHandler);
                        break;
                    case PATCH:
                        sClient.patch(null, url, headers, entity, contentType, jsonHandler);
                        break;
                    case DELETE:
                        sClient.delete(null, url, headers, request.getParams(), jsonHandler);
                        break;
                    default:
                        jsonHandler.sendFailureMessage(0, null, null, new UnsupportedOperationException("Unhandled method " + request.getMethod()));
                }
            }
        }, 0);
    }
654709
public static CmsContentDefinition prefetch(HttpServletRequest request) throws CmsRpcException {

        CmsContentService srv = new CmsContentService();
        srv.setCms(CmsFlexController.getCmsObject(request));
        srv.setRequest(request);
        CmsContentDefinition result = null;
        try {
            result = srv.prefetch();
        } finally {
            srv.clearThreadStorage();
        }
        return result;
    }
74749
protected <T> Response<T> doPost(Request<T> request) {
		String payload = RequestUtil.getRequestPayload(request);
		URI uri = buidURI(request);

		Timer timer = Timer.tic();
		TransportResult result = getApiClientTransportFactory().newTransport(api).doPost(uri, payload);
		timer.toc();

		log.trace(result.getStatusCode() + " " + uri.toString() + " took " + timer.getDifference() + "ms");

		Response<T> response = toResponse(timer, result, request);

		return response;
	}
441382
protected <T extends Request, U extends Response> CompletableFuture<U> forward(T request) {
    CompletableFuture<U> future = new CompletableFuture<>();
    context.getConnections().getConnection(context.getLeader().serverAddress()).whenComplete((connection, connectError) -> {
      if (connectError == null) {
        connection.<T, U>sendAndReceive(request).whenComplete((response, responseError) -> {
          if (responseError == null) {
            future.complete(response);
          } else {
            future.completeExceptionally(responseError);
          }
        });
      } else {
        future.completeExceptionally(connectError);
      }
    });
    return future;
  }
315217
public GetPrefetchStatusResponse getPrefetchStatus(GetPrefetchStatusRequest request) {
        InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, CACHE, "prefetch");
        if (request.getId() != null) {
            internalRequest.addParameter("id", request.getId());
        }

        if (request.getStartTime() != null) {
            internalRequest.addParameter("startTime", DateUtils.formatAlternateIso8601Date(request.getStartTime()));
        }

        if (request.getEndTime() != null) {
            internalRequest.addParameter("endTime", DateUtils.formatAlternateIso8601Date(request.getEndTime()));
        }

        if (request.getMarker() != null) {
            internalRequest.addParameter("marker", request.getMarker());
        }

        if (request.getUrl() != null) {
            internalRequest.addParameter("url", request.getUrl());
        }

        return this.invokeHttpClient(internalRequest, GetPrefetchStatusResponse.class);
    }
1263085
private void addPostParams(final Request request) {
        if (data != null) {
            request.addPostParam("Data", Converter.mapToJson(data));
        }
    }
523334
private void addPostParams(final Request request) {
        if (binding != null) {
            request.addPostParam("Binding", binding);
        }

        if (friendlyName != null) {
            request.addPostParam("FriendlyName", friendlyName);
        }

        if (factorType != null) {
            request.addPostParam("FactorType", factorType.toString());
        }
    }
638944
protected <T extends HttpRequestBase> T createHttpRequest(Q request) {
    T httpRequest = createHttpRequestBase(request);

    applyHeaders(httpRequest, request.getHeaders());

    applyPayload(httpRequest, request);

    return httpRequest;
  }
117029
protected boolean includeRequest(HttpServletRequest request) {
        if (ArrayUtils.isNotEmpty(urlsToInclude)) {
            for (String pathPattern : urlsToInclude) {
                if (pathMatcher.match(pathPattern, HttpUtils.getRequestUriWithoutContextPath(request))) {
                    return true;
                }
            }
        }

        return false;
    }
1146951
public ListPresetsResponse listPresets(ListPresetsRequest request) {
        checkNotNull(request, "The parameter request should NOT be null.");
        InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, PRESET);
        return invokeHttpClient(internalRequest, ListPresetsResponse.class);
    }
1019164
public Response makeRequest(final Request request) {

        HttpMethod method = request.getMethod();
        RequestBuilder builder = RequestBuilder.create(method.toString())
            .setUri(request.constructURL().toString())
            .setVersion(HttpVersion.HTTP_1_1)
            .setCharset(StandardCharsets.UTF_8);

        if (request.requiresAuthentication()) {
            builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString());
        }

        if (method == HttpMethod.POST) {
            builder.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

            for (Map.Entry<String, List<String>> entry : request.getPostParams().entrySet()) {
                for (String value : entry.getValue()) {
                    builder.addParameter(entry.getKey(), value);
                }
            }
        }

        HttpResponse response = null;

        try {
            response = client.execute(builder.build());
            HttpEntity entity = response.getEntity();
            return new Response(
                // Consume the entire HTTP response before returning the stream
                entity == null ? null : new BufferedHttpEntity(entity).getContent(),
                response.getStatusLine().getStatusCode()
            );
        } catch (IOException e) {
            throw new ApiException(e.getMessage(), e);
        } finally {

            // Ensure this response is properly closed
            HttpClientUtils.closeQuietly(response);

        }

    }