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.gtri.fhir.api.vistaex.resource.impl.VistaExResourceImpl.java

public HttpClientContext getHttpClientContext() {
    if (httpClientContext == null) {
        httpClientContext = HttpClientContext.create();
    }
    return httpClientContext;
}

From source file:com.ibm.watson.app.common.util.rest.SimpleRestClient.java

protected <T> T execute(HttpRequestBase request, ResponseHandler<? extends T> responseHandler)
        throws IOException {
    return httpClient.execute(request, responseHandler, HttpClientContext.create());
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java

public byte[] send(byte[] request) {
    while (true) {
        HttpClientContext context = HttpClientContext.create();

        context.setTargetHost(host);//w w w . j a v a  2  s  .  c o  m

        // Set the credentials if they were provided.
        if (null != this.credentials) {
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthSchemeRegistry(authRegistry);
            context.setAuthCache(authCache);
        }

        ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM);

        // Create the client with the AuthSchemeRegistry and manager
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);

        try (CloseableHttpResponse response = execute(post, context)) {
            final int statusCode = response.getStatusLine().getStatusCode();
            if (HttpURLConnection.HTTP_OK == statusCode
                    || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) {
                return EntityUtils.toByteArray(response.getEntity());
            } else if (HttpURLConnection.HTTP_UNAVAILABLE == statusCode) {
                LOG.debug("Failed to connect to server (HTTP/503), retrying");
                continue;
            }

            throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode);
        } catch (NoHttpResponseException e) {
            // This can happen when sitting behind a load balancer and a backend server dies
            LOG.debug("The server failed to issue an HTTP response, retrying");
            continue;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("Failed to execute HTTP request", e);
            throw new RuntimeException(e);
        }
    }
}

From source file:org.cruk.genologics.api.GenologicsAPIPaginatedBatchTest.java

@Test
public void testMultipageFetchFind() throws Exception {
    // Part one - mock the rest template to return the already parsed objects.

    RestOperations restMock = EasyMock.createStrictMock(RestOperations.class);

    EasyMock.expect(restMock.getForEntity("http://lims.cri.camres.org:8080/api/v2/samples?projectname=Run 1030",
            Samples.class)).andReturn(response1).once();
    EasyMock.expect(restMock.getForEntity(
            new URI("http://lims.cri.camres.org:8080/api/v2/samples?start-index=500&projectname=Run+1030"),
            Samples.class)).andReturn(response2).once();
    EasyMock.expect(restMock.getForEntity(
            new URI("http://lims.cri.camres.org:8080/api/v2/samples?start-index=1000&projectname=Run+1030"),
            Samples.class)).andReturn(response3).once();

    GenologicsAPIImpl localApi = context.getBean("genologicsAPI", GenologicsAPIImpl.class);
    localApi.setRestClient(restMock);/*from   w  ww .j a v a  2 s.  c  o  m*/
    localApi.setServer(new URL("http://lims.cri.camres.org:8080"));

    EasyMock.replay(restMock);

    Map<String, Object> terms = new HashMap<String, Object>();
    terms.put("projectname", "Run 1030");

    List<LimsLink<Sample>> links = localApi.find(terms, Sample.class);

    EasyMock.verify(restMock);

    assertEquals("Expected 1150 sample links returned", 1150, links.size());

    // Part two - mock the HTTP client and request factory to ensure that the URIs are
    // being presented as expected without character cludging.

    HttpContext httpContext = HttpClientContext.create();
    HttpClient mockHttpClient = EasyMock.createMock(HttpClient.class);
    AuthenticatingClientHttpRequestFactory mockRequestFactory = EasyMock
            .createMock(AuthenticatingClientHttpRequestFactory.class);

    RestTemplate restTemplate = context.getBean("genologicsRestTemplate", RestTemplate.class);
    restTemplate.setRequestFactory(mockRequestFactory);

    localApi.setHttpClient(mockHttpClient);
    localApi.setRestClient(restTemplate);

    URI pageOne = new URI("http://lims.cri.camres.org:8080/api/v2/samples?projectname=Run%201030");
    URI pageTwo = new URI(
            "http://lims.cri.camres.org:8080/api/v2/samples?start-index=500&projectname=Run+1030");
    URI pageThree = new URI(
            "http://lims.cri.camres.org:8080/api/v2/samples?start-index=1000&projectname=Run+1030");

    HttpGet getOne = new HttpGet(pageOne);
    HttpGet getTwo = new HttpGet(pageOne);
    HttpGet getThree = new HttpGet(pageOne);

    HttpResponse responseOne = createMultipageFetchResponse(pageFiles[0]);
    HttpResponse responseTwo = createMultipageFetchResponse(pageFiles[1]);
    HttpResponse responseThree = createMultipageFetchResponse(pageFiles[2]);

    Class<?> requestClass = Class.forName("org.springframework.http.client.HttpComponentsClientHttpRequest");
    Constructor<?> constructor = requestClass.getDeclaredConstructor(HttpClient.class, HttpUriRequest.class,
            HttpContext.class);
    constructor.setAccessible(true);

    ClientHttpRequest reqOne = (ClientHttpRequest) constructor.newInstance(mockHttpClient, getOne, httpContext);
    ClientHttpRequest reqTwo = (ClientHttpRequest) constructor.newInstance(mockHttpClient, getTwo, httpContext);
    ClientHttpRequest reqThree = (ClientHttpRequest) constructor.newInstance(mockHttpClient, getThree,
            httpContext);

    EasyMock.expect(mockRequestFactory.createRequest(pageOne, HttpMethod.GET)).andReturn(reqOne).once();
    EasyMock.expect(mockRequestFactory.createRequest(pageTwo, HttpMethod.GET)).andReturn(reqTwo).once();
    EasyMock.expect(mockRequestFactory.createRequest(pageThree, HttpMethod.GET)).andReturn(reqThree).once();

    EasyMock.expect(mockHttpClient.execute(getOne, httpContext)).andReturn(responseOne).once();
    EasyMock.expect(mockHttpClient.execute(getTwo, httpContext)).andReturn(responseTwo).once();
    EasyMock.expect(mockHttpClient.execute(getThree, httpContext)).andReturn(responseThree).once();

    EasyMock.replay(mockHttpClient, mockRequestFactory);

    links = localApi.find(terms, Sample.class);

    EasyMock.verify(mockHttpClient, mockRequestFactory);

    assertEquals("Expected 1150 sample links returned", 1150, links.size());
}

