Example usage for org.apache.http.config RegistryBuilder build

List of usage examples for org.apache.http.config RegistryBuilder build

Introduction

In this page you can find the example usage for org.apache.http.config RegistryBuilder build.

Prototype

public Registry<I> build() 

Source Link

Usage

From source file:com.helger.pd.client.jdk6.PDClient.java

@Nonnull
protected HttpClientBuilder createClientBuilder() {
    SSLConnectionSocketFactory aSSLSocketFactory = null;
    try {/* ww  w .  j a  v  a2s . c o  m*/
        // Set SSL context
        final KeyStore aKeyStore = KeyStoreHelper.loadKeyStore(PDClientConfiguration.getKeyStorePath(),
                PDClientConfiguration.getKeyStorePassword());
        final SSLContext aSSLContext = SSLContexts.custom().loadKeyMaterial(aKeyStore,
                PDClientConfiguration.getKeyStoreKeyPassword(), new PrivateKeyStrategy() {
                    public String chooseAlias(final Map<String, PrivateKeyDetails> aAliases,
                            final Socket aSocket) {
                        final String sAlias = PDClientConfiguration.getKeyStoreKeyAlias();
                        return aAliases.containsKey(sAlias) ? sAlias : null;
                    }
                }).build();
        // Allow TLSv1 protocol only
        aSSLSocketFactory = new SSLConnectionSocketFactory(aSSLContext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    } catch (final Throwable t) {
        s_aLogger.error("Failed to initialize keystore for service connection! Can only use http now!", t);
    }

    try {
        final RegistryBuilder<ConnectionSocketFactory> aRB = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory());
        if (aSSLSocketFactory != null)
            aRB.register("https", aSSLSocketFactory);
        final Registry<ConnectionSocketFactory> sfr = aRB.build();

        final PoolingHttpClientConnectionManager aConnMgr = new PoolingHttpClientConnectionManager(sfr);
        aConnMgr.setDefaultMaxPerRoute(100);
        aConnMgr.setMaxTotal(200);
        aConnMgr.setValidateAfterInactivity(1000);
        final ConnectionConfig aConnectionConfig = ConnectionConfig.custom()
                .setMalformedInputAction(CodingErrorAction.IGNORE)
                .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).build();
        aConnMgr.setDefaultConnectionConfig(aConnectionConfig);

        return HttpClientBuilder.create().setConnectionManager(aConnMgr);
    } catch (final Exception ex) {
        throw new InitializationException("Failed to init HTTP client", ex);
    }
}

From source file:com.mirth.connect.plugins.httpauth.oauth2.OAuth2Authenticator.java

@Override
public AuthenticationResult authenticate(RequestInfo request) throws Exception {
    OAuth2HttpAuthProperties properties = getReplacedProperties(request);

    CloseableHttpClient client = null;/*w  w w  .jav a2 s. c  o  m*/
    CloseableHttpResponse response = null;

    try {
        // Create and configure the client and context 
        RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory());
        ConnectorPluginProperties pluginProperties = null;
        if (CollectionUtils.isNotEmpty(properties.getConnectorPluginProperties())) {
            pluginProperties = properties.getConnectorPluginProperties().iterator().next();
        }
        provider.getHttpConfiguration().configureSocketFactoryRegistry(pluginProperties, socketFactoryRegistry);
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(SOCKET_TIMEOUT).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        client = clientBuilder.build();

        HttpClientContext context = HttpClientContext.create();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(SOCKET_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        URIBuilder uriBuilder = new URIBuilder(properties.getVerificationURL());

        // Add query parameters
        if (properties.getTokenLocation() == TokenLocation.QUERY) {
            List<String> paramList = request.getQueryParameters().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(paramList)) {
                for (String value : paramList) {
                    uriBuilder.addParameter(properties.getLocationKey(), value);
                }
            }
        }

        // Build the final URI and create a GET request
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // Add headers
        if (properties.getTokenLocation() == TokenLocation.HEADER) {
            List<String> headerList = request.getHeaders().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(headerList)) {
                for (String value : headerList) {
                    httpGet.addHeader(properties.getLocationKey(), value);
                }
            }
        }

        // Execute the request
        response = client.execute(httpGet, context);

        // Determine authentication from the status code 
        if (response.getStatusLine().getStatusCode() < 400) {
            return AuthenticationResult.Success();
        } else {
            return AuthenticationResult.Failure();
        }
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:com.mirth.connect.client.core.ServerConnection.java

