Example usage for org.apache.http.impl.client HttpClientBuilder build

List of usage examples for org.apache.http.impl.client HttpClientBuilder build

Introduction

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

Prototype

public CloseableHttpClient build() 

Source Link

Usage

From source file:org.metaeffekt.dcc.controller.execution.RemoteExecutor.java

private CloseableHttpClient instantiateHttpClientWithTimeout() throws IOException, GeneralSecurityException {
    final KeyStore keyStore = loadKeyStore(sslConfiguration.getKeyStoreLocation(),
            sslConfiguration.getKeyStorePassword());

    final KeyStore trustStore = loadKeyStore(sslConfiguration.getTrustStoreLocation(),
            sslConfiguration.getTrustStorePassword());

    final SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    sslContextBuilder.loadKeyMaterial(keyStore, sslConfiguration.getKeyStorePassword());
    sslContextBuilder.loadTrustMaterial(trustStore);

    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSslcontext(sslContextBuilder.build());
    builder.setHostnameVerifier(new AllowAllHostnameVerifier());

    final CloseableHttpClient client = builder.build();
    return client;
}

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

private CloseableHttpClient createHttpClient() {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    // setting the SoTimeout (which is configured in seconds)
    builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(1000 * config.getSoTimeout()).build());
    builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    return builder.build();
}

From source file:com.muk.services.configuration.ServiceConfig.java

@Bean
public CloseableHttpClient genericHttpClient() {
    final HttpClientConnectionManager manager = genericConnectionManager();
    final Builder reqConfig = RequestConfig.custom();
    reqConfig.setConnectionRequestTimeout(5000);
    reqConfig.setSocketTimeout(5000);/*ww  w .  j  a  v a  2s .c o  m*/
    reqConfig.setCircularRedirectsAllowed(false);
    reqConfig.setRedirectsEnabled(false);
    reqConfig.setCookieSpec(CookieSpecs.IGNORE_COOKIES);

    final HttpClientBuilder builder = HttpClientBuilder.create().disableRedirectHandling()
            .setConnectionManager(manager).setDefaultRequestConfig(reqConfig.build());

    staleConnectionExecutor().execute(new IdleConnectionMonitor(manager));

    return builder.build();
}

From source file:com.liferay.sync.engine.session.Session.java

public Session(URL url, String oAuthConsumerKey, String oAuthConsumerSecret, String oAuthToken,
        String oAuthTokenSecret, boolean trustSelfSigned, int maxConnections) {

    if (maxConnections == Integer.MAX_VALUE) {
        _executorService = Executors.newCachedThreadPool();
    } else {/*from   w w  w.j  a  v  a 2s  . com*/
        _executorService = Executors.newFixedThreadPool(maxConnections);
    }

    HttpClientBuilder httpClientBuilder = createHttpClientBuilder(trustSelfSigned, maxConnections);

    httpClientBuilder.setConnectionManager(_getHttpClientConnectionManager(trustSelfSigned));

    _httpClient = httpClientBuilder.build();

    _httpHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());

    _oAuthConsumer = new CommonsHttpOAuthConsumer(oAuthConsumerKey, oAuthConsumerSecret);

    _oAuthConsumer.setTokenWithSecret(oAuthToken, oAuthTokenSecret);

    _oAuthEnabled = true;
}

From source file:org.activiti.webservice.WebServiceSendActivitiBehavior.java