From source file:eu.itesla_project.histodb.client.impl.HistoDbHttpClientImpl.java

private InputStream httpRequest(HttpUriRequest request, HistoDbUrl url) throws IOException {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Querying histo DB " + url.format());
    }/*  w  w w  .ja  v a  2 s  .c o m*/
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Querying histo DB " + url.prettyFormat());
    }

    long start = System.currentTimeMillis();

    HttpContext context = HttpClientContext.create();
    CloseableHttpResponse response = getHttpclient(url.getConfig()).execute(request, context);
    StatusLine statusLine = response.getStatusLine();

    switch (statusLine.getStatusCode()) {
    case 200:
        long duration = System.currentTimeMillis() - start;
        LOGGER.debug("Query done in {} ms", duration);
        return new ForwardingInputStream<InputStream>(response.getEntity().getContent()) {
            @Override
            public void close() throws IOException {
                super.close();
                EntityUtils.consume(response.getEntity());
                response.close();
            }
        };

    case 202:
        EntityUtils.consume(response.getEntity());
        response.close();
        return null;

    default:
        throw new RuntimeException("Query failed with status " + statusLine + " : " + url);
    }
}

From source file:org.opensaml.security.httpclient.HttpClientSecuritySupportTest.java

@Test
public void testMarshalSecurityParametersWithReplacement() {
    HttpClientContext context = HttpClientContext.create();

    context.setCredentialsProvider(new BasicCredentialsProvider());
    context.setAttribute(CONTEXT_KEY_TRUST_ENGINE, new MockTrustEngine());
    context.setAttribute(CONTEXT_KEY_CRITERIA_SET, new CriteriaSet());
    context.setAttribute(CONTEXT_KEY_TLS_PROTOCOLS, Lists.newArrayList("foo"));
    context.setAttribute(CONTEXT_KEY_TLS_CIPHER_SUITES, Lists.newArrayList("foo"));
    context.setAttribute(CONTEXT_KEY_CLIENT_TLS_CREDENTIAL, new BasicX509Credential(cert));
    context.setAttribute(CONTEXT_KEY_HOSTNAME_VERIFIER, new StrictHostnameVerifier());

    HttpClientSecurityParameters params = new HttpClientSecurityParameters();
    params.setCredentialsProvider(new BasicCredentialsProvider());
    params.setTLSTrustEngine(new MockTrustEngine());
    params.setTLSCriteriaSet(new CriteriaSet());
    params.setTLSProtocols(Lists.newArrayList("foo"));
    params.setTLSCipherSuites(Lists.newArrayList("foo"));
    params.setClientTLSCredential(new BasicX509Credential(cert));
    params.setHostnameVerifier(new StrictHostnameVerifier());

    HttpClientSecuritySupport.marshalSecurityParameters(context, params, true);

    Assert.assertSame(context.getCredentialsProvider(), params.getCredentialsProvider());
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_TRUST_ENGINE), params.getTLSTrustEngine());
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_CRITERIA_SET), params.getTLSCriteriaSet());
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_TLS_PROTOCOLS), params.getTLSProtocols());
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_TLS_CIPHER_SUITES), params.getTLSCipherSuites());
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_CLIENT_TLS_CREDENTIAL), params.getClientTLSCredential());
    Assert.assertSame(context.getAttribute(CONTEXT_KEY_HOSTNAME_VERIFIER), params.getHostnameVerifier());
}

