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:com.enioka.jqm.tools.JettyTest.java

@Test
public void testSslServices() throws Exception {
    Helpers.setSingleParam("enableWsApiSsl", "true", em);
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "false", em);

    addAndStartEngine();//from   ww  w .  j a  v  a2s.  co m

    // Launch a job so as to be able to query its status later
    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar",
            TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true,
            em);
    JobRequest j = new JobRequest("MarsuApplication", "TestUser");
    int i = JqmClientFactory.getClient().enqueue(j);
    TestHelpers.waitFor(1, 10000, em);

    // HTTPS client - with
    KeyStore trustStore = KeyStore.getInstance("JKS");
    FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks"));
    try {
        trustStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class)
            .setParameter("i", TestHelpers.node.getId()).getSingleResult();
    HttpUriRequest rq = new HttpGet(
            "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i);
    jqmlogger.debug(rq.getURI());
    CloseableHttpResponse rs = cl.execute(rq);
    Assert.assertEquals(200, rs.getStatusLine().getStatusCode());

    rs.close();
    cl.close();
}

From source file:org.auraframework.integration.test.http.AuraResourceServletLoggingHttpTest.java

/**
 * test add for W-2792895/*ww  w . ja v  a 2 s  . c o  m*/
   also since I ask cache to log something when hit miss, this kind of verify W-2105858 as well
 */
@Test
public void testConcurrentGetRequests() throws Exception {
    // I tried to use obtainGetMethod(url) then perform(HttpGet) , but
    // our default httpClient use BasicClientConnectionManager, which doesn't work well with MultiThread
    // let's use PoolingHttpClientConnectionManager instead.
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    // Increase max total connection to 200 -- just some big number
    cm.setMaxTotal(200);
    // Increase default max connection per route to 20 -- again, just some big numer
    cm.setDefaultMaxPerRoute(20);
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

    String modeAndContext = getSimpleContext(Format.JS, false);
    String url = "/l/" + AuraTextUtil.urlencode(modeAndContext) + "/app.js";

    int numOfRequest = 5;
    List<Request> requests = new ArrayList<>();
    for (int i = 1; i <= numOfRequest; i++) {
        requests.add(new Request(httpClient, url));
    }

    ExecutorService excutor = Executors.newFixedThreadPool(numOfRequest);
    List<Future<Integer>> responses = new ArrayList<>();
    for (Request request : requests) {
        responses.add(excutor.submit(request));
    }
    for (Future<Integer> response : responses) {
        response.get();
    }

    int counter = 0;
    String message;
    List<LoggingEvent> logs = appender.getLog();
    for (LoggingEvent le : logs) {
        message = le.getMessage().toString();
        if (message.contains("StringsCache")) {
            counter++;
            assertTrue("get unexpected logging message for cache miss:" + message,
                    message.contains("cache miss for key: JS:DEV:"));
        }
    }
    //run this test right after server is up, we get one miss. second time, what we looking for is cached already, no miss.
    assertTrue("we should only have no more than one cache miss, instead we have " + counter, counter <= 1);
}

From source file:utils.HttpClientGenerator.java

public static CloseableHttpClient getHttpClient(boolean checkCert) {

    if (checkCert == false) {
        HttpClientBuilder b = HttpClientBuilder.create();

        // setup a Trust Strategy that allows all certificates.
        SSLContext sslContext = null;
        try {/*from w  ww . j a  v a 2s  .  c om*/
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            String err = "error occurred while creating SSL disables hhtp client";
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        b.setSslcontext(sslContext);

        // not to check Hostnames
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        //       create an SSL Socket Factory, to use weakened "trust strategy";
        //       and create a Registry, to register it.
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                (X509HostnameVerifier) hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();

        // creating connection-manager using our Registry.
        //      -- allows multi-threaded use
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        connMgr.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("localhost", 9443);
        connMgr.setMaxPerRoute(new HttpRoute(localhost), 10);
        b.setConnectionManager(connMgr);

        // finally, build the HttpClient;
        CloseableHttpClient client = b.build();
        return client;
    } else {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        // Increase default max connection per route to 20
        cm.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("localhost", 9443);
        cm.setMaxPerRoute(new HttpRoute(localhost), 10);
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm).build();
        return client;
    }
}

From source file:monasca.persister.repository.influxdb.InfluxV9RepoWriter.java