public ServerConnection(int timeout, String[] httpsProtocols, String[] httpsCipherSuites, boolean allowHTTP) {
    SSLContext sslContext = null;
    try {/*from   w  w w . j  a  v a  2s  .  c  om*/
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        logger.error("Unable to build SSL context.", e);
    }

    String[] enabledProtocols = MirthSSLUtil.getEnabledHttpsProtocols(httpsProtocols);
    String[] enabledCipherSuites = MirthSSLUtil.getEnabledHttpsCipherSuites(httpsCipherSuites);
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            enabledProtocols, enabledCipherSuites, NoopHostnameVerifier.INSTANCE);
    RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory);
    if (allowHTTP) {
        builder.register("http", PlainConnectionSocketFactory.getSocketFactory());
    }
    Registry<ConnectionSocketFactory> socketFactoryRegistry = builder.build();

    PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    httpClientConnectionManager.setDefaultMaxPerRoute(5);
    httpClientConnectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
    // MIRTH-3962: The stale connection settings has been deprecated, and this is recommended instead
    httpClientConnectionManager.setValidateAfterInactivity(5000);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(httpClientConnectionManager);
    HttpUtil.configureClientBuilder(clientBuilder);

    client = clientBuilder.build();
    requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
            .setConnectionRequestTimeout(CONNECT_TIMEOUT).setSocketTimeout(timeout).build();
}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

protected PoolingHttpClientConnectionManager newConnectionManager() {
    try {/*w  ww . ja  va  2 s  .  co  m*/
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());

        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE);
        if (this.sslHostnameValidationEnabled) {
            registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext));
        } else {
            registryBuilder.register("https",
                    new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE));
        }
        final Registry<ConnectionSocketFactory> registry = registryBuilder.build();

        this.connectionManager = new PoolingHttpClientConnectionManager(registry);
        this.connectionManager.setMaxTotal(this.hostProperties.getMaxTotalConnections());
        this.connectionManager.setDefaultMaxPerRoute(this.hostProperties.getMaxPerRouteConnections());
        return this.connectionManager;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:eu.fthevenet.binjr.data.adapters.HttpDataAdapterBase.java

