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.apache.gobblin.http.ApacheHttpClient.java

public ApacheHttpClient(HttpClientBuilder builder, Config config,
        SharedResourcesBroker<GobblinScopeTypes> broker) {
    super(broker, HttpUtils.createApacheHttpClientLimiterKey(config));
    config = config.withFallback(FALLBACK);

    RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
            .setSocketTimeout(config.getInt(REQUEST_TIME_OUT_MS_KEY))
            .setConnectTimeout(config.getInt(CONNECTION_TIME_OUT_MS_KEY))
            .setConnectionRequestTimeout(config.getInt(CONNECTION_TIME_OUT_MS_KEY)).build();

    builder.disableCookieManagement().useSystemProperties().setDefaultRequestConfig(requestConfig);
    builder.setConnectionManager(getHttpConnManager(config));
    client = builder.build();
}

From source file:org.yamj.api.common.http.SimpleHttpClientBuilder.java

/**
 * Create the CloseableHttpClient//from  w  ww.  j  a  v a 2s . c  om
 *
 * @return
 */
public CloseableHttpClient build() {
    // create proxy
    HttpHost proxy = null;
    CredentialsProvider credentialsProvider = null;

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

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

    HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(maxConnTotal)
            .setMaxConnPerRoute(maxConnPerRoute).setProxy(proxy)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout)
                    .setSocketTimeout(socketTimeout).setProxy(proxy).build());

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

    // build the http client
    return builder.build();
}

From source file:org.nuxeo.connect.downloads.LocalDownloadingPackage.java

@Override
public void run() {
    setPackageState(PackageState.REMOTE);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT_MS)
            .setConnectTimeout(CONNECTION_TIMEOUT_MS);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    ProxyHelper.configureProxyIfNeeded(requestConfigBuilder, credentialsProvider, sourceUrl);
    httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
        setPackageState(PackageState.DOWNLOADING);
        HttpGet method = new HttpGet(sourceUrl);
        if (!sourceUrl.contains(ConnectUrlConfig.CONNECT_TEST_MODE_BASEURL + "test")) { // for testing
            Map<String, String> headers = SecurityHeaderGenerator.getHeaders();
            for (String headerName : headers.keySet()) {
                method.addHeader(headerName, headers.get(headerName));
            }/* w w w .  j  a  va2  s .c  o  m*/
        }
        try (CloseableHttpResponse httpResponse = httpClient.execute(method)) {
            int rc = httpResponse.getStatusLine().getStatusCode();
            switch (rc) {
            case HttpStatus.SC_OK:
                if (sourceSize == 0) {
                    Header clheader = httpResponse.getFirstHeader("content-length");
                    if (clheader != null) {
                        sourceSize = Long.parseLong(clheader.getValue());
                    }
                }
                InputStream in = httpResponse.getEntity().getContent();
                saveStreamAsFile(in);
                registerDownloadedPackage();
                setPackageState(PackageState.DOWNLOADED);
                break;

            case HttpStatus.SC_NOT_FOUND:
                throw new ConnectServerError(String.format("Package not found (%s).", rc));
            case HttpStatus.SC_FORBIDDEN:
                throw new ConnectServerError(String.format("Access refused (%s).", rc));
            case HttpStatus.SC_UNAUTHORIZED:
                throw new ConnectServerError(String.format("Registration required (%s).", rc));
            default:
                serverError = true;
                throw new ConnectServerError(String.format("Connect server HTTP response code %s.", rc));
            }
        }
    } catch (IOException e) { // Expected SocketTimeoutException or ConnectTimeoutException
        serverError = true;
        setPackageState(PackageState.REMOTE);
        log.debug(e, e);
        errorMessage = e.getMessage();
    } catch (ConnectServerError e) {
        setPackageState(PackageState.REMOTE);
        log.debug(e, e);
        errorMessage = e.getMessage();
    } finally {
        ConnectDownloadManager cdm = NuxeoConnectClient.getDownloadManager();
        cdm.removeDownloadingPackage(getId());
        completed = true;
    }
}

From source file:com.nextdoor.bender.ipc.es.ElasticSearchTransportFactory.java

@Override
protected CloseableHttpClient getClient(boolean useSSL, String url, Map<String, String> stringHeaders,
        int socketTimeout) {
    HttpClientBuilder cb = super.getClientBuilder(useSSL, url, stringHeaders, socketTimeout);
    ElasticSearchTransportConfig config = (ElasticSearchTransportConfig) super.config;

    if (config.getAuthConfig() != null) {
        if (config.getAuthConfig() instanceof BasicHttpAuthConfig) {
            cb = addUserPassAuth(cb, (BasicHttpAuthConfig) config.getAuthConfig());
        } else if (config.getAuthConfig() instanceof UrlSigningAuthConfig) {
            cb = addSigningAuth(cb, (UrlSigningAuthConfig) config.getAuthConfig());
        }//from  w  w  w.  j av a  2  s  .c o  m
    }

    RequestConfig rc = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(config.getTimeout())
            .build();
    cb.setDefaultRequestConfig(rc);

    return cb.build();
}

From source file:org.flowable.mule.MuleSendActivityBehavior.java

