Example usage for org.apache.http.client.protocol HttpClientContext create

List of usage examples for org.apache.http.client.protocol HttpClientContext create

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext create.

Prototype

public static HttpClientContext create() 

Source Link

Usage

From source file:org.callimachusproject.webdriver.helpers.BrowserFunctionalTestCase.java

private void putTestData(String info, String jobId, String data, CloseableHttpClient client)
        throws IOException, ClientProtocolException {
    String username = decode(info.substring(0, info.indexOf(':')), "UTF-8");
    String password = decode(info.substring(info.indexOf(':') + 1), "UTF-8");
    UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password);
    AuthScope scope = new AuthScope("saucelabs.com", 80);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(scope, cred);
    HttpClientContext ctx = HttpClientContext.create();
    ctx.setCredentialsProvider(credsProvider);
    HttpPut put = new HttpPut("http://saucelabs.com/rest/v1/" + username + "/jobs/" + jobId);
    put.setEntity(new StringEntity(data, ContentType.APPLICATION_JSON));
    client.execute(put, new ResponseHandler<Void>() {
        public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            if (300 <= response.getStatusLine().getStatusCode()) {
                System.err.println(EntityUtils.toString(response.getEntity()));
            }/*from   www . ja va 2 s.  c om*/
            assertTrue(response.getStatusLine().toString(), 300 > response.getStatusLine().getStatusCode());
            return null;
        }
    }, ctx);
}

From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {/*from  w  ww  . ja v  a 2  s.c  om*/
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(),
                this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }

        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response)));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }

        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyConnectorClient.java

/** Disconnect this connector **/
public void disconnect() {
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("disconnect: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }// w  ww.j  a  va  2s .c  o m

    if (lastInheritedAnnouncement != null) {
        announcementRegistry.unregisterAnnouncement(lastInheritedAnnouncement.getOwnerId());
    }

    final HttpClientContext clientContext = HttpClientContext.create();
    final CloseableHttpClient httpClient = createHttpClient();
    final HttpDelete deleteRequest = new HttpDelete(uri);
    // setting the connection timeout (idle connection, configured in seconds)
    deleteRequest.setConfig(
            RequestConfig.custom().setConnectTimeout(1000 * config.getSocketConnectTimeout()).build());

    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            clientContext.getCredentialsProvider().setCredentials(
                    new AuthScope(deleteRequest.getURI().getHost(), deleteRequest.getURI().getPort()), c);
        }

        requestValidator.trustMessage(deleteRequest, null);
        final CloseableHttpResponse response = httpClient.execute(deleteRequest, clientContext);
        if (logger.isDebugEnabled()) {
            logger.debug("disconnect: done. code=" + response.getStatusLine().getStatusCode() + " - "
                    + response.getStatusLine().getReasonPhrase());
        }
        // ignoring the actual statuscode though as there's little we can
        // do about it after this point
    } catch (IOException e) {
        logger.warn("disconnect: got IOException: " + e);
    } catch (RuntimeException re) {
        logger.error("disconnect: got RuntimeException: " + re, re);
    } finally {
        deleteRequest.releaseConnection();
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("disconnect: could not close httpClient: " + e, e);
        }
    }
}

From source file:org.elasticsearch.client.RestClient.java

