Example usage for org.apache.http.impl.client HttpClients custom

List of usage examples for org.apache.http.impl.client HttpClients custom

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClients custom.

Prototype

public static HttpClientBuilder custom() 

Source Link

Document

Creates builder object for construction of custom CloseableHttpClient instances.

Usage

From source file:org.ow2.proactive.scheduling.api.graphql.service.AuthenticationService.java

@PostConstruct
protected void init() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    schedulerLoginFetchUrl = createLoginFetchUrl(schedulerRestUrl);

    sessionCache = CacheBuilder.newBuilder().maximumSize(Integer.parseInt(sessionCacheMaxSize))
            .expireAfterWrite(Integer.parseInt(sessionCacheExpireAfter), TimeUnit.MILLISECONDS)
            .build(new CacheLoader<String, String>() {
                @Override//from w  w  w . jav  a 2s  .  c  o  m
                public String load(String sessionId) throws Exception {
                    return getLoginFromSessionId(sessionId);
                }
            });

    if (schedulerLoginFetchUrl.startsWith("https")) {
        CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        restTemplate.setRequestFactory(requestFactory);
    }

}

From source file:org.elasticsearch.http.netty.NettyHttpCompressionIT.java

public void testCanInterpretUncompressedRequest() throws Exception {
    ensureGreen();//from   w w w . ja  v  a  2 s.c o m

    ContentEncodingHeaderExtractor headerExtractor = new ContentEncodingHeaderExtractor();
    CloseableHttpClient internalClient = HttpClients.custom()
            // this disable content compression in both directions (request and response)
            .disableContentCompression().addInterceptorFirst(headerExtractor).build();

    HttpResponse response = httpClient(internalClient).path("/company/employees/1").method("POST")
            .body(SAMPLE_DOCUMENT).execute();

    assertEquals(201, response.getStatusCode());
    assertFalse(headerExtractor.hasContentEncodingHeader());
}

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

@Autowired
public ExternalItemRecommendationAlgorithm(ItemService itemService) {
    cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);// w w  w  .  j  av  a 2  s. com
    cm.setDefaultMaxPerRoute(20);

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(DEFAULT_REQ_TIMEOUT)
            .setConnectTimeout(DEFAULT_CON_TIMEOUT).setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build();

    httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build();

    this.itemService = itemService;
}

From source file:edu.mit.scratch.ScratchSession.java

public void logout() throws ScratchUserException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .build();/*from w  w w .  j  a v a  2s  . c  o  m*/

    final CookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
    final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", this.getSessionID());
    final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.getCSRFToken());
    final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
    lang.setDomain(".scratch.mit.edu");
    lang.setPath("/");
    sessid.setDomain(".scratch.mit.edu");
    sessid.setPath("/");
    token.setDomain(".scratch.mit.edu");
    token.setPath("/");
    debug.setDomain(".scratch.mit.edu");
    debug.setPath("/");
    cookieStore.addCookie(lang);
    cookieStore.addCookie(sessid);
    cookieStore.addCookie(token);
    cookieStore.addCookie(debug);

    final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)"
                    + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36")
            .setDefaultCookieStore(cookieStore).build();
    CloseableHttpResponse resp;

    final JSONObject loginObj = new JSONObject();
    loginObj.put("csrftoken", this.getCSRFToken());
    try {
        final HttpUriRequest logout = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/logout/")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "en-US,en;q=0.8")
                .addHeader("Content-Type", "application/json").addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("X-CSRFToken", this.getCSRFToken()).setEntity(new StringEntity(loginObj.toString()))
                .build();
        resp = httpClient.execute(logout);
    } catch (final Exception e) {
        throw new ScratchUserException();
    }

    this.session_id = null;
    this.token = null;
    this.expires = null;
    this.username = null;
}

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

@Override
public void configUpdated(String configKey, String configValue) {
    if (configValue != null && configValue.length() > 0) {
        ObjectMapper mapper = new ObjectMapper();
        try {/*from ww  w . ja v a 2s . c  o  m*/
            PredictionServerConfig config = mapper.readValue(configValue, PredictionServerConfig.class);
            cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(config.maxConnections);
            cm.setDefaultMaxPerRoute(config.maxConnections);
            httpClient = HttpClients.custom().setConnectionManager(cm).build();
            logger.info("Updated httpclient to use " + config.maxConnections + " max connections");
        } catch (Exception e) {
            throw new RuntimeException(String.format("* Error * parsing statsd configValue[%s]", configValue),
                    e);
        }
    }

}

From source file:org.commonjava.indy.httprox.AbstractHttproxFunctionalTest.java

protected CloseableHttpClient proxiedHttp(final String user, final String pass, SSLSocketFactory socketFactory)
        throws Exception {
    CredentialsProvider creds = null;/*  w  w w . j a va  2  s .  co m*/

    if (user != null) {
        creds = new BasicCredentialsProvider();
        creds.setCredentials(new AuthScope(HOST, proxyPort), new UsernamePasswordCredentials(user, pass));
    }

    HttpHost proxy = new HttpHost(HOST, proxyPort);

    final HttpRoutePlanner planner = new DefaultProxyRoutePlanner(proxy);
    HttpClientBuilder builder = HttpClients.custom().setRoutePlanner(planner)
            .setDefaultCredentialsProvider(creds).setProxy(proxy).setSSLSocketFactory(socketFactory);

    return builder.build();
}

From source file:org.ensembl.gti.seqstore.database.cramstore.EnaCramSubmitter.java

protected static HttpClient getHttpsClient() {
    try {/*from   w w w  .j a v  a  2  s  .co  m*/
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
}

From source file:co.paralleluniverse.comsat.webactors.AbstractWebActorTest.java

@Test
public void testWebSocketMsg()
        throws IOException, InterruptedException, ExecutionException, DeploymentException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    final HttpGet httpGet = new HttpGet("http://localhost:8080");
    HttpClients.custom().setDefaultRequestConfig(requestConfig).setDefaultCookieStore(cookieStore).build()
            .execute(httpGet, new BasicResponseHandler());

    final SettableFuture<String> res = new SettableFuture<>();
    final WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();
    wsContainer.setAsyncSendTimeout(timeout);
    wsContainer.setDefaultMaxSessionIdleTimeout(timeout);
    try (final Session ignored = wsContainer.connectToServer(sendAndGetTextEndPoint("test it", res),
            getClientEndPointConfig(cookieStore), URI.create("ws://localhost:8080/ws"))) {
        final String s = res.get();
        assertEquals("test it", s);
    }/*from w ww  .j  ava 2 s  .c  om*/
}

From source file:org.ops4j.pax.web.itest.VirtualHostsTest.java

@Test
public void shouldNotFindResourceOnDefaultHost() throws Exception {
    assertThat(servletContext.getContextPath(), is("/cm-static"));

    String path = String.format("http://localhost:%d/cm-static/hello", getHttpPort());
    HttpClientContext context = HttpClientContext.create();
    CloseableHttpClient client = HttpClients.custom().build();
    HttpGet httpGet = new HttpGet(path);
    HttpResponse response = client.execute(httpGet, context);

    int statusCode = response.getStatusLine().getStatusCode();
    assertThat(statusCode, is(404));//from  w w  w  . j ava2s  .  co  m
}

From source file:com.yahoo.sql4d.sql4ddriver.DruidNodeAccessor.java

public CloseableHttpClient getClient() {
    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(pool);
    return (customRouterPlanner != null) ? builder.setRoutePlanner(customRouterPlanner).build()
            : builder.build();//  ww w  .j a  v  a 2  s .c o m
}