Executes a prepared HTTP request using the given client.

@param httpClient the client to use for the request
@param httpRequest the prepared request to perform
@return CompletionStage holding object of type T
977533
private <T> CompletionStage<T> executeRequest(HttpAsyncClient httpClient,
            HttpUriRequest httpRequest, JsonParser<T> parser) {
        CompletableFuture<T> future = new CompletableFuture<>();
        httpClient.execute(httpRequest, new FutureCallback<HttpResponse>() {
            @Override
            public void failed(Exception e) {
                future.completeExceptionally(e);
            }

            @Override
            public void completed(HttpResponse response) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK ||
                        statusCode == HttpStatus.SC_ACCEPTED) {

                    // Parse result type from the returned JSON
                    try {
                        T result = parser.parse(response.getEntity().getContent());
                        future.complete(result);
                    } catch (Exception e) {
                        future.completeExceptionally(e);
                    }
                } else {
                    future.completeExceptionally(createSaltException(statusCode));
                }
            }

            @Override
            public void cancelled() {
                future.cancel(false);
            }
        });

        return future;
    }
820984
static <T> CompletionStage<Boolean> authorize(Authorizer<T> authorizer, ServiceRequestContext ctx, T data) {
        try {
            final CompletionStage<Boolean> f = authorizer.authorize(ctx, data);
            if (f == null) {
                throw new NullPointerException("An " + Authorizer.class.getSimpleName() +
                                               " returned null: " + authorizer);
            }
            return f;
        } catch (Throwable cause) {
            return CompletableFutures.exceptionallyCompletedFuture(cause);
        }
    }
699280
@Override
  public boolean execute(HttpRequestBase request) {
    DataSenderThread senderThread = new DataSenderThread(HTTP_CLIENT_INSTANCE, request);
    senderThread.run();
    return true;
  }
1362000
public HttpResponse execute( final HttpUriRequest request ) throws IOException, ReadOnlyException {
        if ( readOnly ) {
            switch ( request.getMethod().toLowerCase() ) {
                case "copy": case "delete": case "move": case "patch": case "post": case "put":
                    throw new ReadOnlyException();
                default:
                    break;
            }
        }

        return httpClient.execute(request, httpContext);
    }
987556
protected T sendAndReturn(final HttpUriRequest request) throws IOException {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
      return this.parseResponse(client.execute(request));
    }
  }
34719
public HttpConnection execute(HttpConnection connection) {

        //set our HttpUrlFactory on the connection
        connection.connectionFactory = factory;

        // all CouchClient requests want to receive application/json responses
        connection.requestProperties.put("Accept", "application/json");
        connection.responseInterceptors.addAll(this.responseInterceptors);
        connection.requestInterceptors.addAll(this.requestInterceptors);
        InputStream es = null; // error stream - response from server for a 500 etc

        // first try to execute our request and get the input stream with the server's response
        // we want to catch IOException because HttpUrlConnection throws these for non-success
        // responses (eg 404 throws a FileNotFoundException) but we need to map to our own
        // specific exceptions
        try {
            try {
                connection = connection.execute();
            } catch (HttpConnectionInterceptorException e) {
                CouchDbException exception = new CouchDbException(connection.getConnection()
                        .getResponseMessage(), connection.getConnection().getResponseCode());
                if (e.deserialize) {
                    try {
                        JsonObject errorResponse = new Gson().fromJson(e.error, JsonObject
                                .class);
                        exception.error = getAsString(errorResponse, "error");
                        exception.reason = getAsString(errorResponse, "reason");
                    } catch (JsonParseException jpe) {
                        exception.error = e.error;
                    }
                } else {
                    exception.error = e.error;
                    exception.reason = e.reason;
                }
                throw exception;
            }
            int code = connection.getConnection().getResponseCode();
            String response = connection.getConnection().getResponseMessage();
            // everything ok? return the stream
            if (code / 100 == 2) { // success [200,299]
                return connection;
            } else {
                final CouchDbException ex;
                switch (code) {
                    case HttpURLConnection.HTTP_NOT_FOUND: //404
                        ex = new NoDocumentException(response);
                        break;
                    case HttpURLConnection.HTTP_CONFLICT: //409
                        ex = new DocumentConflictException(response);
                        break;
                    case HttpURLConnection.HTTP_PRECON_FAILED: //412
                        ex = new PreconditionFailedException(response);
                        break;
                    case 429:
                        // If a Replay429Interceptor is present it will check for 429 and retry at
                        // intervals. If the retries do not succeed or no 429 replay was configured
                        // we end up here and throw a TooManyRequestsException.
                        ex = new TooManyRequestsException(response);
                        break;
                    default:
                        ex = new CouchDbException(response, code);
                        break;
                }
                es = connection.getConnection().getErrorStream();
                //if there is an error stream try to deserialize into the typed exception
                if (es != null) {
                    try {
                        //read the error stream into memory
                        byte[] errorResponse = IOUtils.toByteArray(es);

                        Class<? extends CouchDbException> exceptionClass = ex.getClass();
                        //treat the error as JSON and try to deserialize
                        try {
                            // Register an InstanceCreator that returns the existing exception so
                            // we can just populate the fields, but not ignore the constructor.
                            // Uses a new Gson so we don't accidentally recycle an exception.
                            Gson g = new GsonBuilder().registerTypeAdapter(exceptionClass, new
                                    CouchDbExceptionInstanceCreator(ex)).create();
                            // Now populate the exception with the error/reason other info from JSON
                            g.fromJson(new InputStreamReader(new ByteArrayInputStream
                                    (errorResponse),
                                    "UTF-8"), exceptionClass);
                        } catch (JsonParseException e) {
                            // The error stream was not JSON so just set the string content as the
                            // error field on ex before we throw it
                            ex.error = new String(errorResponse, "UTF-8");
                        }
                    } finally {
                        close(es);
                    }
                }
                ex.setUrl(connection.url.toString());
                throw ex;
            }
        } catch (IOException ioe) {
            CouchDbException ex = new CouchDbException("Error retrieving server response", ioe);
            ex.setUrl(connection.url.toString());
            throw ex;
        }
    }