private void performRequestAsync(final long startTime, final HostTuple<Iterator<HttpHost>> hostTuple,
        final HttpRequestBase request, final Set<Integer> ignoreErrorCodes,
        final HttpAsyncResponseConsumerFactory httpAsyncResponseConsumerFactory,
        final FailureTrackingResponseListener listener) {
    final HttpHost host = hostTuple.hosts.next();
    //we stream the request body if the entity allows for it
    final HttpAsyncRequestProducer requestProducer = HttpAsyncMethods.create(host, request);
    final HttpAsyncResponseConsumer<HttpResponse> asyncResponseConsumer = httpAsyncResponseConsumerFactory
            .createHttpAsyncResponseConsumer();
    final HttpClientContext context = HttpClientContext.create();
    context.setAuthCache(hostTuple.authCache);
    client.execute(requestProducer, asyncResponseConsumer, context, new FutureCallback<HttpResponse>() {
        @Override//from w w  w  .j  a  v  a  2 s .  c  om
        public void completed(HttpResponse httpResponse) {
            try {
                RequestLogger.logResponse(logger, request, host, httpResponse);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                Response response = new Response(request.getRequestLine(), host, httpResponse);
                if (isSuccessfulResponse(statusCode)
                        || ignoreErrorCodes.contains(response.getStatusLine().getStatusCode())) {
                    onResponse(host);
                    listener.onSuccess(response);
                } else {
                    ResponseException responseException = new ResponseException(response);
                    if (isRetryStatus(statusCode)) {
                        //mark host dead and retry against next one
                        onFailure(host);
                        retryIfPossible(responseException);
                    } else {
                        //mark host alive and don't retry, as the error should be a request problem
                        onResponse(host);
                        listener.onDefinitiveFailure(responseException);
                    }
                }
            } catch (Exception e) {
                listener.onDefinitiveFailure(e);
            }
        }

        @Override
        public void failed(Exception failure) {
            try {
                RequestLogger.logFailedRequest(logger, request, host, failure);
                onFailure(host);
                retryIfPossible(failure);
            } catch (Exception e) {
                listener.onDefinitiveFailure(e);
            }
        }

        private void retryIfPossible(Exception exception) {
            if (hostTuple.hosts.hasNext()) {
                //in case we are retrying, check whether maxRetryTimeout has been reached
                long timeElapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
                long timeout = maxRetryTimeoutMillis - timeElapsedMillis;
                if (timeout <= 0) {
                    IOException retryTimeoutException = new IOException(
                            "request retries exceeded max retry timeout [" + maxRetryTimeoutMillis + "]");
                    listener.onDefinitiveFailure(retryTimeoutException);
                } else {
                    listener.trackFailure(exception);
                    request.reset();
                    performRequestAsync(startTime, hostTuple, request, ignoreErrorCodes,
                            httpAsyncResponseConsumerFactory, listener);
                }
            } else {
                listener.onDefinitiveFailure(exception);
            }
        }

        @Override
        public void cancelled() {
            listener.onDefinitiveFailure(new ExecutionException("request was cancelled", null));
        }
    });
}

From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {/*from ww w .ja  v a2  s  . c  om*/
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(),
                this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ApacheConnectorClientResponse(status, clientRequest,
                response);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<String>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }

        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(response));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }

        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java

protected HttpResponse getHttpResponse(final HttpUriRequest httpRequest, final URI uri) throws DSSException {

    final HttpClient client = getHttpClient(uri);

    final String host = uri.getHost();
    final int port = uri.getPort();
    final String scheme = uri.getScheme();
    final HttpHost targetHost = new HttpHost(host, port, scheme);

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    try {/*from ww  w.  j  a v a 2 s.  c o  m*/
        final HttpResponse response = client.execute(targetHost, httpRequest, localContext);
        return response;
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:com.liferay.petra.json.web.service.client.BaseJSONWebServiceClientImpl.java

protected String execute(HttpRequestBase httpRequestBase)
        throws JSONWebServiceInvocationException, JSONWebServiceTransportException {

    signRequest(httpRequestBase);// w  w w  .ja v a 2  s.c o  m

    HttpHost httpHost = new HttpHost(_hostName, _hostPort, _protocol);

    try {
        if (_closeableHttpAsyncClient == null) {
            afterPropertiesSet();
        }

        Future<HttpResponse> future = null;

        if (!isNull(_login) && !isNull(_password)) {
            HttpClientContext httpClientContext = HttpClientContext.create();

            AuthCache authCache = new BasicAuthCache();

            AuthScheme authScheme = null;

            if (!isNull(_proxyHostName)) {
                authScheme = new BasicScheme(ChallengeState.PROXY);
            } else {
                authScheme = new BasicScheme(ChallengeState.TARGET);
            }

            authCache.put(httpHost, authScheme);

            httpClientContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

            future = _closeableHttpAsyncClient.execute(httpHost, httpRequestBase, httpClientContext, null);
        } else {
            future = _closeableHttpAsyncClient.execute(httpHost, httpRequestBase, null);
        }

        HttpResponse httpResponse = future.get();

        StatusLine statusLine = httpResponse.getStatusLine();

        int statusCode = statusLine.getStatusCode();

        if (_logger.isTraceEnabled()) {
            _logger.trace("Server returned status " + statusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        if ((statusCode == HttpServletResponse.SC_NO_CONTENT)
                || (((httpEntity == null) || (httpEntity.getContentLength() == 0))
                        && _isStatus2XX(statusCode))) {

            return null;
        }

        String content = EntityUtils.toString(httpEntity, _CHARSET);

        if ((httpEntity.getContentType() != null) && _isApplicationJSONContentType(httpEntity)) {

            content = updateJSON(content);
        }

        if (_isStatus2XX(statusCode)) {
            return content;
        } else if ((statusCode == HttpServletResponse.SC_BAD_REQUEST)
                || (statusCode == HttpServletResponse.SC_FORBIDDEN)
                || (statusCode == HttpServletResponse.SC_METHOD_NOT_ALLOWED)
                || (statusCode == HttpServletResponse.SC_NOT_ACCEPTABLE)
                || (statusCode == HttpServletResponse.SC_NOT_FOUND)) {

            throw new JSONWebServiceInvocationException(content, statusCode);
        } else if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
            throw new JSONWebServiceTransportException.AuthenticationFailure(
                    "Not authorized to access JSON web service");
        }

        throw new JSONWebServiceTransportException.CommunicationFailure("Server returned status " + statusCode,
                statusCode);
    } catch (ExecutionException ee) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ee);
    } catch (InterruptedException ie) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ie);
    } catch (IOException ioe) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ioe);
    } finally {
        httpRequestBase.releaseConnection();
    }
}

