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.fcrepo.camel.ldpath.ClientFactory.java

/**
 * Create a linked data client suitable for use with a Fedora Repository.
 * @param authScope the authentication scope
 * @param credentials the credentials//w  ww.j  a  v a  2s.com
 * @param endpoints additional endpoints to enable on the client
 * @param providers additional providers to enable on the client
 * @return a configuration for use with an LDClient
 */
public static ClientConfiguration createClient(final AuthScope authScope, final Credentials credentials,
        final List<Endpoint> endpoints, final List<DataProvider> providers) {

    final ClientConfiguration client = new ClientConfiguration();

    if (credentials != null && authScope != null) {
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(authScope, credentials);
        client.setHttpClient(HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .useSystemProperties().build());
    }

    // manually add default Providers and Endpoints
    client.addProvider(new LinkedDataProvider());
    client.addProvider(new CacheProvider());
    client.addProvider(new RegexUriProvider());
    client.addProvider(new SPARQLProvider());
    client.addEndpoint(new LinkedDataEndpoint());

    // add any injected endpoints/providers
    endpoints.forEach(client::addEndpoint);
    providers.forEach(client::addProvider);

    return client;
}

From source file:edu.xiyou.fruits.WebCrawler.net.HttpRequest.java

public HttpRequest() {
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(Config.TTIME_OUT)
            .setSocketTimeout(Config.TTIME_OUT).build();
    client = HttpClients.custom().setUserAgent(
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36")
            .setRetryHandler(new DefaultHttpRequestRetryHandler(Config.RETRY, true))
            .setRedirectStrategy(new LaxRedirectStrategy()).setDefaultRequestConfig(requestConfig)
            .setConnectionManager(connectionManager).build();
}

From source file:org.springframework.cloud.config.server.environment.HttpClientConfigurableHttpConnectionFactory.java

private HttpClientBuilder lookupHttpClientBuilder(final URL url) {
    Map<String, HttpClientBuilder> builderMap = this.httpClientBuildersByUri.entrySet().stream()
            .filter(entry -> {//from   w  ww  .j  a va 2 s.c o m
                String key = entry.getKey();
                String spec = getUrlWithPlaceholders(url, key);
                if (spec.equals(key)) {
                    return true;
                }
                int index = spec.lastIndexOf("/");
                while (index != -1) {
                    spec = spec.substring(0, index);
                    if (spec.equals(key)) {
                        return true;
                    }
                    index = spec.lastIndexOf("/");
                }
                return false;
            }).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

    if (builderMap.isEmpty()) {
        this.log.warn(String.format("No custom http config found for URL: %s", url));
        return HttpClients.custom();
    }
    if (builderMap.size() > 1) {
        this.log.error(String.format(
                "More than one git repo URL template matched URL:"
                        + " %s, proxy and skipSslValidation config won't be applied. Matched templates: %s",
                url, builderMap.keySet().stream().collect(Collectors.joining(", "))));
        return HttpClients.custom();
    }
    return new ArrayList<>(builderMap.values()).get(0);
}

From source file:synapticloop.scaleway.api.ScalewayApiClient.java

/**
 * Instantiate a new API Client for the Scaleway API Provider, each API
 * client points to a specific Region.  Once this region is set, it cannot
 * be changed.  Instead instantiate a new API client for the new region,
 *
 * @param accessToken the access token that is authorised to invoke the API -
 *                    see the credentials section: <a href="https://cloud.scaleway.com/#/credentials">https://cloud.scaleway.com/#/credentials</a>
 *                    for access tokens/*  w ww  .  j  av a  2s  . c  o m*/
 * @param region      the scaleway datacentre region that this API points to (see
 *                    {@link Region} for all of the regions available at the moment)
 */
public ScalewayApiClient(String accessToken, Region region) {
    this.accessToken = accessToken;
    this.region = region;
    this.computeUrl = String.format(Constants.COMPUTE_URL, region);

    HttpClientBuilder httpBuilder = HttpClients.custom();
    httpBuilder.setUserAgent(Constants.USER_AGENT);
    this.httpclient = httpBuilder.build();

    Version currentJacksonVersion = new ObjectMapper().version();
    Version earliestSupportedVersion = new Version(2, 8, 7, null, currentJacksonVersion.getGroupId(),
            currentJacksonVersion.getArtifactId());
    int versionCompared = currentJacksonVersion.compareTo(earliestSupportedVersion);
    if (versionCompared < 0) {
        LOGGER.error("Jackson version: {}, version compared: {}", currentJacksonVersion.toString(),
                versionCompared);
        throw new RuntimeException(
                "Sorry, scaleway-api-client requires Jackson version 2.8.7 due to bugs in earlier versions.");
    }
}

From source file:com.digitalpebble.storm.crawler.protocol.httpclient.HttpProtocol.java

@Override
public void configure(final Config conf) {
    this.maxContent = ConfUtils.getInt(conf, "http.content.limit", 64 * 1024);
    String userAgent = getAgentString(ConfUtils.getString(conf, "http.agent.name"),
            ConfUtils.getString(conf, "http.agent.version"),
            ConfUtils.getString(conf, "http.agent.description"), ConfUtils.getString(conf, "http.agent.url"),
            ConfUtils.getString(conf, "http.agent.email"));

    this.responseTime = ConfUtils.getBoolean(conf, "http.store.responsetime", true);

    this.skipRobots = ConfUtils.getBoolean(conf, "http.skip.robots", false);

    robots = new HttpRobotRulesParser(conf);

    builder = HttpClients.custom().setUserAgent(userAgent).setConnectionManager(CONNECTION_MANAGER)
            .setConnectionManagerShared(true).disableRedirectHandling();

    String proxyHost = ConfUtils.getString(conf, "http.proxy.host", null);
    int proxyPort = ConfUtils.getInt(conf, "http.proxy.port", 8080);

    boolean useProxy = (proxyHost != null && proxyHost.length() > 0);

    // use a proxy?
    if (useProxy) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        builder.setRoutePlanner(routePlanner);
    }//from ww w  .j  a v  a  2s. c  o  m

    int timeout = ConfUtils.getInt(conf, "http.timeout", 10000);
    requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
}

