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.deeplearning4j.examples.utilities.DataUtilities.java

/**
 * Download a remote file if it doesn't exist.
 * @param remoteUrl URL of the remote file.
 * @param localPath Where to download the file.
 * @return True if and only if the file has been downloaded.
 * @throws Exception IO error./*from   w w w .j  a v  a 2 s.  c  o  m*/
 */
public static boolean downloadFile(String remoteUrl, String localPath) throws IOException {
    boolean downloaded = false;
    if (remoteUrl == null || localPath == null)
        return downloaded;
    File file = new File(localPath);
    if (!file.exists()) {
        file.getParentFile().mkdirs();
        HttpClientBuilder builder = HttpClientBuilder.create();
        CloseableHttpClient client = builder.build();
        try (CloseableHttpResponse response = client.execute(new HttpGet(remoteUrl))) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                try (FileOutputStream outstream = new FileOutputStream(file)) {
                    entity.writeTo(outstream);
                    outstream.flush();
                    outstream.close();
                }
            }
        }
        downloaded = true;
    }
    if (!file.exists())
        throw new IOException("File doesn't exist: " + localPath);
    return downloaded;
}

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

protected static CloseableHttpClient createClient(final boolean disableRedirects) {
    final HttpClientBuilder client = HttpClientBuilder.create().setMaxConnPerRoute(MAX_VALUE)
            .setMaxConnTotal(MAX_VALUE);
    if (disableRedirects) {
        client.disableRedirectHandling();
    }//from  w w  w  . j  ava2 s. com
    return client.build();
}

From source file:org.finra.herd.dao.helper.HttpClientHelper.java

/**
 * Creates a new HTTP client./*from  w w w  . j  a v  a2  s .  c  om*/
 *
 * @param trustSelfSignedCertificate specifies whether to trust a self-signed certificate
 * @param disableHostnameVerification specifies whether to turn off hostname verification
 *
 * @return the HTTP client
 * @throws KeyStoreException if a key store exception occurs
 * @throws NoSuchAlgorithmException if a no such algorithm exception occurs
 * @throws KeyManagementException if key management exception
 */
public CloseableHttpClient createHttpClient(Boolean trustSelfSignedCertificate,
        Boolean disableHostnameVerification)
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    // Create an HTTP client builder.
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    // Create an SSL context builder.
    SSLContextBuilder sslContextBuilder = SSLContexts.custom();

    // If specified, setup a trust strategy that allows all certificates.
    if (BooleanUtils.isTrue(trustSelfSignedCertificate)) {
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    }

    // If specified, turn hostname verification off.
    HostnameVerifier hostnameVerifier = BooleanUtils.isTrue(disableHostnameVerification)
            ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
            : SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;

    // Create and assign an SSL connection socket factory.
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build(), hostnameVerifier);
    httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);

    // Build and return an HTTP client.
    return httpClientBuilder.build();
}

From source file:org.flowable.app.service.editor.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {/* ww  w.j  a v  a2s  . c  o m*/
    String deployApiUrl = environment.getRequiredProperty("deployment.api.url");
    String basicAuthUser = environment.getRequiredProperty("idm.admin.user");
    String basicAuthPassword = environment.getRequiredProperty("idm.admin.password");

    if (deployApiUrl.endsWith("/") == false) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(
            Base64.encodeBase64((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    SSLConnectionSocketFactory sslsf = null;
    try {
        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.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            logger.error("Invalid deploy result code: {}", response.getStatusLine());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }
    } catch (IOException ioe) {
        logger.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                logger.warn("Exception while closing http client", e);
            }
        }
    }
}

From source file:org.flowable.http.impl.HttpActivityBehaviorImpl.java

public HttpActivityBehaviorImpl() {
    HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {/*from  www.  j  a  v  a 2  s.  c om*/
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    // Build http client
    client = httpClientBuilder.build();
    LOGGER.info("HTTP client is initialized");

    // Shutdown hook to close the http client
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if (client != null) {
                try {
                    client.close();
                    LOGGER.info("HTTP client is closed");
                } catch (Throwable e) {
                    LOGGER.error("Could not close http client", e);
                }
            }
        }
    });
}

From source file:org.flowable.ui.admin.service.engine.FlowableClientService.java