public void execute(DelegateExecution execution) {
    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);

    boolean isFlowable5Execution = false;
    Object payload = null;//from  ww  w .jav  a2 s . c  o  m
    if ((Context.getCommandContext() != null && Flowable5Util
            .isFlowable5ProcessDefinitionId(Context.getCommandContext(), execution.getProcessDefinitionId()))
            || (Context.getCommandContext() == null
                    && Flowable5Util.getFlowable5CompatibilityHandler() != null)) {

        payload = Flowable5Util.getFlowable5CompatibilityHandler()
                .getScriptingEngineValue(payloadExpressionValue, languageValue, execution);
        isFlowable5Execution = true;

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

    if (endpointUrlValue.startsWith("vm:")) {
        LocalMuleClient client = this.getMuleContext().getClient();
        MuleMessage message = new DefaultMuleMessage(payload, this.getMuleContext());
        MuleMessage resultMessage;
        try {
            resultMessage = client.send(endpointUrlValue, message);
        } catch (MuleException e) {
            throw new RuntimeException(e);
        }
        Object result = resultMessage.getPayload();
        if (resultVariableValue != null) {
            execution.setVariable(resultVariableValue, result);
        }

    } 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, "mule-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 FlowableException("Error setting message payload", e);
        }

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

        } catch (Exception e) {
            throw new RuntimeException(e);
        } 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 FlowableException("Failed to read response value", e);
            }
        }
    }

    if (isFlowable5Execution) {
        Flowable5Util.getFlowable5CompatibilityHandler().leaveExecution(execution);

    } else {
        this.leave(execution);
    }
}

From source file:com.jaspersoft.studio.data.adapter.JSSBuiltinDataFileServiceFactory.java

@Override
public DataFileService createService(JasperReportsContext context, DataFile dataFile) {
    if (dataFile instanceof RepositoryDataLocation) {
        return new RepositoryDataLocationService(context, (RepositoryDataLocation) dataFile);
    }/*from   w ww. jav  a2 s  .com*/
    if (dataFile instanceof HttpDataLocation) {
        return new HttpDataService(context, (HttpDataLocation) dataFile) {
            @Override
            protected CloseableHttpClient createHttpClient(Map<String, Object> parameters) {
                HttpClientBuilder clientBuilder = HttpClients.custom();
                HttpUtils.setupProxy(clientBuilder);
                // single connection
                BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
                clientBuilder.setConnectionManager(connManager);

                // ignore cookies for now
                RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                        .build();
                clientBuilder.setDefaultRequestConfig(requestConfig);

                HttpClientContext clientContext = HttpClientContext.create();

                setAuthentication(parameters, clientContext);

                CloseableHttpClient client = clientBuilder.build();
                return client;
            }
        };
    }
    return null;
}

From source file:sachin.spider.SpiderConfig.java

private String handleRedirect(String url) {
    try {/*from   ww w  .  j a v  a2  s.  co  m*/
        HttpGet httpget = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setRedirectsEnabled(true)
                .setCircularRedirectsAllowed(true).setRelativeRedirectsAllowed(true)
                .setConnectionRequestTimeout(getConnectionRequestTimeout()).setSocketTimeout(getSocketTimeout())
                .setConnectTimeout(getConnectionTimeout()).build();
        httpget.setConfig(requestConfig);
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setUserAgent(getUserAgentString());
        if (isAuthenticate()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(getUsername(), getPassword()));
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
        CloseableHttpClient httpclient = builder.build();
        HttpClientContext context = HttpClientContext.create();
        CloseableHttpResponse response = httpclient.execute(httpget, context);
        HttpHost target = context.getTargetHost();
        List<URI> redirectLocations = context.getRedirectLocations();
        URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
        url = location.toString();
        EntityUtils.consumeQuietly(response.getEntity());
        HttpClientUtils.closeQuietly(response);
    } catch (IOException | URISyntaxException ex) {
        Logger.getLogger(SpiderConfig.class.getName()).log(Level.SEVERE, null, ex);
        System.err.println(url);
    }
    return url;
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Because the creation of the SSLConnectionSocketFactory is expensive (reads from disk
 * the certs file) we will cache the client. The client is re-used so doesn't have any
 * target RTC server info associated with it.
 * @return an HttpClient//from  w  ww. j  a v  a2 s. c  om
 * @throws GeneralSecurityException
 */
private synchronized static CloseableHttpClient getClient() throws GeneralSecurityException {
    if (HTTP_CLIENT == null) {
        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        clientBuilder.setSSLSocketFactory(getSSLConnectionSocketFactory());

        // TODO to find out if this is sufficient, we can periodically dump the PoolStats
        clientBuilder.setMaxConnPerRoute(10);
        clientBuilder.setMaxConnTotal(100);

        // allow redirects on POST
        clientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        // How long to wait to get a connection from our connection manager. The default
        // timeouts are forever which is probably not good. 
        // TODO If we set it when creating the GET, PUT & POST maybe its not really needed here
        RequestConfig config = getRequestConfig(CONNECTION_REQUEST_TIMEOUT);
        clientBuilder.setDefaultRequestConfig(config);

        // This will create a client with the defaults (which includes the PoolingConnectionManager)
        HTTP_CLIENT = clientBuilder.build();
    }

    return HTTP_CLIENT;
}

From source file:edu.emory.bmi.medicurator.tcia.TciaQuery.java

private HttpClient getInsecureClient() throws Exception {
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }//from  ww w . j  a va  2s  .c o m
    }).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSSLSocketFactory(sslsf);
    if (Constants.PROXY_HOST != null && Constants.PROXY_PORT != null) {
        HttpHost proxy = new HttpHost(Constants.PROXY_HOST, Constants.PROXY_PORT, "http");
        builder.setProxy(proxy);
    }
    if (Constants.PROXY_USERNAME != null && Constants.PROXY_PASSWORD != null) {
        Credentials credentials = new UsernamePasswordCredentials(Constants.PROXY_USERNAME,
                Constants.PROXY_PASSWORD);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, credentials);
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    return builder.build();
}