Execute CRX HTTP Package manager method and checks response status. If the response status is not 200 the call
fails (after retrying).
@param httpClient Http client
@param method Get or Post method
176521
public void executePackageManagerMethodStatus(CloseableHttpClient httpClient, HttpRequestBase method) {
    PackageManagerStatusCall call = new PackageManagerStatusCall(httpClient, method, log);
    executeHttpCallWithRetry(call, 0);
  }
331189
private HttpResponse execute( HttpUriRequest request ) throws RestException
    {
        log.debug( ">>>> " + request.getRequestLine() );
        for ( Header header : request.getAllHeaders() )
        {
            log.trace( ">>>> " + header.getName() + ": " + header.getValue() );
        }

        HttpResponse response;
        try
        {
            response = getHttpClient().execute( request );
            log.debug( "<<<< " + response.getStatusLine() );
            for ( Header header : response.getAllHeaders() )
            {
                log.trace( "<<<< " + header.getName() + ": " + header.getValue() );
            }

            if ( response.getStatusLine().getStatusCode() == 204 )
            {
                log.debug( "Consuming quietly the response entity since server returned no content" );
                EntityUtils.consumeQuietly( response.getEntity() );
            }

            checkError( response );
            return response;
        }
        catch ( KeyManagementException | NoSuchAlgorithmException | IOException e )
        {
            throw new RuntimeRestException( e );
        }
        finally
        {
            // https://issues.apache.org/jira/browse/HTTPCLIENT-1523
            DateUtils.clearThreadLocal();
        }
    }
846915
protected void receiveClientResponse(HttpMessage response) {
        runner.http(action -> {
            HttpClientResponseActionBuilder responseBuilder = action.client(httpClient).receive()
                .response(response.getStatusCode())
                .message(response);

            for (Map.Entry<String, String> headerEntry : pathValidations.entrySet()) {
                responseBuilder.validate(headerEntry.getKey(), headerEntry.getValue());
            }
            pathValidations.clear();
        });
    }
289152
function (url, method, cb) {

            request({
                url: url,
                method: method
            }, function (error, response, body) {

                if (error) {
                    return cb(error);
                }

                if (response.statusCode == 200 || response.statusCode == 201) {

                    return cb(null, body);

                } else {

                    return cb(new Error('Server responded with error: ' + response.statusCode));

                }

            })

        }
144948
private void executePutOperation(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ClassNotFoundException {
        if (request.getContentLength() > 0) {
            ObjectInputStream input = new ObjectInputStream(new BufferedInputStream(request.getInputStream()));
            CommandPayload payload = (CommandPayload) input.readObject();
            Command operation = payload.getCommand();
            Manager manager = (Manager) request.getAttribute(ARQUILLIAN_MANAGER_ATTRIBUTE);
            // execute remote Event
            try {
                manager.fire(new ActivateManager(manager));
                manager.inject(operation);
                operation.perform();
                manager.fire(new PassivateManager(manager));
            } catch (Throwable e) {
                payload.setThrowable(e);
            }
            response.setStatus(HttpServletResponse.SC_OK);
            ObjectOutputStream output = new ObjectOutputStream(response.getOutputStream());
            output.writeObject(payload);
            output.flush();
            output.close();
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    }
1124276
public void withHttpMethod(Http method) {
        Objects.requireNonNull(method, Required.METHOD.toString());
        this.method = method;
    }
733682
private Observable<HttpClientResponse<O>> submit(final Server server, final HttpClientRequest<I> request, final RetryHandler errorHandler, final IClientConfig requestConfig, final ClientConfig rxClientConfig) {
        RetryHandler retryHandler = errorHandler;
        if (retryHandler == null) {
            retryHandler = getRequestRetryHandler(request, requestConfig);
        }
        
        final IClientConfig config = requestConfig == null ? DefaultClientConfigImpl.getEmptyConfig() : requestConfig;
        final ExecutionContext<HttpClientRequest<I>> context = new ExecutionContext<HttpClientRequest<I>>(request, config, this.getClientConfig(), retryHandler);
        
        Observable<HttpClientResponse<O>> result = submitToServerInURI(request, config, rxClientConfig, retryHandler, context);
        if (result == null) {
            LoadBalancerCommand<HttpClientResponse<O>> command;
            if (retryHandler != defaultRetryHandler) {
                // need to create new builder instead of the default one
                command = LoadBalancerCommand.<HttpClientResponse<O>>builder()
                        .withExecutionContext(context)
                        .withLoadBalancerContext(lbContext)
                        .withListeners(listeners)
                        .withClientConfig(this.getClientConfig())
                        .withRetryHandler(retryHandler)
                        .withServer(server)
                        .build();
            }
            else {
                command = defaultCommandBuilder;
            }
            
            result = command.submit(requestToOperation(request, getRxClientConfig(config, rxClientConfig)));
        }
        return result;
    }
992228
private Object executeMethod(final Method method, final ServletContextImpl context, final Object[] params)
            throws PrivilegedActionException, IllegalAccessException, InvocationTargetException {

        if (SecurityUtil.isPackageProtectionEnabled()) {
            return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                public Object run() throws IllegalAccessException, InvocationTargetException {
                    return method.invoke(context, params);
                }
            });
        } else {
            return method.invoke(context, params);
        }
    }