public CloseableHttpClient getHttpClient(String userName, String password) {

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

    SSLConnectionSocketFactory sslsf = null;
    try {/*from w w  w . j ava2  s. com*/
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (Exception e) {
        LOGGER.warn("Could not configure HTTP client to use SSL", e);
    }

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    if (preemptiveBasicAuthentication) {
        String auth = userName + ":" + password;
        httpClientBuilder.setDefaultHeaders(Collections.singletonList(new BasicHeader(AUTH.WWW_AUTH_RESP,
                "Basic " + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8)))));
    }

    if (sslsf != null) {
        httpClientBuilder.setSSLSocketFactory(sslsf);
    }

    return httpClientBuilder.build();
}

From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java

/**
 * Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers
 * many opportunities for customization. By default, <a href=
 * "http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html">
 * SystemDefaultHttpClient</a> is used if available, otherwise it falls back
 * to://w  w w  .j ava  2 s.c  om
 * 
 * <pre>
 * new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams)
 * </pre>
 * 
 * SystemDefaultHttpClient uses PoolingClientConnectionManager. In any case,
 * it should be thread-safe.
 */
protected HttpClient createHttpClient(HttpParams hcParams) {
    try {

        String negotiateURL = getConfigParam("negotiate.url");
        String negotiateSPN = getConfigParam("negotiate.spn");
        if (negotiateURL != null && negotiateSPN != null) {
            System.out.println("negotiate url:" + negotiateURL);
            System.out.println("negotiate spn:" + negotiateSPN);
            // initialize the Windows security Context to get the negotiate
            // client token
            IWindowsSecurityContext clientContext = null;
            IWindowsCredentialsHandle clientCredentials = null;
            clientContext = WindowsSecurityContextImpl.getCurrent(SECURITY_PACKAGE, negotiateSPN);
            clientCredentials = WindowsCredentialsHandleImpl.getCurrent(SECURITY_PACKAGE);
            clientCredentials.initialize();
            String username = WindowsAccountImpl.getCurrentUsername();
            System.out.println("credentials for user " + username + " get prepared");
            byte[] token = clientContext.getToken();
            // encode the token with Base64 to be able to add it to the http
            // header
            String clientToken = Base64.encodeBase64String(token);
            System.out.println("clientToken" + clientToken);
            // if there is only a negotiate url the rest of the
            // authorization is based on cookies
            // so we need to support them.
            CookieStore cookieStore = new BasicCookieStore();
            RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
            HttpClientContext context = HttpClientContext.create();
            proxyContext = context;
            context.setCookieStore(cookieStore);
            HttpClient httpClient = HttpClients.custom().disableRedirectHandling()
                    .setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build();

            // first we need to act as a normal browser to get a http 401
            // with negotiate header
            doActAsBrowser = true;
            HttpGet browserHttpGet = new HttpGet(negotiateURL);
            addBrowserHeader(browserHttpGet);
            HttpResponse rep = httpClient.execute(browserHttpGet, context);

            if (rep.getStatusLine().getStatusCode() == 401) {
                System.out.println("negotiate requested - sending negotiate client token");
                HttpGet negotiateHttpGet = new HttpGet(negotiateURL);
                addBrowserHeader(negotiateHttpGet);
                negotiateHttpGet.addHeader("Authorization", "Negotiate " + clientToken);
                HttpResponse response = httpClient.execute(negotiateHttpGet, context);
                System.out.println(
                        "http result code of negotiate request:" + response.getStatusLine().getStatusCode());
                // now the url needs to be called periodically to keep the
                // cookie and connection alive
                String refreshTimeString = getConfigParam("negotiate.refreshtime");
                long refreshTime = 1000000;
                if (refreshTimeString != null) {
                    refreshTime = Long.parseLong(refreshTimeString);
                }
                HttpClientRefreshThread thread = new HttpClientRefreshThread(refreshTime, negotiateURL);
                thread.start();
                List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies();
                cookieString = "";
                int size = cookies.size() - 1;
                for (int i = 0; i < cookies.size(); i++) {
                    cookieString += cookies.get(i).getName();
                    cookieString += "=";
                    cookieString += cookies.get(i).getValue();
                    if (i != size)
                        cookieString += "; ";
                }
            } else {
                System.out.println("No negotiate requested");
            }
        } else {
            if (!WinHttpClients.isWinAuthAvailable()) {
                System.out.println("Integrated Win auth is not supported!!!");
            } else {
                HttpClientBuilder builder = WinHttpClients.custom();
                Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                        .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                        .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                        .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                        .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();
                builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
                String username = getConfigParam("user");
                String password = getConfigParam("password");
                String domain = getConfigParam("domain");
                String host = getConfigParam("host");
                if (username != null) {
                    NTCredentials cred = new NTCredentials(username, password, host, domain);
                    CredentialsProvider credsProvider = new WindowsCredentialsProvider(
                            new SystemDefaultCredentialsProvider());
                    credsProvider.setCredentials(AuthScope.ANY, cred);
                    builder.setDefaultCredentialsProvider(credsProvider);
                }
                builder.disableCookieManagement();
                builder.disableRedirectHandling();
                return builder.build();
            }

            // as of HttpComponents v4.2, this class is better since it uses
            // System
            // Properties:
            Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient");
            Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class);
            return (HttpClient) constructor.newInstance(hcParams);
        }
    } catch (ClassNotFoundException e) {
        // no problem; use v4.1 below
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // Fallback on using older client:
    return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams);
}