From source file:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);

    try {//from w  ww .j av  a  2s .c om
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(),
                this.getClass().getName());

        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null
                ? Statuses.from(response.getStatusLine().getStatusCode())
                : Statuses.from(response.getStatusLine().getStatusCode(),
                        response.getStatusLine().getReasonPhrase());

        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }

        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }

        final HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }

            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }

        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response)));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }

        localHttpContext.set(context);
        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:com.ngdata.hbaseindexer.indexer.FusionPipelineClient.java

public void postJsonToPipeline(String endpoint, List docs, int requestId) throws Exception {

    FusionSession fusionSession = null;/*from   w w  w.  j a  va  2s  .  c  o m*/

    long currTime = System.nanoTime();
    synchronized (this) {
        fusionSession = sessions.get(endpoint);

        // ensure last request within the session timeout period, else reset the session
        if (fusionSession == null || (currTime - fusionSession.sessionEstablishedAt) > maxNanosOfInactivity) {
            log.info("Fusion session is likely expired (or soon will be) for endpoint " + endpoint + ", "
                    + "pre-emptively re-setting this session before processing request " + requestId);
            fusionSession = resetSession(endpoint);
            if (fusionSession == null)
                throw new IllegalStateException("Failed to re-connect to " + endpoint
                        + " after session loss when processing request " + requestId);
        }
    }

    HttpEntity entity = null;
    try {
        HttpPost postRequest = new HttpPost(endpoint);

        // stream the json directly to the HTTP output
        EntityTemplate et = new EntityTemplate(new JacksonContentProducer(jsonObjectMapper, docs));
        et.setContentType("application/json");
        et.setContentEncoding(StandardCharsets.UTF_8.name());
        postRequest.setEntity(et); // new BufferedHttpEntity(et));

        HttpResponse response = null;
        HttpClientContext context = null;
        if (isKerberos) {
            httpClient = FusionKrb5HttpClientConfigurer.createClient(fusionUser);
            response = httpClient.execute(postRequest);
        } else {
            context = HttpClientContext.create();
            if (cookieStore != null) {
                context.setCookieStore(cookieStore);
            }
            response = httpClient.execute(postRequest, context);
        }

        entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 401) {
            // unauth'd - session probably expired? retry to establish
            log.warn("Unauthorized error (401) when trying to send request " + requestId + " to Fusion at "
                    + endpoint + ", will re-try to establish session");

            // re-establish the session and re-try the request
            try {
                EntityUtils.consume(entity);
            } catch (Exception ignore) {
                log.warn("Failed to consume entity due to: " + ignore);
            } finally {
                entity = null;
            }

            synchronized (this) {
                fusionSession = resetSession(endpoint);
                if (fusionSession == null)
                    throw new IllegalStateException(
                            "After re-establishing session when processing request " + requestId + ", endpoint "
                                    + endpoint + " is no longer active! Try another endpoint.");
            }

            log.info("Going to re-try request " + requestId + " after session re-established with " + endpoint);
            if (isKerberos) {
                httpClient = FusionKrb5HttpClientConfigurer.createClient(fusionUser);
                response = httpClient.execute(postRequest);
            } else {
                response = httpClient.execute(postRequest, context);
            }

            entity = response.getEntity();
            statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200 || statusCode == 204) {
                log.info("Re-try request " + requestId + " after session timeout succeeded for: " + endpoint);
            } else {
                raiseFusionServerException(endpoint, entity, statusCode, response, requestId);
            }
        } else if (statusCode != 200 && statusCode != 204) {
            raiseFusionServerException(endpoint, entity, statusCode, response, requestId);
        } else {
            // OK!
            if (fusionSession != null && fusionSession.docsSentMeter != null)
                fusionSession.docsSentMeter.mark(docs.size());
        }
    } finally {

        if (entity != null) {
            try {
                EntityUtils.consume(entity);
            } catch (Exception ignore) {
                log.warn("Failed to consume entity due to: " + ignore);
            } finally {
                entity = null;
            }
        }
    }
}