675453
public static HttpResponse execute(final String url, final String method,
                                       final Map<String, Object> headers) {
        return execute(url, method, null, null, new HashMap<>(), headers);
    }
451849
protected void sendServerResponse(HttpMessage response) {
        designer.http().server(httpServer).send()
                .response(response.getStatusCode())
                .message(response);
    }
818728
public ApiResponse apiRequest(HttpMethod method,
            Map<String, Object> params, Object data, String... segments) {
        ApiResponse response = null;
        try {
            response = httpRequest(method, ApiResponse.class, params, data,
                    segments);
            log.info("Client.apiRequest(): Response: " + response);
        } catch (HttpClientErrorException e) {
            log.error("Client.apiRequest(): HTTP error: "
                    + e.getLocalizedMessage());
            response = parse(e.getResponseBodyAsString(), ApiResponse.class);
            if ((response != null) && !isEmpty(response.getError())) {
                log.error("Client.apiRequest(): Response error: "
                        + response.getError());
                if (!isEmpty(response.getException())) {
                    log.error("Client.apiRequest(): Response exception: "
                            + response.getException());
                }
            }
        }
        return response;
    }
352991
public HttpResponse doAction(HttpRequest request, String form, HttpMethod method)
        throws ClientException, ServerException {
        request.validate();
        
        // try refresh credentials if CredentialProvider set
        this.config.refreshCredentials();
        
        try {
            int retryTimes = 0;
            HttpResponse response = null;

            boolean httpInvoke = false;
            if (request instanceof HttpInvokeFunctionRequest) {
                httpInvoke = true;
            }

            do {
                if (!httpInvoke
                    || !ANONYMOUS.equals(((HttpInvokeFunctionRequest) request).getAuthType())) {
                    signRequest(request, form, method, httpInvoke);
                }

                PrepareUrl prepareUrl = prepareUrl(request.getPath(), request.getQueryParams());

                response = HttpResponse.getResponse(prepareUrl.getUrl(), request, method,
                    config.getConnectTimeoutMillis(), config.getReadTimeoutMillis());

                retryTimes++;

                if (httpInvoke) {
                    return response;
                }

            } while (500 <= response.getStatus() && AUTO_RETRY && retryTimes < MAX_RETRIES);

            if (response.getStatus() >= 500) {
                String requestId = response.getHeader(HeaderKeys.REQUEST_ID);
                String stringContent =
                    response.getContent() == null ? "" : new String(response.getContent());
                ServerException se;
                try {
                    se = new Gson().fromJson(stringContent, ServerException.class);
                } catch (JsonParseException e) {
                    se = new ServerException("InternalServiceError",
                        "Failed to parse response content", requestId);
                }
                se.setStatusCode(response.getStatus());
                se.setRequestId(requestId);
                throw se;
            } else if (response.getStatus() >= 300) {
                ClientException ce;
                if (response.getContent() == null) {
                    ce = new ClientException("SDK.ServerUnreachable",
                        "Failed to get response content from server");
                } else {
                    try {
                        ce = new Gson()
                            .fromJson(new String(response.getContent()), ClientException.class);
                    } catch (JsonParseException e) {
                        ce = new ClientException("SDK.ResponseNotParsable",
                            "Failed to parse response content", e);
                    }
                }
                if (ce == null) {
                    ce = new ClientException("SDK.UnknownError", "Unknown client error");
                }
                ce.setStatusCode(response.getStatus());
                ce.setRequestId(response.getHeader(HeaderKeys.REQUEST_ID));
                throw ce;
            }
            return response;
        } catch (InvalidKeyException exp) {
            throw new ClientException("SDK.InvalidAccessSecret",
                "Speicified access secret is not valid.");
        } catch (SocketTimeoutException exp) {
            throw new ClientException("SDK.ServerUnreachable",
                "SocketTimeoutException has occurred on a socket read or accept.");
        } catch (IOException exp) {
            throw new ClientException("SDK.ServerUnreachable",
                "Server unreachable: " + exp.toString());
        } catch (NoSuchAlgorithmException exp) {
            throw new ClientException("SDK.InvalidMD5Algorithm",
                "MD5 hash is not supported by client side.");
        } catch (URISyntaxException e) {
            throw new ClientException("SDK.InvalidURL", "url is not valid: " + e.getMessage());
        }
    }