public void execute(ActivityExecution execution) throws Exception {
    String endpointUrlValue = this.getStringFromField(this.endpointUrl, execution);
    String languageValue = this.getStringFromField(this.language, execution);
    String payloadExpressionValue = this.getStringFromField(this.payloadExpression, execution);
    String resultVariableValue = this.getStringFromField(this.resultVariable, execution);
    String usernameValue = this.getStringFromField(this.username, execution);
    String passwordValue = this.getStringFromField(this.password, execution);

    ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
    Object payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution);

    if (endpointUrlValue.startsWith("vm:")) {
        LocalWebServiceClient client = this.getWebServiceContext().getClient();
        WebServiceMessage message = new DefaultWebServiceMessage(payload, this.getWebServiceContext());
        WebServiceMessage resultMessage = client.send(endpointUrlValue, message);
        Object result = resultMessage.getPayload();
        if (resultVariableValue != null) {
            execution.setVariable(resultVariableValue, result);
        }//from   w w  w .j  a  va  2 s.  co  m

    } else {

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        if (usernameValue != null && passwordValue != null) {
            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(usernameValue,
                    passwordValue);
            provider.setCredentials(new AuthScope("localhost", -1, "webservice-realm"), credentials);
            clientBuilder.setDefaultCredentialsProvider(provider);
        }

        HttpClient client = clientBuilder.build();

        HttpPost request = new HttpPost(endpointUrlValue);

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(payload);
            oos.flush();
            oos.close();

            request.setEntity(new ByteArrayEntity(baos.toByteArray()));

        } catch (Exception e) {
            throw new ActivitiException("Error setting message payload", e);
        }

        byte[] responseBytes = null;
        try {
            // execute the POST request
            HttpResponse response = client.execute(request);
            responseBytes = IOUtils.toByteArray(response.getEntity().getContent());

        } finally {
            // release any connection resources used by the method
            request.releaseConnection();
        }

        if (responseBytes != null) {
            try {
                ByteArrayInputStream in = new ByteArrayInputStream(responseBytes);
                ObjectInputStream is = new ObjectInputStream(in);
                Object result = is.readObject();
                if (resultVariableValue != null) {
                    execution.setVariable(resultVariableValue, result);
                }
            } catch (Exception e) {
                throw new ActivitiException("Failed to read response value", e);
            }
        }
    }

    this.leave(execution);
}

From source file:emea.summit.architects.HackathlonAPIResource.java

private String httpCall(String httpMethod, String serviceURL, String data) {
    String result = "Not valid request for \n" + "HTTP METHOD" + httpMethod + "\n" + "URL" + serviceURL + "\n"
            + "Content" + data;

    System.out.println("<===================== Calling External Service  ======================>");
    System.out.println("     HTTP METHOD : " + httpMethod);
    System.out.println("     URL         : " + serviceURL);
    System.out.println("     Content     : " + data);
    //System.out.println("<======================================================================>");

    if (httpMethod != null || httpMethod.equals("GET") || httpMethod.equals("POST")
            || httpMethod.equals("PUT")) {

        try {//from   ww  w  .j  a  v  a2 s  . c  o  m
            HttpClientBuilder builder = HttpClientBuilder.create();
            CloseableHttpClient client = builder.build();

            //HttpUriRequest request = new HttpGet(serviceURL+"api/hackathlon/info");
            HttpUriRequest request;
            if (httpMethod.equalsIgnoreCase("GET")) {
                result = getRequest(serviceURL, "application/json");
            } else if (httpMethod.equalsIgnoreCase("POST")) {
                // eg. http://www.programcreek.com/java-api-examples/org.apache.http.entity.StringEntity
                StringEntity content = new StringEntity(data, "UTF-8");
                result = postRequest(serviceURL, "application/json", content);
            } else {
                result = putRequest(serviceURL, "application/json");
            }
            System.out.println("<============================= RESPONSE ==============================> ");
            System.out.println("    " + result);
            System.out.println("<======================================================================>");

        } catch (Exception e) {
            System.out.println("****************************************************************");
            System.out.println("FAILED - CALLING SERVICE AT " + serviceURL);
            System.out.println(e.getMessage());
            System.out.println("****************************************************************");
            return result;
        }
        System.out.println("****************************************************************");
        System.out.println("SUCCESS - CALLING SERVICE AT " + serviceURL);
        System.out.println("****************************************************************");
        return result;

    }
    System.out.println("****************************************************************");
    System.out.println("FAILED - CALLING SERVICE AT " + serviceURL);
    System.out.println("****************************************************************");
    return result;
}

From source file:com.terracotta.nrplugin.rest.nr.MetricReporter.java

@PostConstruct
private void init() {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000)
            .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();
    HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig);
    if (useProxy) {
        int parsedProxyPort = 8080;
        try {/*from w  w  w  .j  a  v  a 2  s .  c  om*/
            parsedProxyPort = Integer.parseInt(proxyPort);
        } catch (NumberFormatException e) {
            log.warn("Could not parse the proxyPort. Defaulting to 8080.");
            parsedProxyPort = 8080;
        }

        HttpHost proxy = new HttpHost(proxyHostname, parsedProxyPort, proxyScheme);
        httpClientBuilder.setProxy(proxy);
        log.info("Configuring HttpClient with proxy '" + proxy.toString() + "'");
    }
    httpClient = httpClientBuilder.build();
}

From source file:fr.cnes.sitools.metacatalogue.resources.proxyservices.RedirectorHttps.java

