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 String[] supportedProtocols, final String[] supportedCipherSuites,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:org.ulyssis.ipp.publisher.HttpOutput.java

@Override
public void outputScore(Score score) {
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(createSslCustomContext(),
            new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    try (CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build()) {
        HttpPost req = new HttpPost(options.getHttp().toURI());
        byte[] scoreBytes = Serialization.getJsonMapper().writeValueAsBytes(score);
        HttpEntity ent = new ByteArrayEntity(scoreBytes, ContentType.APPLICATION_JSON);
        req.setEntity(ent);/* ww  w.j  av  a2  s.  c o m*/
        try (CloseableHttpResponse response = httpClient.execute(req)) {
            if (response.getStatusLine().getStatusCode() != 200) {
                LOG.error("Non-success result!");
                return;
            }
            HttpEntity entity = response.getEntity();
            if (entity.getContentLength() != 7L) {
                LOG.error("Non-success result!");
                return;
            }
            String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            if (!"SUCCESS".equals(result)) {
                LOG.error("Non-success result!");
                return;
            }
        }
    } catch (Exception e) {
        // TODO: DO SOMETHING WITH THE EXCEPTION!
        LOG.error("Exception", e);
    }
}

From source file:com.vmware.bdd.cli.http.HttpClientProvider.java

@Bean(name = SECURE_HTTP_CLIENT)
@Qualifier(SECURE_HTTP_CLIENT)//from  w w w .j  a  va 2  s  .co m
public HttpClient secureHttpClient()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContext sslContext = SSLContexts.custom().useTLS().build();

    sslContext.init(null, new TrustManager[] { trustManager }, null);

    String[] supportedProtocols = cliProperties.getSupportedProtocols();
    String[] supportedCipherSuites = cliProperties.getSupportedCipherSuites();
    String hostnameVerifier = cliProperties.getHostnameVerifier();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("supported protocols: " + ArrayUtils.toString(supportedProtocols));
        LOGGER.debug("supported cipher suites: " + ArrayUtils.toString(supportedCipherSuites));
        LOGGER.debug("hostname verifier: " + hostnameVerifier);
    }

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols,
            supportedCipherSuites, getHostnameVerifier(hostnameVerifier));

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", socketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    cm.setMaxTotal(20);
    cm.setDefaultMaxPerRoute(10);
    //      HttpHost proxy = new HttpHost("127.0.0.1", 8810, "http");
    //      HttpClient  client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).setProxy(proxy).build();

    HttpClient client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    return client1;
}

From source file:com.enioka.jqm.tools.JettyTest.java

@Test
public void testSslServices() throws Exception {
    Helpers.setSingleParam("enableWsApiSsl", "true", em);
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "false", em);

    addAndStartEngine();/*  w  ww . java 2  s .c o  m*/

    // Launch a job so as to be able to query its status later
    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar",
            TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true,
            em);
    JobRequest j = new JobRequest("MarsuApplication", "TestUser");
    int i = JqmClientFactory.getClient().enqueue(j);
    TestHelpers.waitFor(1, 10000, em);

    // HTTPS client - with
    KeyStore trustStore = KeyStore.getInstance("JKS");
    FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks"));
    try {
        trustStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class)
            .setParameter("i", TestHelpers.node.getId()).getSingleResult();
    HttpUriRequest rq = new HttpGet(
            "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i);
    jqmlogger.debug(rq.getURI());
    CloseableHttpResponse rs = cl.execute(rq);
    Assert.assertEquals(200, rs.getStatusLine().getStatusCode());

    rs.close();
    cl.close();
}

From source file:org.owasp.benchmark.tools.BenchmarkCrawler.java

public static SSLConnectionSocketFactory getSSLFactory() throws Exception {

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, NoopHostnameVerifier.INSTANCE);

    return sslsf;
}

From source file:org.createnet.raptor.auth.AuthHttpClient.java