protected CloseableHttpClient httpClientFactory() throws CannotInitializeDataAdapterException {
    try {/*ww  w. j  a  va 2  s  .  c o  m*/
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(createSslCustomContext(), null, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        RegistryBuilder<AuthSchemeProvider> schemeProviderBuilder = RegistryBuilder.create();
        schemeProviderBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
            @Override
            public Principal getUserPrincipal() {
                return null;
            }

            @Override
            public String getPassword() {
                return null;
            }
        });

        return HttpClients.custom().setDefaultAuthSchemeRegistry(schemeProviderBuilder.build())
                .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(csf).build();
    } catch (Exception e) {
        throw new CannotInitializeDataAdapterException(
                "Could not initialize adapter to source '" + this.getSourceName() + "': " + e.getMessage(), e);
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.ClientProxy.java

private HttpClientConnectionManager getClientConnectionManager() throws Exception {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.create();

    sfr.register("http", PlainConnectionSocketFactory.INSTANCE);

    if (SystemProperties.isSslEnabled()) {
        sfr.register("https", createSSLSocketFactory());
    }// w  w  w  .j  a  v a  2s . c  om

    SocketConfig.Builder sockBuilder = SocketConfig.custom().setTcpNoDelay(true);
    sockBuilder.setSoLinger(SystemProperties.getClientProxyHttpClientSoLinger());
    sockBuilder.setSoTimeout(SystemProperties.getClientProxyHttpClientTimeout());
    SocketConfig socketConfig = sockBuilder.build();

    PoolingHttpClientConnectionManager poolingManager = new PoolingHttpClientConnectionManager(sfr.build());
    poolingManager.setMaxTotal(SystemProperties.getClientProxyPoolTotalMaxConnections());
    poolingManager.setDefaultMaxPerRoute(SystemProperties.getClientProxyPoolDefaultMaxConnectionsPerRoute());
    poolingManager.setDefaultSocketConfig(socketConfig);
    poolingManager.setValidateAfterInactivity(
            SystemProperties.getClientProxyValidatePoolConnectionsAfterInactivityMs());

    return poolingManager;
}

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

private HttpClientConnectionManager _getHttpClientConnectionManager(boolean trustSelfSigned) {

    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connectionFactory = new SyncManagedHttpClientConnectionFactory();

    try {/* w  w  w.j  a  v  a  2 s .  c  o  m*/
        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();

        registryBuilder.register("http", new PlainConnectionSocketFactory());

        if (trustSelfSigned) {
            registryBuilder.register("https", _getTrustingSSLSocketFactory());
        } else {
            registryBuilder.register("https", _getDefaultSSLSocketFactory());
        }

        Registry<ConnectionSocketFactory> registry = registryBuilder.build();

        return new PoolingHttpClientConnectionManager(registry, connectionFactory);
    } catch (Exception e) {
        _logger.error(e.getMessage(), e);
    }

    return new PoolingHttpClientConnectionManager(connectionFactory);
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java

private HttpClientConnectionManager getConnectionManager() throws DSSException {

    LOG.debug("HTTPS TrustStore undefined, using default");
    RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder = RegistryBuilder.create();
    socketFactoryRegistryBuilder = setConnectionManagerSchemeHttp(socketFactoryRegistryBuilder);
    socketFactoryRegistryBuilder = setConnectionManagerSchemeHttps(socketFactoryRegistryBuilder);

    final HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistryBuilder.build());
    return connectionManager;
}

From source file:com.xebialabs.overthere.winrm.WinRmClient.java

private void configureHttpClient(final HttpClientBuilder httpclient) throws GeneralSecurityException {
    configureTrust(httpclient);/*from  w ww .j a  v a  2 s . c  om*/
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    httpclient.setDefaultCredentialsProvider(credentialsProvider);

    configureAuthentication(credentialsProvider, BASIC, new BasicUserPrincipal(username));

    if (enableKerberos) {
        String spnServiceClass = kerberosUseHttpSpn ? "HTTP" : "WSMAN";
        RegistryBuilder<AuthSchemeProvider> authSchemeRegistryBuilder = RegistryBuilder.create();
        authSchemeRegistryBuilder.register(KERBEROS, new WsmanKerberosSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        authSchemeRegistryBuilder.register(SPNEGO, new WsmanSPNegoSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        httpclient.setDefaultAuthSchemeRegistry(authSchemeRegistryBuilder.build());
        configureAuthentication(credentialsProvider, KERBEROS, new KerberosPrincipal(username));
        configureAuthentication(credentialsProvider, SPNEGO, new KerberosPrincipal(username));
    }

    httpclient.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build());
    httpclient.setDefaultRequestConfig(
            RequestConfig.custom().setAuthenticationEnabled(true).setConnectTimeout(connectionTimeout).build());
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

/**
 * Returns the URL for the passed in String. If the URL requires authentication, then the WSDL
 * is saved as a temp file and the URL for that file is returned.
 * /*from   w  w  w .  j av  a 2s. co m*/
 * @param wsdlUrl
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private URL getWsdlUrl(DispatchContainer dispatchContainer) throws Exception {
    URI uri = new URI(dispatchContainer.getCurrentWsdlUrl());

    // If the URL points to file, just return it
    if (!uri.getScheme().equalsIgnoreCase("file")) {
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        CloseableHttpClient client = clientBuilder.build();

        try {
            clients.add(client);
            HttpClientContext context = HttpClientContext.create();

            if (dispatchContainer.getCurrentUsername() != null
                    && dispatchContainer.getCurrentPassword() != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,
                        AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(
                        dispatchContainer.getCurrentUsername(), dispatchContainer.getCurrentPassword());
                credsProvider.setCredentials(authScope, credentials);
                AuthCache authCache = new BasicAuthCache();
                RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder
                        .<AuthSchemeProvider>create();
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());

                context.setCredentialsProvider(credsProvider);
                context.setAuthSchemeRegistry(registryBuilder.build());
                context.setAuthCache(authCache);
            }

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setSocketTimeout(timeout).setStaleConnectionCheckEnabled(true).build();
            context.setRequestConfig(requestConfig);

            return getWsdl(client, context, dispatchContainer, new HashMap<String, File>(),
                    dispatchContainer.getCurrentWsdlUrl()).toURI().toURL();
        } finally {
            HttpClientUtils.closeQuietly(client);
            clients.remove(client);
        }
    }

    return uri.toURL();
}