/**
 * CloseableHttpResponse//  w ww  .j a  va2  s.c  o m
 * 
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public CloseableHttpResponse getCloseableResponse(String url, Series<Cookie> cookies)
        throws ClientProtocolException, IOException {

    HttpClientBuilder httpclientBuilder = HttpClients.custom();

    if (withproxy) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                ProxySettings.getProxyUser(), ProxySettings.getProxyPassword()));
        httpclientBuilder.setDefaultCredentialsProvider(credsProvider).build();
    }
    CloseableHttpClient httpclient = httpclientBuilder.build();

    HttpClientContext context = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();

    Iterator<Cookie> iter = cookies.iterator();

    while (iter.hasNext()) {
        Cookie restCookie = iter.next();
        BasicClientCookie cookie = new BasicClientCookie(restCookie.getName(), restCookie.getValue());
        // cookie.setDomain(restCookie.getDomain());
        cookie.setDomain(getDomainName(url));
        cookie.setPath(restCookie.getPath());
        cookie.setSecure(true);
        // cookie.setExpiryDate(restCookie);
        cookieStore.addCookie(cookie);
    }

    context.setCookieStore(cookieStore);

    HttpGet httpget = new HttpGet(url);

    Builder configBuilder = RequestConfig.custom();

    if (withproxy) {
        HttpHost proxy = new HttpHost(ProxySettings.getProxyHost(),
                Integer.parseInt(ProxySettings.getProxyPort()), "http");
        configBuilder.setProxy(proxy).build();
    }

    RequestConfig config = configBuilder.build();
    httpget.setConfig(config);

    return httpclient.execute(httpget, context);

}

From source file:org.yamj.core.tools.web.PoolingHttpClientBuilder.java

@SuppressWarnings("resource")
public PoolingHttpClient build() {
    // create proxy
    HttpHost proxy = null;/*w w  w. j  a v  a  2  s . co m*/
    CredentialsProvider credentialsProvider = null;

    if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) {
        proxy = new HttpHost(proxyHost, proxyPort);

        if (StringUtils.isNotBlank(proxyUsername) && StringUtils.isNotBlank(proxyPassword)) {
            if (systemProperties) {
                credentialsProvider = new SystemDefaultCredentialsProvider();
            } else {
                credentialsProvider = new BasicCredentialsProvider();
            }
            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }
    }

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
    connManager.setMaxTotal(connectionsMaxTotal);
    connManager.setDefaultMaxPerRoute(connectionsMaxPerRoute);

    HttpClientBuilder builder = HttpClientBuilder.create().setConnectionManager(connManager).setProxy(proxy)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectionTimeout)
                    .setSocketTimeout(socketTimeout).setProxy(proxy).build());

    // use system properties
    if (systemProperties) {
        builder.useSystemProperties();
    }

    // build the client
    PoolingHttpClient wrapper = new PoolingHttpClient(builder.build(), connManager);
    wrapper.addGroupLimit(".*", 1); // default limit, can be overwritten

    if (StringUtils.isNotBlank(maxDownloadSlots)) {
        LOG.debug("Using download limits: {}", maxDownloadSlots);

        Pattern pattern = Pattern.compile(",?\\s*([^=]+)=(\\d+)");
        Matcher matcher = pattern.matcher(maxDownloadSlots);
        while (matcher.find()) {
            String group = matcher.group(1);
            try {
                final Integer maxResults = Integer.valueOf(matcher.group(2));
                wrapper.addGroupLimit(group, maxResults);
                LOG.trace("Added download slot '{}' with max results {}", group, maxResults);
            } catch (NumberFormatException error) {
                LOG.debug("Rule '{}' is no valid regexp, ignored", group);
            }
        }
    }

    return wrapper;
}

From source file:org.flowable.app.service.idm.RemoteIdmServiceImpl.java

protected JsonNode callRemoteIdmService(String url, String username, String password) {
    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Basic "
            + new String(Base64.encodeBase64((username + ":" + password).getBytes(Charset.forName("UTF-8")))));

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    SSLConnectionSocketFactory sslsf = null;
    try {//www  .  jav  a2s  .  co m
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        clientBuilder.setSSLSocketFactory(sslsf);
    } catch (Exception e) {
        logger.warn("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return objectMapper.readTree(response.getEntity().getContent());
        }
    } catch (Exception e) {
        logger.warn("Exception while getting token", e);
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                logger.warn("Exception while closing http client", e);
            }
        }
    }
    return null;
}