Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory.

Prototype

public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:groovyx.net.http.ApacheHttpBuilder.java

/**
 * Creates a new `HttpBuilder` based on the Apache HTTP client. While it is acceptable to create a builder with this method, it is generally
 * preferred to use one of the `static` `configure(...)` methods.
 *
 * @param config the configuration object
 *//* ww w .  j a  va2  s.  c  o  m*/
public ApacheHttpBuilder(final HttpObjectConfig config) {
    super(config);

    this.proxyInfo = config.getExecution().getProxyInfo();
    this.config = new HttpConfigs.ThreadSafeHttpConfig(config.getChainedConfig());
    this.executor = config.getExecution().getExecutor();
    this.clientConfig = config.getClient();

    final HttpClientBuilder myBuilder = HttpClients.custom();

    final Registry<ConnectionSocketFactory> registry = registry(config);

    if (config.getExecution().getMaxThreads() > 1) {
        final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        cm.setMaxTotal(config.getExecution().getMaxThreads());
        cm.setDefaultMaxPerRoute(config.getExecution().getMaxThreads());
        myBuilder.setConnectionManager(cm);
    } else {
        final BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(registry);
        myBuilder.setConnectionManager(cm);
    }

    final SSLContext sslContext = config.getExecution().getSslContext();
    if (sslContext != null) {
        myBuilder.setSSLContext(sslContext);
        myBuilder.setSSLSocketFactory(
                new SSLConnectionSocketFactory(sslContext, config.getExecution().getHostnameVerifier()));
    }

    myBuilder.addInterceptorFirst((HttpResponseInterceptor) (response, context) -> {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    final Consumer<Object> clientCustomizer = clientConfig.getClientCustomizer();
    if (clientCustomizer != null) {
        clientCustomizer.accept(myBuilder);
    }

    this.client = myBuilder.build();
}

From source file:org.commonjava.util.jhttpc.HttpFactory.java

private SSLConnectionSocketFactory createSSLSocketFactory(final SiteConfig location) throws JHttpCException {
    SSLConnectionSocketFactory fac = (SSLConnectionSocketFactory) location.getAttribute(SSL_FACTORY_ATTRIB);
    if (fac != null) {
        return fac;
    }//from w  w w.  j ava  2s.  c o  m

    KeyStore ks = null;
    KeyStore ts = null;

    final String kcPem = location.getKeyCertPem();

    final String kcPass = passwords.lookup(new PasswordKey(location, PasswordType.KEY));
    if (kcPem != null) {
        logger.debug("Adding client key/certificate from: {}", location);
        if (kcPass == null || kcPass.length() < 1) {
            logger.error("Invalid configuration. Location: {} cannot have an empty key password!",
                    location.getUri());
            throw new JHttpCException(
                    "Location: " + location.getUri() + " is misconfigured! Key password cannot be empty.");
        }

        try {
            logger.trace("Reading Client SSL key from:\n\n{}\n\n", kcPem);
            ks = SSLUtils.readKeyAndCert(kcPem, kcPass);

            logger.trace("Keystore contains the following certificates: {}", new CertEnumerator(ks, kcPass));
        } catch (final CertificateException e) {
            logger.error(String.format(
                    "Invalid configuration. Location: %s has an invalid client certificate! Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final KeyStoreException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final NoSuchAlgorithmException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final InvalidKeySpecException e) {
            logger.error(
                    String.format("Invalid configuration. Invalid client key for repository: %s. Error: %s",
                            location.getUri(), e.getMessage()),
                    e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (IOException e) {
            throw new JHttpCException("Failed to read client SSL key/certificate from: %s. Reason: %s", e,
                    location, e.getMessage());
        } catch (JHttpCException e) {
            throw new JHttpCException("Failed to read client SSL key/certificate from: %s. Reason: %s", e,
                    location, e.getMessage());
        }
    } else {
        logger.debug("No client key/certificate found");
    }

    final String sPem = location.getServerCertPem();

    //        logger.debug( "Server certificate PEM:\n{}", sPem );
    if (sPem != null) {
        logger.debug("Loading TrustStore (server SSL) information from: {}", location);
        try {
            logger.trace("Reading Server SSL cert from:\n\n{}\n\n", sPem);
            ts = SSLUtils.decodePEMTrustStore(sPem, location.getHost());

            logger.trace("Trust store contains the following certificates:\n{}", new CertEnumerator(ts, null));
        } catch (final CertificateException e) {
            logger.error(String.format(
                    "Invalid configuration. Location: %s has an invalid server certificate! Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final KeyStoreException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final NoSuchAlgorithmException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (IOException e) {
            throw new JHttpCException(
                    "Failed to read server SSL certificate(s) (or couldn't parse server hostname) from: %s. Reason: %s",
                    e, location, e.getMessage());
        }
    } else {
        logger.debug("No server certificates found");
    }

    if (ks != null || ts != null) {
        logger.debug("Setting up SSL context.");
        try {
            SSLContextBuilder sslBuilder = SSLContexts.custom().useProtocol(SSLConnectionSocketFactory.TLS);
            if (ks != null) {
                logger.trace("Loading key material for SSL context...");
                PrivateKeyStrategy pkStrategy = new MonolithicKeyStrategy();
                sslBuilder.loadKeyMaterial(ks, kcPass.toCharArray(), pkStrategy);
            }

            if (ts != null) {
                logger.trace("Loading trust material for SSL context...");

                SiteTrustType trustType = location.getTrustType();
                if (trustType == null) {
                    trustType = SiteTrustType.DEFAULT;
                }

                sslBuilder.loadTrustMaterial(ts, trustType.getTrustStrategy());
            }

            SSLContext ctx = sslBuilder.build();

            fac = new SSLConnectionSocketFactory(ctx, new DefaultHostnameVerifier());
            location.setAttribute(SSL_FACTORY_ATTRIB, fac);
            return fac;
        } catch (final KeyManagementException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final UnrecoverableKeyException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final NoSuchAlgorithmException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final KeyStoreException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        }
    } else {
        logger.debug("No SSL configuration present; no SSL context created.");
    }

    return null;
}

From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java

/**
 * Returns the HttpClient through which the REST call is made. Uses an
 * unsafe TrustStrategy in case the user specified a HTTPS URL and
 * set the ignoreUnverifiedSSLPeer flag.
 *
 * @param logger    the logger to log messages to
 * @param build/*w w w.ja  v  a2s.c  om*/
 * @return         the HttpClient
 */
private HttpClient getHttpClient(PrintStream logger, AbstractBuild<?, ?> build) throws Exception {
    boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
    String bitbucketServer = bitbucketServerBaseUrl;
    DescriptorImpl descriptor = getDescriptor();

    // Determine if we are using the local or global settings
    String credentialsId = getCredentialsId();
    if (StringUtils.isBlank(credentialsId)) {
        credentialsId = descriptor.getCredentialsId();
    }

    Credentials credentials = CredentialsMatchers.firstOrNull(CredentialsProvider
            .lookupCredentials(CertificateCredentials.class, Jenkins.getInstance(), ACL.SYSTEM),
            CredentialsMatchers.withId(credentialsId));

    if ("".equals(bitbucketServer) || bitbucketServer == null) {
        bitbucketServer = descriptor.getBitbucketRootUrl();
    }
    if (!ignoreUnverifiedSSL) {
        ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
    }

    URL url = new URL(bitbucketServer);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (url.getProtocol().equals("https")
            && (ignoreUnverifiedSSL || credentials instanceof CertificateCredentials)) {
        // add unsafe trust manager to avoid thrown
        // SSLPeerUnverifiedException
        try {
            SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(
                    buildSslContext(ignoreUnverifiedSSL, credentials),
                    ignoreUnverifiedSSL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : null);
            builder.setSSLSocketFactory(sslConnSocketFactory);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnSocketFactory).build();

            HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

            builder.setConnectionManager(ccm);
        } catch (NoSuchAlgorithmException nsae) {
            logger.println("Couldn't establish SSL context:");
            nsae.printStackTrace(logger);
        } catch (KeyManagementException kme) {
            logger.println("Couldn't initialize SSL context:");
            kme.printStackTrace(logger);
        } catch (KeyStoreException kse) {
            logger.println("Couldn't initialize SSL context:");
            kse.printStackTrace(logger);
        }
    }

    // Configure the proxy, if needed
    // Using the Jenkins methods handles the noProxyHost settings
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    if (proxyConfig != null) {
        Proxy proxy = proxyConfig.createProxy(url.getHost());
        if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
            SocketAddress addr = proxy.address();
            if (addr != null && addr instanceof InetSocketAddress) {
                InetSocketAddress proxyAddr = (InetSocketAddress) addr;
                HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
                builder = builder.setProxy(proxyHost);

                String proxyUser = proxyConfig.getUserName();
                if (proxyUser != null) {
                    String proxyPass = proxyConfig.getPassword();
                    BasicCredentialsProvider cred = new BasicCredentialsProvider();
                    cred.setCredentials(new AuthScope(proxyHost),
                            new UsernamePasswordCredentials(proxyUser, proxyPass));
                    builder = builder.setDefaultCredentialsProvider(cred)
                            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        }
    }

    return builder.build();
}

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

private HttpClientConnectionManager createConnectionManager() throws GeneralSecurityException, IOException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);//from ww w .  j  av a2 s  .c om

    if (registry == null) {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        X509TrustManager x509TrustManager = null;
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                x509TrustManager = (X509TrustManager) trustManager;
                break;
            }
        }

        X509Certificate[] acceptedIssuers = x509TrustManager.getAcceptedIssuers();
        if (acceptedIssuers != null) {
            // If this is null, something is really wrong...
            int issuerNum = 1;
            for (X509Certificate cert : acceptedIssuers) {
                trustStore.setCertificateEntry("issuer" + issuerNum, cert);
                issuerNum++;
            }
        } else {
            LOG.log(Level.INFO, "Didn't find any new certificates to trust.");
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

        sslContextBuilder.loadTrustMaterial(trustStore,
                new KnownArcGISCertificatesTrustStrategy(new ArrayList<>(trustedCerts)));
        SSLContext sslContext = sslContextBuilder.build();
        SSLContext.setDefault(sslContext);
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new DataStoreProxyHostnameVerifier(new ArrayList<>(trustedCerts)));

        this.registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();
    }
    return new PoolingHttpClientConnectionManager(registry);
}

From source file:fi.csc.shibboleth.mobileauth.impl.authn.AuthenticateMobile.java

/**
 * This method will create CloseableHttpClient with client certificate authentication
 * //w  ww . j  a  va 2s  .  co m
 * @return CloseableHttpClient
 * @throws KeyStoreException
 * @throws RuntimeException
 */
private CloseableHttpClient createHttpClient() throws KeyStoreException, RuntimeException {

    KeyStore trustStore = KeyStore.getInstance(trustStoreType);
    KeyStore clientStore = KeyStore.getInstance(keystoreType);

    try {
        trustStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());
        clientStore.load(new FileInputStream(keystorePath), keystorePasswd.toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new RuntimeException("Cannot load key/trust stores", e);
    }

    final SSLConnectionSocketFactory socketFactory;

    try {
        final SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadKeyMaterial(clientStore, keystorePasswd.toCharArray()).loadTrustMaterial(trustStore)
                .build();
        socketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        throw new RuntimeException("SSL initialization error", e);
    }
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", socketFactory).build();
    final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry);
    log.debug("Created httpClient");
    return HttpClients.custom().setConnectionManager(connectionManager).build();
}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SharePointRepository.java

/** Set up a session */
protected void getSession() throws ManifoldCFException {
    if (proxy == null) {
        String serverVersion = params.getParameter(SharePointConfig.PARAM_SERVERVERSION);
        if (serverVersion == null)
            serverVersion = "4.0";
        supportsItemSecurity = !serverVersion.equals("2.0");
        dspStsWorks = serverVersion.equals("2.0") || serverVersion.equals("3.0");
        attachmentsSupported = !serverVersion.equals("2.0");

        String authorityType = params.getParameter(SharePointConfig.PARAM_AUTHORITYTYPE);
        if (authorityType == null)
            authorityType = "ActiveDirectory";

        activeDirectoryAuthority = authorityType.equals("ActiveDirectory");

        serverProtocol = params.getParameter(SharePointConfig.PARAM_SERVERPROTOCOL);
        if (serverProtocol == null)
            serverProtocol = "http";
        try {/* w ww  .j  a  va  2s  .  c  o m*/
            String serverPort = params.getParameter(SharePointConfig.PARAM_SERVERPORT);
            if (serverPort == null || serverPort.length() == 0) {
                if (serverProtocol.equals("https"))
                    this.serverPort = 443;
                else
                    this.serverPort = 80;
            } else
                this.serverPort = Integer.parseInt(serverPort);
        } catch (NumberFormatException e) {
            throw new ManifoldCFException(e.getMessage(), e);
        }
        serverLocation = params.getParameter(SharePointConfig.PARAM_SERVERLOCATION);
        if (serverLocation == null)
            serverLocation = "";
        if (serverLocation.endsWith("/"))
            serverLocation = serverLocation.substring(0, serverLocation.length() - 1);
        if (serverLocation.length() > 0 && !serverLocation.startsWith("/"))
            serverLocation = "/" + serverLocation;
        encodedServerLocation = serverLocation;
        serverLocation = decodePath(serverLocation);

        userName = params.getParameter(SharePointConfig.PARAM_SERVERUSERNAME);
        password = params.getObfuscatedParameter(SharePointConfig.PARAM_SERVERPASSWORD);
        int index = userName.indexOf("\\");
        if (index != -1) {
            strippedUserName = userName.substring(index + 1);
            ntlmDomain = userName.substring(0, index);
        } else {
            strippedUserName = null;
            ntlmDomain = null;
        }

        String proxyHost = params.getParameter(SharePointConfig.PARAM_PROXYHOST);
        String proxyPortString = params.getParameter(SharePointConfig.PARAM_PROXYPORT);
        int proxyPort = 8080;
        if (proxyPortString != null && proxyPortString.length() > 0) {
            try {
                proxyPort = Integer.parseInt(proxyPortString);
            } catch (NumberFormatException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
        String proxyUsername = params.getParameter(SharePointConfig.PARAM_PROXYUSER);
        String proxyPassword = params.getParameter(SharePointConfig.PARAM_PROXYPASSWORD);
        String proxyDomain = params.getParameter(SharePointConfig.PARAM_PROXYDOMAIN);

        serverUrl = serverProtocol + "://" + serverName;
        if (serverProtocol.equals("https")) {
            if (serverPort != 443)
                serverUrl += ":" + Integer.toString(serverPort);
        } else {
            if (serverPort != 80)
                serverUrl += ":" + Integer.toString(serverPort);
        }

        fileBaseUrl = serverUrl + encodedServerLocation;

        // Set up ssl if indicated
        keystoreData = params.getParameter(SharePointConfig.PARAM_SERVERKEYSTORE);

        int connectionTimeout = 60000;
        int socketTimeout = 900000;

        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        SSLConnectionSocketFactory myFactory = null;
        if (keystoreData != null) {
            keystoreManager = KeystoreManagerFactory.make("", keystoreData);
            myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(),
                    new BrowserCompatHostnameVerifier());
        }

        if (strippedUserName != null) {
            credentialsProvider.setCredentials(new AuthScope(serverName, serverPort),
                    new NTCredentials(strippedUserName, password, currentHost, ntlmDomain));
        }

        RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        // If there's a proxy, set that too.
        if (proxyHost != null && proxyHost.length() > 0) {

            // Configure proxy authentication
            if (proxyUsername != null && proxyUsername.length() > 0) {
                if (proxyPassword == null)
                    proxyPassword = "";
                if (proxyDomain == null)
                    proxyDomain = "";

                credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
            }

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);

            requestBuilder.setProxy(proxy);
        }

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(credentialsProvider);
        if (myFactory != null)
            builder.setSSLSocketFactory(myFactory);
        builder.setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy());
        httpClient = builder.build();

        proxy = new SPSProxyHelper(serverUrl, encodedServerLocation, serverLocation, userName, password,
                org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd",
                httpClient);

    }
    sessionTimeout = System.currentTimeMillis() + sessionExpirationInterval;
}

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Create connection manager for http client.
 *
 * @return The connection manager for http client.
 *///from w  ww . j av  a2 s.  c om
private HttpClientConnectionManager createHttpClientConnectionManager() {
    ConnectionSocketFactory socketFactory = PlainConnectionSocketFactory.getSocketFactory();
    LayeredConnectionSocketFactory sslSocketFactory;
    try {
        sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
    } catch (NoSuchAlgorithmException e) {
        throw new BceClientException("Fail to create SSLConnectionSocketFactory", e);
    }
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(Protocol.HTTP.toString(), socketFactory)
            .register(Protocol.HTTPS.toString(), sslSocketFactory).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setDefaultMaxPerRoute(this.config.getMaxConnections());
    connectionManager.setDefaultSocketConfig(SocketConfig.custom()
            .setSoTimeout(this.config.getSocketTimeoutInMillis()).setTcpNoDelay(true).build());
    connectionManager.setMaxTotal(this.config.getMaxConnections());
    return connectionManager;
}

From source file:com.ibm.dataworks.DataLoadResource.java

/** 
 * Create an HTTP client object that is authenticated with the user and password
 * of the IBM DataWorks Service./* ww w. ja  v a 2 s.c o  m*/
 */
private HttpClient getAuthenticatedHttpClient() throws GeneralSecurityException {
    // NOTE: If you re-purpose this code for your own application you might want to have 
    // additional security mechanisms in place regarding certificate authentication.

    // build credentials object
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(vcapInfo.getUser(),
            vcapInfo.getPassword());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    // For demo purposes only: always accept the certificate 
    TrustStrategy accepAllTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };
    SSLContextBuilder contextBuilder = new SSLContextBuilder();
    SSLContext context = contextBuilder.loadTrustMaterial(null, accepAllTrustStrategy).build();
    SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(context, new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create() //
            .setSSLSocketFactory(scsf) //
            .setDefaultCredentialsProvider(credsProvider) //
            .build();

    return httpClient;
}

From source file:br.com.intercomex.ws.GnreResultadoLote.java

@WebMethod(operationName = "consultarSimplesHomoloacao")
public String consultarSimplesHomoloacao(@WebParam(name = "nrRecibo") String nrRecibo) {
    String url_HML = "https://www.gnre-h.pe.gov.br/gnreWS/services/GnreResultadoLote?wsdl";
    String action_HML = "http://www.gnre-h.pe.gov.br/gnreWS/services/GnreResultadoLote/consultar";
    String resultado = null;/*from   w  ww . j  av  a2  s.  co m*/
    TResultLoteGNRE retorno = null;
    loadConfig();
    try {
        //<TConsLote_GNRE xmlns="http://www.gnre.pe.gov.br"><ambiente>1</ambiente><numeroRecibo>2012314940</numeroRecibo></TConsLote_GNRE>
        String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreResultadoLote\">"
                + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>"
                + " <soap:Body><gnr:gnreDadosMsg><TConsLote_GNRE xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>2</ambiente><numeroRecibo>"
                + nrRecibo + "</numeroRecibo></TConsLote_GNRE></gnr:gnreDadosMsg></soap:Body></soap:Envelope>";

        System.out.println("PARAMETRO envio ==== " + XML_DATA);
        HttpPost httpPost = new HttpPost(url_HML);
        httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8"));
        httpPost.setHeader(new BasicHeader("SOAPAction", action_HML));
        StringEntity s = new StringEntity(XML_DATA, "UTF-8");
        httpPost.setEntity(s);
        FileInputStream instream = null;
        FileInputStream instreamTrust = null;
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        instream = new FileInputStream(new File(caminhoDoCertificadoDoCliente));
        keyStore.load(instream, senhaDoCertificadoDoCliente.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("JKS");
        instreamTrust = new FileInputStream(new File(arquivoCacertsGeradoParaCadaEstado));
        trustStore.load(instreamTrust, senhaDoCertificadoDoCliente.toCharArray());

        SSLContextBuilder builder = SSLContexts.custom().loadTrustMaterial(trustStore);
        builder.loadKeyMaterial(keyStore, senhaDoCertificadoDoCliente.toCharArray());
        SSLContext sslcontext = builder.build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclientSLL = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        System.out.println("executing request" + httpPost.getRequestLine());
        System.out.println("Conteudo envio ==== " + XML_DATA);
        HttpResponse response = httpclientSLL.execute(httpPost);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            String str = EntityUtils.toString(entity);
            System.out.println(str);
            XmlUtil util = new XmlUtil();
            retorno = util.getTResultLoteGNRE(str);
            resultado = retorno.getResultado();

        }
        if (entity != null) {
            entity.consumeContent();
        }
        httpclient.getConnectionManager().shutdown();

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (CertificateException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    }

    return resultado;
}

From source file:org.apache.metron.dataloads.taxii.TaxiiHandler.java

private static HttpClient buildClient(URL proxy, String username, String password) throws Exception {
    HttpClient client = new HttpClient(); // Start with a default TAXII HTTP client.

    // Create an Apache HttpClientBuilder to be customized by the command line arguments.
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();

    // Proxy/*from  www . j av  a 2s.c o  m*/
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol());
        builder.setProxy(proxyHost);
    }

    // Basic authentication. User & Password
    if (username != null ^ password != null) {
        throw new Exception("'username' and 'password' arguments are required to appear together.");
    }

    // from:  http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3
    SSLContextBuilder ssbldr = new SSLContextBuilder();
    ssbldr.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ssbldr.build(),
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(20);//max connection

    System.setProperty("jsse.enableSNIExtension", "false"); //""
    CloseableHttpClient httpClient = builder.setSSLSocketFactory(sslsf).setConnectionManager(cm).build();

    client.setHttpclient(httpClient);
    return client;
}