1035425
private void fakeResponse(final HttpMethod method)
        throws IOException, HttpException {
        // What is to follow is an ugly hack.
        // I REALLY hate having to resort to such
        // an appalling trick
        // The only feasible solution is to split monolithic
        // HttpMethod into HttpRequest/HttpResponse pair.
        // That would allow to execute CONNECT method 
        // behind the scene and return CONNECT HttpResponse 
        // object in response to the original request that 
        // contains the correct status line, headers & 
        // response body.
        LOG.debug("CONNECT failed, fake the response for the original method");
        // Pass the status, headers and response stream to the wrapped
        // method.
        // To ensure that the connection is not released more than once
        // this method is still responsible for releasing the connection. 
        // This will happen when the response body is consumed, or when
        // the wrapped method closes the response connection in 
        // releaseConnection().
        if (method instanceof HttpMethodBase) {
            ((HttpMethodBase) method).fakeResponse(
                this.connectMethod.getStatusLine(),
                this.connectMethod.getResponseHeaderGroup(),
                conn,
                this.connectMethod.getResponseBodyAsStream()
            );
            method.getProxyAuthState().setAuthScheme(
                this.connectMethod.getProxyAuthState().getAuthScheme());
            this.connectMethod = null;
        } else {
            releaseConnection = true;
            LOG.warn(
                "Unable to fake response on method as it is not derived from HttpMethodBase.");
        }
    }
750659
@Override
	public HttpResponse execute() throws IOException {
		if (this.method == HttpMethod.GET) {
			String url = this.toString();
			if (url.length() > this.cutoff) {
				if (log.isLoggable(Level.FINER))
					log.finer("URL length " + url.length() + " too long, converting GET to POST: " + url);
				
				String rebase = this.baseURL + "?method=GET";
				return this.execute(HttpMethod.POST, rebase);
			}
		}

		return super.execute();
	}
912156
private static void ensureStatusOk(HttpResponse<String> response) throws ClientErrorException,
            ServerErrorException, OtherCommunicationException {
        int responseStatus = response.getStatus();
        if (isClientError(responseStatus)) {
            throw new ClientErrorException(response.getBody());
        } else if (isServerError(responseStatus)) {
            throw new ServerErrorException();
        } else if (isOtherErrorResponse(responseStatus)) {
            throw new OtherCommunicationException();
        }
    }
1349988
private <T extends Object> T getResponse(HttpResponse httpResponse, Class<T> clazz) throws IOException, HttpRosetteAPIException {
        int status = httpResponse.getStatusLine().getStatusCode();
        String encoding = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_ENCODING));

        try (
                InputStream stream = httpResponse.getEntity().getContent();
                InputStream inputStream = "gzip".equalsIgnoreCase(encoding) ? new GZIPInputStream(stream) : stream) {
            String ridHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-DocumentRequest-Id"));
            if (HTTP_OK != status) {
                String ecHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Code"));
                String emHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Message"));
                String responseContentType = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE));
                if ("application/json".equals(responseContentType)) {
                    ErrorResponse errorResponse = mapper.readValue(inputStream, ErrorResponse.class);
                    if (ridHeader != null) {
                        LOG.debug("DocumentRequest ID " + ridHeader);
                    }
                    if (ecHeader != null) {
                        errorResponse.setCode(ecHeader);
                    }
                    if (429 == status) {
                        String concurrencyMessage = "You have exceeded your plan's limit on concurrent calls. "
                                + "This could be caused by multiple processes or threads making Rosette API calls in parallel, "
                                + "or if your httpClient is configured with higher concurrency than your plan allows.";
                        if (emHeader == null) {
                            emHeader = concurrencyMessage;
                        } else {
                            emHeader = concurrencyMessage + System.lineSeparator() + emHeader;
                        }
                    }
                    if (emHeader != null) {
                        errorResponse.setMessage(emHeader);
                    }
                    throw new HttpRosetteAPIException(errorResponse, status);
                } else {
                    String errorContent;
                    if (inputStream != null) {
                        byte[] content = getBytes(inputStream);
                        errorContent = new String(content, "utf-8");
                    } else {
                        errorContent = "(no body)";
                    }
                    // something not from us at all
                    throw new HttpRosetteAPIException("Invalid error response (not json)",
                            ErrorResponse.builder().code("invalidErrorResponse").message(errorContent).build(), status);
                }
            } else {
                return mapper.readValue(inputStream, clazz);
            }
        }
    }
926898
protected <T> T _execute(
                    final String string_url,
                    final HttpMethod method,
                    final RequestCallback callback,
                    final ResponseExtractor<T> extractor
                    )
    {
        _LOG_.debug( "HTTP: method = " + method + ", URL=" + string_url );

        URI  uri = null;
        try {
            URL  url = new URL( string_url );   //throws MalformedURLException
            uri = url.toURI();                  //throws URISyntaxException
        } catch (Exception ex) {
            _LOG_.error( "HTTP client error: " + ex );
            throw new HttpException( ex );
        }

        T  response = null;
        try {
            RestTemplate  rest = new RestTemplate();
            response = rest.execute( uri, method, callback, extractor );
                            //throws RestClientException
        } catch (Exception ex) {
            _LOG_.error( "HTTP client error: " + ex );
            throw new HttpException( ex );
        }

        return response;
    }