From source file:io.seldon.external.ExternalPredictionServer.java

public JsonNode predict(String client, JsonNode jsonNode, OptionsHolder options) {
    long timeNow = System.currentTimeMillis();
    URI uri = URI.create(options.getStringOption(URL_PROPERTY_NAME));
    try {/*from   w  ww .  j  a v  a 2s  . c  o  m*/
        URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort())
                .setPath(uri.getPath()).setParameter("client", client)
                .setParameter("json", jsonNode.toString());

        uri = builder.build();
    } catch (URISyntaxException e) {
        throw new APIException(APIException.GENERIC_ERROR);
    }
    HttpContext context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(uri);
    try {
        if (logger.isDebugEnabled())
            logger.debug("Requesting " + httpGet.getURI().toString());
        CloseableHttpResponse resp = httpClient.execute(httpGet, context);
        try {
            if (resp.getStatusLine().getStatusCode() == 200) {
                ObjectMapper mapper = new ObjectMapper();
                JsonFactory factory = mapper.getFactory();
                JsonParser parser = factory.createParser(resp.getEntity().getContent());
                JsonNode actualObj = mapper.readTree(parser);

                return actualObj;
            } else {
                logger.error(
                        "Couldn't retrieve prediction from external prediction server -- bad http return code: "
                                + resp.getStatusLine().getStatusCode());
                throw new APIException(APIException.GENERIC_ERROR);
            }
        } finally {
            if (resp != null)
                resp.close();
            if (logger.isDebugEnabled())
                logger.debug(
                        "External prediction server took " + (System.currentTimeMillis() - timeNow) + "ms");
        }
    } catch (IOException e) {
        logger.error("Couldn't retrieve prediction from external prediction server - ", e);
        throw new APIException(APIException.GENERIC_ERROR);
    } catch (Exception e) {
        logger.error("Couldn't retrieve prediction from external prediction server - ", e);
        throw new APIException(APIException.GENERIC_ERROR);
    } finally {

    }

}

From source file:com.vmware.photon.controller.nsxclient.RestClient.java

/**
 * Creates a HTTP client context with preemptive basic authentication.
 *//*w  w  w .j  a v  a 2  s .  co  m*/
private HttpClientContext getHttpClientContext(String target, String username, String password) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    HttpHost targetHost = HttpHost.create(target);
    AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, new BasicScheme());

    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    return context;
}

From source file:org.fcrepo.integration.AbstractResourceIT.java

protected HttpResponse executeWithBasicAuth(final HttpUriRequest request, final String username,
        final String password) throws IOException {
    final HttpHost target = new HttpHost(HOSTNAME, SERVER_PORT, PROTOCOL);
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    try (final CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider).build()) {

        final AuthCache authCache = new BasicAuthCache();
        final BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        final HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        final CloseableHttpResponse response = httpclient.execute(request, localContext);
        return response;
    }/*w w w.j a va2 s  .c o  m*/
}