504871
public <T> HttpClientRequest.Builder<T> delete(final URI uri, final HttpClientResponseHandler<T> httpHandler)
    {
        return new HttpClientRequest.Builder<T>(httpClientFactory, HttpClientMethod.DELETE, uri, httpHandler);
    }
1124589
public function setHttpClient(HttpClient $httpClient = null)
    {
        if (!$httpClient) {
            $httpClient = $this->apiDiscoveryProxy->discoverHttpClient();
        }

        $this->httpClient = $httpClient;

        return $this;
    }
709538
protected <R> R executeRequest(Request request, JavaType javaType)
    {
        long start = System.currentTimeMillis();
        boolean error = true;
        try
        {
            Response response = executeRequest(request);
            R r = readResponse(response, javaType);
            error = false;
            return r;
        }
        finally
        {
            if(clientEventListener != null)
            {
                ClientEvent event = new ClientEvent(baseUrl,request.getEntityName(),request.getRequestMethod(),
                        System.currentTimeMillis() - start,error);
                clientEventListener.handleEvent(event);
            }
        }
    }
681125
public HttpClientActionBuilder client(String httpClient) {
		HttpClientActionBuilder clientAction = new HttpClientActionBuilder(action, httpClient)
				.withApplicationContext(applicationContext);
		return clientAction;
	}
602518
public final HttpClient httpResponseDecoder(Function<HttpResponseDecoderSpec, HttpResponseDecoderSpec> responseDecoderOptions) {
		return tcpConfiguration(
				responseDecoderOptions.apply(new HttpResponseDecoderSpec())
				                      .build());
	}
1007085
@Override
    public final void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

        AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
        if (authState.getAuthScheme() == null) {

            HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            AuthCache authCache = new BasicAuthCache();
            authCache.put(targetHost, new BasicScheme());
            context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
        }
    }
372488
public <T> HttpClientRequest.Builder<T> perform(final String methodName, final URI uri, final HttpClientResponseHandler<T> httpHandler) {
        final HttpClientMethod method;
        try {
            method = HttpClientMethod.valueOf(methodName.toUpperCase(Locale.ENGLISH));
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Unknown HTTP method type " + methodName, e);
        }

        return new HttpClientRequest.Builder<T>(httpClientFactory, method, uri, httpHandler);
    }
597226
@Override
	public Promise<HttpResponse> request(HttpRequest request) {
		assert eventloop.inEventloopThread();
		if (inspector != null) inspector.onRequest(request);
		String host = request.getUrl().getHost();

		assert host != null;

		return asyncDnsClient.resolve4(host)
				.thenEx((dnsResponse, e) -> {
					if (e == null) {
						if (inspector != null) inspector.onResolve(request, dnsResponse);
						if (dnsResponse.isSuccessful()) {
							//noinspection ConstantConditions - dnsResponse is successful (not null)
							return doSend(request, dnsResponse.getRecord().getIps());
						} else {
							return Promise.ofException(new DnsQueryException(AsyncHttpClient.class, dnsResponse));
						}
					} else {
						if (inspector != null) inspector.onResolveError(request, e);
						request.recycle();
						return Promise.ofException(e);
					}
				});
	}
885173
public static CloseableHttpAsyncClient defaultClient() {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(0)
                .setConnectTimeout(10000)
                .setSocketTimeout(20000)
                .setCookieSpec(CookieSpecs.STANDARD)
                .build();
        HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
        httpClientBuilder.setDefaultRequestConfig(requestConfig);

        CloseableHttpAsyncClient asyncHttpClient = httpClientBuilder.build();
        asyncHttpClient.start();
        return asyncHttpClient;
    }
1128052
protected static org.apache.http.client.HttpClient buildHttpClient(boolean contentCompression, boolean sslVerification) {
        RequestConfig rc = RequestConfig.custom()
                .setCookieSpec(CookieSpecs.STANDARD)
                .build();

        HttpClientBuilder builder = HttpClients.custom()
                .useSystemProperties();

        if (!contentCompression) {
            builder.disableContentCompression();
        }

        if (!sslVerification) {
            try {
                builder.setSSLSocketFactory(generateAllTrustingSSLConnectionSocketFactory());
            } catch (Exception e) {
                throw new RuntimeException("Unable to create all-trusting SSLConnectionSocketFactory", e);
            }

        }

        return builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
                .setUserAgent(HttpClient.class.getName())
                .setDefaultRequestConfig(rc)
                .build();
    }
593009
public CloseableHttpClient NewHttpClient() throws Exception {
    	SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    	SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
    	this.httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    	return this.httpclient;
    }