From source file:com.aliyun.api.gateway.demo.Client.java

/**
 * <br>/*  w  w w .ja va 2  s  .  c  om*/
 * Client?httpsURL?keystore?storePasswordkeystore??? 
 * <a href="http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html">keytool</a>
 * 
 * @param appKey
 *            APP Key?APIAPP?
 * @param appSecret
 *            APP?APIAPP?
 * @param testEnv
 *            ?truefalse
 */
public Client(String appKey, String appSecret, boolean testEnv) {
    HttpClientBuilder builder = HttpClients.custom();
    try {
        SSLContext sslContext = null;
        if (testEnv) {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    //truetrue
                    return true;
                }
            }).build();
        } else {
            //keytool?keystorekeystore
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, null);
            sslContext = SSLContexts.custom().loadTrustMaterial(ks, new TrustSelfSignedStrategy()).build();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslsf);
    } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException | CertificateException
            | IOException e) {
        log.error(e.getMessage(), e);
    }
    httpClient = builder.setUserAgent(Constants.USER_AGENT).build();
    this.appKey = appKey;
    this.appSecret = appSecret;
    this.testEnv = testEnv;
}

From source file:com.collaide.fileuploader.requests.repository.FilesRequest.java

public CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(getMaxConnection());
        httpClient = HttpClients.custom().setConnectionManager(cm).build();
    }/* ww  w . ja v a2s.c o m*/
    return httpClient;
}

From source file:com.jivesoftware.os.routing.bird.http.client.HttpClientFactoryProvider.java

public HttpClientFactory createHttpClientFactory(Collection<HttpClientConfiguration> configurations,
        boolean latentClient) {

    HttpClientConfig httpClientConfig = locateConfig(configurations, HttpClientConfig.class,
            HttpClientConfig.newBuilder().build());
    HttpClientSSLConfig sslConfig = locateConfig(configurations, HttpClientSSLConfig.class, null);

    String scheme;//from w w  w  .j  a v  a  2s .  c o  m
    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
    if (sslConfig != null && sslConfig.isUseSsl()) {
        LayeredConnectionSocketFactory sslSocketFactory;
        if (sslConfig.getCustomSSLSocketFactory() != null) {
            sslSocketFactory = sslConfig.getCustomSSLSocketFactory();
        } else {
            sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
        }

        scheme = "https";
        poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", sslSocketFactory).build());
    } else {
        scheme = "http";
        poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
    }

    if (httpClientConfig.getMaxConnections() > 0) {
        poolingHttpClientConnectionManager.setMaxTotal(httpClientConfig.getMaxConnections());
    } else {
        poolingHttpClientConnectionManager.setMaxTotal(Integer.MAX_VALUE);
    }

    if (httpClientConfig.getMaxConnectionsPerHost() > 0) {
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpClientConfig.getMaxConnectionsPerHost());
    } else {
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(Integer.MAX_VALUE);
    }

    poolingHttpClientConnectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(
            httpClientConfig.getSocketTimeoutInMillis() > 0 ? httpClientConfig.getSocketTimeoutInMillis() : 0)
            .build());

    Closeable closeable;
    HttpClientConnectionManager clientConnectionManager;
    clientConnectionManager = poolingHttpClientConnectionManager;
    closeable = poolingHttpClientConnectionManager;

    return (OAuthSigner signer, String host, int port) -> {
        HttpClientBuilder httpClientBuilder = HttpClients.custom()
                .setConnectionManager(clientConnectionManager);

        CloseableHttpClient client = httpClientBuilder.build();
        HttpClient httpClient = new ApacheHttpClient441BackedHttpClient(scheme, host, port, signer, client,
                closeable, httpClientConfig.getCopyOfHeadersForEveryRequest());

        if (latentClient) {
            httpClient = new LatentHttpClient(httpClient);
        }
        return httpClient;
    };
}

From source file:org.jbpm.workbench.wi.backend.server.casemgmt.service.CaseProvisioningExecutor.java

protected int getManagementInterfaceStatus(String host, String managementPort, String password,
        String username) {//from w ww  .  j ava  2s  .co  m
    final CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(new AuthScope(host, Integer.valueOf(managementPort)),
            new UsernamePasswordCredentials(username, password));

    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider)
            .build()) {
        final HttpGet httpget = new HttpGet("http://" + host + ":" + managementPort + "/management");
        return httpClient.execute(httpget).getStatusLine().getStatusCode();
    } catch (Exception ex) {
        LOGGER.error("Exception while trying to connect to Wildfly Management interface", ex);
        return -1;
    }
}

From source file:com.microsoft.azure.hdinsight.spark.common.SparkInteractiveSessions.java

/**
 * create new session/*from w w w . java2 s  .  c  o m*/
 *
 * @param connectUrl : eg http://localhost:8998/sessions
 * @param kind       : spark or pyspark or sparkr
 * @return response result
 * @throws IOException
 */
public HttpResponse createNewSession(String connectUrl, String kind) throws IOException {
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider)
            .build();
    HttpPost httpPost = new HttpPost(connectUrl);
    httpPost.addHeader("Content-Type", "application/json");
    String jsonString = "{\"kind\" : \"" + kind + "\"}";
    StringEntity postingString = new StringEntity(jsonString);
    httpPost.setEntity(postingString);

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        return StreamUtil.getResultFromHttpResponse(response);
    }
}