Example usage for org.apache.http.impl.conn SystemDefaultRoutePlanner SystemDefaultRoutePlanner

List of usage examples for org.apache.http.impl.conn SystemDefaultRoutePlanner SystemDefaultRoutePlanner

Introduction

In this page you can find the example usage for org.apache.http.impl.conn SystemDefaultRoutePlanner SystemDefaultRoutePlanner.

Prototype

public SystemDefaultRoutePlanner(final ProxySelector proxySelector) 

Source Link

Usage

From source file:org.springframework.cloud.config.server.support.HttpClientSupport.java

public static HttpClientBuilder builder(HttpEnvironmentRepositoryProperties environmentProperties)
        throws GeneralSecurityException {
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    if (environmentProperties.isSkipSslValidation()) {
        sslContextBuilder.loadTrustMaterial(null, (certificate, authType) -> true);
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }/*from   www .j a v a2s .  c o m*/

    if (!CollectionUtils.isEmpty(environmentProperties.getProxy())) {
        ProxyHostProperties httpsProxy = environmentProperties.getProxy()
                .get(ProxyHostProperties.ProxyForScheme.HTTPS);
        ProxyHostProperties httpProxy = environmentProperties.getProxy()
                .get(ProxyHostProperties.ProxyForScheme.HTTP);

        httpClientBuilder.setRoutePlanner(new SchemeBasedRoutePlanner(httpsProxy, httpProxy));
        httpClientBuilder
                .setDefaultCredentialsProvider(new ProxyHostCredentialsProvider(httpProxy, httpsProxy));
    } else {
        httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
        httpClientBuilder.setDefaultCredentialsProvider(new SystemDefaultCredentialsProvider());
    }

    int timeout = environmentProperties.getTimeout() * 1000;
    return httpClientBuilder.setSSLContext(sslContextBuilder.build()).setDefaultRequestConfig(
            RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build());
}

From source file:org.cee.net.impl.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient() {
    return HttpClients.custom().setConnectionManager(connectionManager)
            .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
            .addInterceptorFirst(new RedirectHttpResponseInterceptor()).build();
}

From source file:de.undercouch.gradle.tasks.download.internal.DefaultHttpClientFactory.java

@Override
public CloseableHttpClient createHttpClient(HttpHost httpHost, boolean acceptAnyCertificate) {
    HttpClientBuilder builder = HttpClientBuilder.create();

    //configure proxy from system environment
    builder.setRoutePlanner(new SystemDefaultRoutePlanner(null));

    //accept any certificate if necessary
    if ("https".equals(httpHost.getSchemeName()) && acceptAnyCertificate) {
        SSLConnectionSocketFactory icsf = getInsecureSSLSocketFactory();
        builder.setSSLSocketFactory(icsf);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", icsf).build();
        HttpClientConnectionManager cm = new BasicHttpClientConnectionManager(registry);
        builder.setConnectionManager(cm);
    }//from w ww .ja  va 2 s .c om

    //add an interceptor that replaces the invalid Content-Type
    //'none' by 'identity'
    builder.addInterceptorFirst(new ContentEncodingNoneInterceptor());

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

From source file:com.kenai.redminenb.repository.RedmineManagerFactoryHelper.java

public static HttpClient getTransportConfig() {
    /**//from   w w w.  ja v a  2  s.c o m
    * Implement a minimal hostname verifier. This is needed to be able to use
    * hosts with certificates, that don't match the used hostname (VServer).
     *
     * This is implemented by first trying the "Browser compatible" hostname
     * verifier and if that fails, fall back to the default java hostname
     * verifier.
     *
     * If the default case the hostname verifier in java always rejects, but
     * for netbeans the "SSL Certificate Exception" module is available that
     * catches this and turns a failure into a request to the GUI user.
     */
    X509HostnameVerifier hostnameverified = new X509HostnameVerifier() {
        @Override
        public void verify(String string, SSLSocket ssls) throws IOException {
            if (SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER.verify(string, ssls.getSession())) {
                return;
            }
            if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls.getSession())) {
                throw new SSLException("Hostname did not verify");
            }
        }

        @Override
        public void verify(String string, X509Certificate xc) throws SSLException {
            throw new SSLException("Check not implemented yet");
        }

        @Override
        public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            throw new SSLException("Check not implemented yet");
        }

        @Override
        public boolean verify(String string, SSLSession ssls) {
            if (SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER.verify(string, ssls)) {
                return true;
            }
            return HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls);
        }
    };

    try {
        SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                hostnameverified);

        HttpClient hc = HttpClientBuilder.create()
                .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                .setSSLSocketFactory(scsf).build();

        return hc;
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.floragunn.searchguard.HeaderAwareJestClientFactory.java

protected HttpRoutePlanner getRoutePlanner() {
    return new SystemDefaultRoutePlanner(ProxySelector.getDefault());
}

From source file:com.openshift.internal.restclient.authorization.AuthorizationClient.java