From source file:org.opennms.core.web.HttpClientWrapper.java

public CloseableHttpClient getClient() {
    if (m_httpClient == null) {
        final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

        if (!m_reuseConnections) {
            httpClientBuilder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
        }/*w w  w  .ja  v  a  2 s  .  c o  m*/
        if (m_usePreemptiveAuth) {
            enablePreemptiveAuth(httpClientBuilder);
        }
        if (m_useSystemProxySettings) {
            httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
        }
        if (!isEmpty(m_cookieSpec)) {
            requestConfigBuilder.setCookieSpec(m_cookieSpec);
        }
        if (m_cookieStore != null) {
            httpClientBuilder.setDefaultCookieStore(m_cookieStore);
        }
        if (m_username != null) {
            setCredentials(httpClientBuilder, m_username, m_password);
        }
        if (m_socketTimeout != null) {
            requestConfigBuilder.setSocketTimeout(m_socketTimeout);
        }
        if (m_connectionTimeout != null) {
            requestConfigBuilder.setConnectTimeout(m_connectionTimeout);
        }
        if (m_retries != null) {
            httpClientBuilder.setRetryHandler(new HttpRequestRetryOnExceptionHandler(m_retries, false));
        }
        if (m_sslContext.size() != 0) {
            configureSSLContext(httpClientBuilder);
        }
        for (final HttpRequestInterceptor interceptor : m_requestInterceptors) {
            httpClientBuilder.addInterceptorLast(interceptor);
        }
        for (final HttpResponseInterceptor interceptor : m_responseInterceptors) {
            httpClientBuilder.addInterceptorLast(interceptor);
        }
        if (m_useLaxRedirect) {
            httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
        }
        httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
        m_httpClient = httpClientBuilder.build();
    }
    return m_httpClient;
}

From source file:org.openstreetmap.josm.plugins.mapillary.oauth.UploadUtils.java

/**
 * @param file File that is going to be uploaded
 * @param hash Information attached to the upload
 * @throws IllegalArgumentException if the hash doesn't contain all the needed keys.
 *///  w w  w . java2s .  c  om
private static void uploadFile(File file, Map<String, String> hash) throws IOException {
    HttpClientBuilder builder = HttpClientBuilder.create();
    HttpPost httpPost = new HttpPost(UPLOAD_URL);

    try (CloseableHttpClient httpClient = builder.build()) {
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        for (String key : keys) {
            if (hash.get(key) == null)
                throw new IllegalArgumentException();
            entityBuilder.addPart(key, new StringBody(hash.get(key), ContentType.TEXT_PLAIN));
        }
        entityBuilder.addPart("file", new FileBody(file));
        HttpEntity entity = entityBuilder.build();
        httpPost.setEntity(entity);
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            if (response.getStatusLine().toString().contains("204")) {
                PluginState.imageUploaded();
                Main.info(PluginState.getUploadString() + " (Mapillary)");
            } else {
                Main.info("Upload error");
            }
        }
    }
    if (!file.delete()) {
        Main.error("MapillaryPlugin: File could not be deleted during upload");
    }
    MapillaryUtils.updateHelpText();
}

From source file:org.tanaguru.util.http.HttpRequestHandler.java

private CloseableHttpClient getHttpClient(String url) {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectionTimeout).build();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager());
    httpClientBuilder.setUserAgent(TANAGURU_USER_AGENT);
    if (isProxySet(url)) {
        LOGGER.debug(("Set proxy with " + proxyHost + " and " + proxyPort));
        httpClientBuilder.setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort)));
        if (isProxyCredentialSet()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyHost, Integer.valueOf(proxyPort)),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            LOGGER.debug(("Set proxy credentials " + proxyHost + " and " + proxyPort + " and " + proxyUser
                    + " and " + proxyPassword));
        }/*from w ww  . j  a  v a 2 s  . c om*/
    }
    return httpClientBuilder.build();
}