private CloseableHttpClient getHttpClient() throws KeyStoreException, NoSuchAlgorithmException,
        KeyManagementException, UnrecoverableKeyException, CertificateException, IOException {

    if (httpclient == null) {

        logger.debug("Created http client instance");

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new File(config.token.truststore.path),
                config.token.truststore.password.toCharArray(), new TrustSelfSignedStrategy()).build();

        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                new String[] { "TLSv1.2", "TLSv1.1", "TLSv1" }, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());

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

        HttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);/*ww  w. j a v  a2  s.  co  m*/

        httpclient = HttpClients.custom()
                //              .setSSLSocketFactory(sslsf)
                .setConnectionManager(poolingConnManager)
                //              .setConnectionManagerShared(true)
                .build();
    }

    return httpclient;
}

From source file:net.ymate.framework.commons.HttpClientHelper.java

public static SSLConnectionSocketFactory createConnectionSocketFactory(String certType, URL certFilePath,
        char[] passwordChars) throws KeyStoreException, IOException, CertificateException,
        NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    if (StringUtils.isBlank(certType)) {
        throw new NullArgumentException("certType");
    }/*from  www. j a va  2 s .  c o m*/
    if (certFilePath == null) {
        throw new NullArgumentException("certFilePath");
    }
    if (ArrayUtils.isEmpty(passwordChars)) {
        throw new NullArgumentException("passwordChars");
    }
    KeyStore _keyStore = KeyStore.getInstance(certType);
    InputStream _certFileStream = null;
    try {
        _certFileStream = certFilePath.openStream();
        _keyStore.load(_certFileStream, passwordChars);
    } finally {
        IOUtils.closeQuietly(_certFileStream);
    }
    SSLContext _sslContext = SSLContexts.custom().loadKeyMaterial(_keyStore, passwordChars).build();
    return new SSLConnectionSocketFactory(_sslContext, new String[] { "TLSv1" }, null,
            new DefaultHostnameVerifier());
}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            // System.out.println("getAcceptedIssuers =============");
            return null;
        }/*from  w  w  w  . ja v  a2  s.  c o  m*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkClientTrusted =============");
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkServerTrusted =============");
        }
    } }, new SecureRandom());

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String arg0) {
                    // TODO Auto-generated method stub
                    return super.isRedirectable(arg0);
                }

                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    // TODO Auto-generated method stub
                    return super.isRedirected(request, response, context);
                }
            }).setDefaultCookieStore(new BasicCookieStore())
            .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0")
            .build();

    Executor exec = Executor.newInstance(httpclient);

    URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html");

    String fullURL = ub.build().toASCIIString();
    Request req = HttpUtils.get(fullURL, sp);
    HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    String tgtID = readData(exec, req, monitor);
    String action = getFormAction(tgtID);
    if (action != null) {
        action = action.replaceFirst("/", "");
        int indx = action.indexOf(";jsession");
        if (indx >= 0)
            action = action.substring(0, indx);
    } else
        action = "cas/login";
    String url = srv.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub = new URIBuilder(url + action);
    //
    fullURL = ub.build().toASCIIString();
    req = HttpUtils.get(fullURL, sp);
    proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    tgtID = readData(exec, req, monitor);
    action = getFormAction(tgtID);
    action = action.replaceFirst("/", "");

    ub = new URIBuilder(url + action);
    Map<String, String> map = getInputs(tgtID);
    Form form = Form.form();
    for (String key : map.keySet()) {
        if (key.equals("btn-reset"))
            continue;
        else if (key.equals("username")) {
            form.add(key, srv.getUser());
            continue;
        } else if (key.equals("password")) {
            form.add(key, Pass.getPass(srv.getPassword()));
            continue;
        }
        form.add(key, map.get(key));
    }
    //
    req = HttpUtils.post(ub.build().toASCIIString(), form, sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // Header header = null;
    readData(exec, req, monitor);
    // for (Header h : headers) {
    // for (HeaderElement he : h.getElements()) {
    // if (he.getName().equals("CASTGC")) {
    // header = new BasicHeader("Cookie", h.getValue());
    // break;
    // }
    // }
    // }
    ub = new URIBuilder(url + action);
    url = sp.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub.addParameter("service", url + "j_spring_security_check");

    req = HttpUtils.get(ub.build().toASCIIString(), sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // req.addHeader("Accept",
    // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value");
    req.addHeader("Referrer", sp.getUrl());
    // req.addHeader(header);
    String html = readData(exec, req, monitor);
    Matcher matcher = ahrefPattern.matcher(html);
    while (matcher.find()) {
        Map<String, String> attributes = parseAttributes(matcher.group(1));
        String v = attributes.get("href");
        int ind = v.indexOf("ticket=");
        if (ind > 0) {
            return v.substring(ind + "ticket=".length());
        }
    }
    return null;
}

From source file:projekat.rest_client.RestTemplateFactory.java

@Override
public void afterPropertiesSet() {

    fillTypesForRestService();//from w  ww.j  av a2s  . c o  m
    //za potrebe testirnja
    if (rest_keystore == null || "".equals(rest_keystore)) {
        rest_keystore = "/etc/keystores/nst2.jks";
        rest_keystore_password = "changeit";
        res_host_port = "8443";
        rest_hostname = "localhost";
    }
    InputStream keyStoreInputStream = null;
    try {
        keyStoreInputStream = new FileInputStream(rest_keystore);
        if (keyStoreInputStream == null) {
            throw new FileNotFoundException("");
        }
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            trustStore.load(keyStoreInputStream, rest_keystore_password.toCharArray());
        } finally {
            keyStoreInputStream.close();
        }
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        auth = new HttpComponentsClientHttpRequestFactoryBasicAuth(
                new HttpHost(rest_hostname, Integer.parseInt(res_host_port), "https"), httpClient);
        auth.setConnectTimeout(60000);
        auth.setReadTimeout(180000);
        restTemplate = new RestTemplate(auth);
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
            | KeyManagementException ex) {
        Logger.getLogger(RestTemplateFactory.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            keyStoreInputStream.close();
        } catch (Exception ex) {
            Logger.getLogger(RestTemplateFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:me.vertretungsplan.parser.BaseParser.java

BaseParser(SubstitutionScheduleData scheduleData, CookieProvider cookieProvider) {
    this.scheduleData = scheduleData;
    this.cookieProvider = cookieProvider;
    this.cookieStore = new BasicCookieStore();
    this.colorProvider = new ColorProvider(scheduleData);
    this.encodingDetector = new UniversalDetector(null);

    try {//from   w w w  .j a  v a  2  s . c  o m
        KeyStore ks = loadKeyStore();
        MultiTrustManager multiTrustManager = new MultiTrustManager();
        multiTrustManager.addTrustManager(getDefaultTrustManager());
        multiTrustManager.addTrustManager(trustManagerFromKeystore(ks));

        TrustManager[] trustManagers = new TrustManager[] { multiTrustManager };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
        final HostnameVerifier hostnameVerifier;

        if (scheduleData.getData() != null && scheduleData.getData().has(PARAM_SSL_HOSTNAME)) {
            hostnameVerifier = new CustomHostnameVerifier(scheduleData.getData().getString(PARAM_SSL_HOSTNAME));
        } else {
            hostnameVerifier = new DefaultHostnameVerifier();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" }, null, hostnameVerifier);

        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
                .build();
        this.executor = Executor.newInstance(httpclient).use(cookieStore);
    } catch (GeneralSecurityException | JSONException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.phenotips.data.internal.MonarchPatientScorer.java

@Override
public void initialize() throws InitializationException {
    try {//  ww  w .j  a  v  a 2  s . c o m
        this.scorerURL = this.configuration.getProperty("phenotips.patientScoring.monarch.serviceURL",
                "https://monarchinitiative.org/score");
        CacheConfiguration config = new LRUCacheConfiguration("monarchSpecificityScore", 2048, 3600);
        this.cache = this.cacheManager.createNewCache(config);
    } catch (CacheException ex) {
        throw new InitializationException("Failed to create cache", ex);
    }
    try {
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustAllStrategy()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, null, null,
                NoopHostnameVerifier.INSTANCE);
        this.client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) {
        this.logger.warn("Failed to set custom certificate trust, using the default", ex);
        this.client = HttpClients.createSystem();
    }
}