@Inject
public InfluxV9RepoWriter(final PersisterConfig config) {

    this.influxName = config.getInfluxDBConfiguration().getName();
    this.influxUrl = config.getInfluxDBConfiguration().getUrl() + "/write";
    this.influxUser = config.getInfluxDBConfiguration().getUser();
    this.influxPass = config.getInfluxDBConfiguration().getPassword();
    this.influxCreds = this.influxUser + ":" + this.influxPass;
    this.influxRetentionPolicy = config.getInfluxDBConfiguration().getRetentionPolicy();
    this.gzip = config.getInfluxDBConfiguration().getGzip();

    this.baseAuthHeader = "Basic " + new String(Base64.encodeBase64(this.influxCreds.getBytes()));

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(config.getInfluxDBConfiguration().getMaxHttpConnections());

    if (this.gzip) {

        this.httpClient = HttpClients.custom().setConnectionManager(cm)
                .addInterceptorFirst(new HttpRequestInterceptor() {

                    public void process(final HttpRequest request, final HttpContext context)
                            throws HttpException, IOException {
                        if (!request.containsHeader("Accept-Encoding")) {
                            request.addHeader("Accept-Encoding", "gzip");
                        }//from   w  ww. j  a v a2 s. c o  m
                    }
                }).addInterceptorFirst(new HttpResponseInterceptor() {

                    public void process(final HttpResponse response, final HttpContext context)
                            throws HttpException, IOException {
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            Header ceheader = entity.getContentEncoding();
                            if (ceheader != null) {
                                HeaderElement[] codecs = ceheader.getElements();
                                for (int i = 0; i < codecs.length; i++) {
                                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                                        return;
                                    }
                                }
                            }
                        }
                    }

                }).build();

    } else {

        this.httpClient = HttpClients.custom().setConnectionManager(cm).build();

    }
}

From source file:com.hp.octane.integrations.services.rest.SSCRestClientImpl.java

SSCRestClientImpl(OctaneSDK.SDKServicesConfigurer configurer) {
    if (configurer == null || configurer.pluginServices == null) {
        throw new IllegalArgumentException("invalid configurer");
    }//  ww  w.  java2 s  .  c om

    SSLContext sslContext = SSLContexts.createSystemDefault();
    HostnameVerifier hostnameVerifier = new OctaneRestClientImpl.CustomHostnameVerifier();
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MAX_TOTAL_CONNECTIONS);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connectionManager);

    httpClient = clientBuilder.build();
}

From source file:org.apache.jena.fuseki.embedded.TestFusekiTestAuth.java

@Test(expected = HttpException.class)
public void testServer_auth_bad_user() {
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials("USERUSER", PASSWORD);
    credsProvider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try (TypedInputStream in = HttpOp.execHttpGet(FusekiTestAuth.urlDataset(), "*/*", client, null)) {
    } catch (HttpException ex) {
        throw assertAuthHttpException(ex);
    }/*  w  ww .jav a 2  s. c  o  m*/
}

From source file:edu.kit.dama.staging.adalapi.protocol.SimpleHttp.java

@Override
public final CloseableHttpClient connectProtocolClient() throws AdalapiException {
    final CloseableHttpClient httpclient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()) // adds HTTP REDIRECT support to GET and POST methods 
            .build();/*  w  ww . j  a v  a2 s  . c om*/

    /* AbstractAuthentication auth = getAuthenticationMethod();
            
    if (!auth.isConnected()) {
    LOGGER.debug("Authentication is not connected, requesting user interaction");
    try {
        auth.authenticate();
    } catch (AuthenticationInputMethodException uaim) {
        throw new AdalapiSecurityException("Failed to authenticate", uaim);
    }
    LOGGER.debug("User interaction finished. Trying to connect protocol client");
    }
     */
    return httpclient;
}

From source file:sample.tomcat.X509ApplicationTests.java

private HttpClient httpClient() throws Exception {
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(socketFactory()).build();
    return httpclient;
}

From source file:org.openehealth.ipf.commons.ihe.fhir.SslAwareApacheRestfulClientFactory.java

protected synchronized HttpClient getNativeHttpClient() {
    if (httpClient == null) {

        // @formatter:off
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(getConnectTimeout())
                .setSocketTimeout(getSocketTimeout()).setConnectionRequestTimeout(getConnectionRequestTimeout())
                .setProxy(proxy).setStaleConnectionCheckEnabled(true).build();

        HttpClientBuilder builder = HttpClients.custom().useSystemProperties()
                .setDefaultRequestConfig(defaultRequestConfig).setMaxConnTotal(getPoolMaxTotal())
                .setMaxConnPerRoute(getPoolMaxPerRoute()).setConnectionTimeToLive(5, TimeUnit.SECONDS)
                .disableCookieManagement();

        if (securityInformation != null) {
            securityInformation.configureHttpClientBuilder(builder);
        }/*from ww w.j av a2  s. c o  m*/

        // Need to authenticate against proxy
        if (proxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }

        httpClient = builder.build();
    }

    return httpClient;
}