private IAuthorizationContext getContextUsingCredentials(final String baseURL,
        CredentialsProvider credentialsProvider) {

    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;//from   w w w.j  a va2 s  . com
    try {
        OpenShiftAuthorizationRedirectStrategy redirectStrategy = new OpenShiftAuthorizationRedirectStrategy(
                openshiftClient);
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT)
                .setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT)
                .setStaleConnectionCheckEnabled(true).build();
        client = HttpClients.custom().setRedirectStrategy(redirectStrategy)
                .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                .setHostnameVerifier(hostnameVerifier).setDefaultCredentialsProvider(credentialsProvider)
                .setSslcontext(sslContext).setDefaultRequestConfig(defaultRequestConfig).build();
        HttpGet request = new HttpGet(new URIBuilder(String.format("%s/oauth/authorize", baseURL))
                .addParameter("response_type", "token")
                .addParameter("client_id", "openshift-challenging-client").build());
        request.addHeader("X-CSRF-Token", "1");
        response = client.execute(request);
        return redirectStrategy.getAuthorizationContext();
    } catch (URISyntaxException e) {
        throw new OpenShiftException(e, String
                .format("Unvalid URI while trying to get an authorization context for server %s", baseURL));
    } catch (ClientProtocolException e) {
        throw new OpenShiftException(e, String.format(
                "Client protocol exception while trying to get authorization context for server %s", baseURL));
    } catch (IOException e) {
        throw new OpenShiftException(e,
                String.format("%s while trying to get an authorization context for server %s",
                        e.getClass().getName(), baseURL));
    } finally {
        close(response);
        close(client);
    }

}

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

public static HttpRoutePlanner getHttpRoutePlanner() {
    if (_httpRoutePlanner != null) {
        return _httpRoutePlanner;
    }/*  w w w  .jav a 2 s.c  o  m*/

    ProxySearch proxySearch = ProxySearch.getDefaultProxySearch();

    ProxySelector proxySelector = proxySearch.getProxySelector();

    if (proxySelector == null) {
        proxySelector = ProxySelector.getDefault();
    }

    _httpRoutePlanner = new SystemDefaultRoutePlanner(proxySelector);

    return _httpRoutePlanner;
}

From source file:com.maxmind.ws.HTTPBase.java

boolean querySingleServer(String hostname) {
    String scheme, url2;//from  w  w  w  .  jav a  2s.c  om

    // check if we using the Secure HTTPS protocol
    scheme = isSecure ? "https://" : "http://";

    final ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
    for (final Map.Entry<String, String> entry : queries.entrySet()) {
        parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    parameters.add(new BasicNameValuePair("clientAPI", clientApi));

    // scheme already has the name of the protocol
    // append the domain name of the server, url of the web service
    // and the query string to the string named url2
    url2 = scheme + hostname + "/" + url;
    if (debug) {
        System.out.println("url2 = " + url2);
    }
    CloseableHttpClient client = null;
    try {
        RequestConfig timeoutConfig = RequestConfig.custom().setConnectionRequestTimeout((int) timeout * 1000)
                .setSocketTimeout((int) timeout * 1000).build();

        HttpRoutePlanner proxyPlaner = null;
        if (useSystemProxies) {
            proxyPlaner = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
        }
        if (proxyHost != null && proxyPort > -1) {
            proxyPlaner = new DefaultProxyRoutePlanner(new HttpHost(proxyHost, proxyPort));
        }
        client = HttpClients.custom().setDefaultRequestConfig(timeoutConfig).setRoutePlanner(proxyPlaner)
                .build();

        // connect the server
        final HttpPost method = new HttpPost(url2);
        method.setEntity(new UrlEncodedFormEntity(parameters));

        final HttpResponse response = client.execute(method);

        final String content = EntityUtils.toString(response.getEntity());
        if (response.getStatusLine().getStatusCode() == 200) {

            if (debug) {
                System.out.println("content = " + content);
            }

            // get the keys and values from
            // the string content and store them
            // the hash named outputstr

            // split content into pairs containing both
            // the key and the value
            final StringTokenizer st = new StringTokenizer(content, ";");

            // for each pair store key and value into the
            // hash named outputstr
            while (st.hasMoreTokens()) {
                final String keyvaluepair = st.nextToken();

                // split the pair into a key and a value
                final StringTokenizer st2 = new StringTokenizer(keyvaluepair, "=");
                String key;
                String value;
                key = st2.nextToken();
                value = st2.hasMoreTokens() ? st2.nextToken() : "";
                // store the key and the value into the
                // hash named outputstr
                outputstr.put(key, value);
                if (debug) {
                    System.out.println("key = " + key + ", value = " + value);
                }
            }
            if (!outputstr.containsKey(check_field)) {
                // if the output does not have the field it is checking for
                // then return false
                return false;
            }
            method.releaseConnection();
            return true;
        }
        method.releaseConnection();
        return false;
    } catch (final java.io.IOException e) {
        if (e instanceof InterruptedIOException) {
            System.out.println("web service timeout");
        }
        System.out.println("error = " + e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            if (client != null) {
                client.close();
            }
        } catch (IOException e) {
            //ignore
        }
    }
    return false;
}