Example usage for javax.net.ssl HttpsURLConnection setSSLSocketFactory

List of usage examples for javax.net.ssl HttpsURLConnection setSSLSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setSSLSocketFactory.

Prototype

public void setSSLSocketFactory(SSLSocketFactory sf) 

Source Link

Document

Sets the <code>SSLSocketFactory</code> to be used when this instance creates sockets for secure https URL connections.

Usage

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsWithCertificate(final URL url) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);// Make an empty store

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    FileInputStream fis = new FileInputStream(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH);
    BufferedInputStream bis = new BufferedInputStream(fis);
    while (bis.available() > 0) {
        Certificate cert = cf.generateCertificate(bis);
        // System.out.println(cert.getPublicKey().toString());
        trustStore.setCertificateEntry("jetty" + bis.available(), cert);
    }/*from   ww w.j a v  a 2  s  . c om*/

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory sslFactory = ctx.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if (0 == hostname.compareToIgnoreCase(url.getHost())) {
                return true;
            }
            return false;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslFactory);

    return urlConnection.getInputStream();
}

From source file:com.dell.asm.asmcore.asmmanager.util.discovery.DeviceTypeCheckUtil.java

/**
 * HTTP request extractor/*from w  ww.  j av  a  2s . c o m*/
 *
 * @param urlToRead device URL
 * @return device type string
 * @throws IOException
 */
public static String getHTML(String urlToRead) throws IOException {
    URL url;
    HttpURLConnection conn;
    BufferedReader rd = null;
    String line;
    StringBuffer result = new StringBuffer();

    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            HttpsURLConnection sslConn = (HttpsURLConnection) conn;
            sslConn.setHostnameVerifier(hv);
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { tmNoCheck }, new SecureRandom());
            sslConn.setSSLSocketFactory(sslContext.getSocketFactory());
        }

        conn.setRequestMethod("GET");
        conn.setConnectTimeout(AsmManagerApp.CONNECT_TIMEOUT); // timeout value
        conn.setReadTimeout(AsmManagerApp.CONNECT_TIMEOUT);
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (RuntimeException e) {
        throw new IOException("Could not connect to the url: " + e.getMessage());
    } catch (Exception e) {
        throw new IOException("Could not connect to the url: " + urlToRead);
    } finally {
        if (rd != null)
            rd.close();
    }
    return result.toString();
}

From source file:dk.itst.oiosaml.sp.service.util.HttpSOAPClient.java

public Envelope wsCall(String location, String username, String password, boolean ignoreCertPath, String xml,
        String soapAction) throws IOException, SOAPException {
    URI serviceLocation;//from   w w  w . java  2 s .c  o m
    try {
        serviceLocation = new URI(location);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid uri for artifact resolve: " + location);
    }
    if (log.isDebugEnabled())
        log.debug("serviceLocation..:" + serviceLocation);
    if (log.isDebugEnabled())
        log.debug("SOAP Request: " + xml);

    HttpURLConnection c = (HttpURLConnection) serviceLocation.toURL().openConnection();
    if (c instanceof HttpsURLConnection) {
        HttpsURLConnection sc = (HttpsURLConnection) c;

        if (ignoreCertPath) {
            sc.setSSLSocketFactory(new DummySSLSocketFactory());
            sc.setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
    }
    c.setAllowUserInteraction(false);
    c.setDoInput(true);
    c.setDoOutput(true);
    c.setFixedLengthStreamingMode(xml.getBytes("UTF-8").length);
    c.setRequestMethod("POST");
    c.setReadTimeout(20000);
    c.setConnectTimeout(30000);

    addContentTypeHeader(xml, c);
    c.addRequestProperty("SOAPAction", "\"" + (soapAction == null ? "" : soapAction) + "\"");

    if (username != null && password != null) {
        c.addRequestProperty("Authorization",
                "Basic " + Base64.encodeBytes((username + ":" + password).getBytes(), Base64.DONT_BREAK_LINES));
    }
    OutputStream outputStream = c.getOutputStream();
    IOUtils.write(xml, outputStream, "UTF-8");
    outputStream.flush();
    outputStream.close();

    if (c.getResponseCode() == 200) {
        InputStream inputStream = c.getInputStream();
        String result = IOUtils.toString(inputStream, "UTF-8");
        inputStream.close();

        if (log.isDebugEnabled())
            log.debug("Server SOAP response: " + result);
        XMLObject res = SAMLUtil.unmarshallElementFromString(result);

        Envelope envelope = (Envelope) res;
        if (SAMLUtil.getFirstElement(envelope.getBody(), Fault.class) != null) {
            log.warn(
                    "Result has soap11:Fault, but server returned 200 OK. Treating as error, please fix the server");
            throw new SOAPException(c.getResponseCode(), result);
        }
        return envelope;
    } else {
        log.debug("Response code: " + c.getResponseCode());

        InputStream inputStream = c.getErrorStream();
        String result = IOUtils.toString(inputStream, "UTF-8");
        inputStream.close();
        if (log.isDebugEnabled())
            log.debug("Server SOAP fault: " + result);

        throw new SOAPException(c.getResponseCode(), result);
    }
}

From source file:com.dell.asm.asmcore.asmmanager.util.discovery.DeviceTypeCheckUtil.java

/**
 * HTTP POST with basic auth//w  w  w  .  ja  v  a2 s  . com
 *
 * @param urlToRead device URL
 * @return http response message
 * @throws IOException
 */
public static String httpPost(String urlToRead, String username, String password) throws IOException {
    URL url;
    HttpURLConnection conn;
    BufferedReader rd = null;
    String line;
    StringBuffer result = new StringBuffer();

    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            HttpsURLConnection sslConn = (HttpsURLConnection) conn;
            sslConn.setHostnameVerifier(hv);
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { tmNoCheck }, new SecureRandom());
            sslConn.setSSLSocketFactory(sslContext.getSocketFactory());
        }
        conn.setDoOutput(true);
        conn.setConnectTimeout(AsmManagerApp.CONNECT_TIMEOUT); // timeout value
        conn.setReadTimeout(AsmManagerApp.CONNECT_TIMEOUT);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("x-dell-api-version", "2.0");
        conn.setRequestProperty("Authorization", encodeCredentials(username, password));
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setFixedLengthStreamingMode("{}".length());
        conn.getOutputStream().write("{}".getBytes(Charset.forName("UTF-8")));

        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (RuntimeException e) {
        throw new IOException("Could not connect to the url: " + e.getMessage());
    } catch (Exception e) {
        throw new IOException("Could not connect to the url: " + urlToRead);
    } finally {
        if (rd != null)
            rd.close();
    }
    return result.toString();
}

From source file:com.persistent.cloudninja.scheduler.DeploymentMonitor.java

/**
 * Gets the information regarding the roles and their instances
 * of the deployment. It makes a call to REST API and gets the XML response. 
 * // w ww.ja  va2 s  . com
 * @return XML response
 * @throws IOException
 */
public StringBuffer getRoleInfoForDeployment() throws IOException {
    StringBuffer response = new StringBuffer();
    System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");

    StringBuffer keyStore = new StringBuffer();
    keyStore.append(System.getProperty("java.home"));
    LOGGER.debug("java.home : " + keyStore.toString());
    if (keyStore.length() == 0) {
        keyStore.append(System.getenv("JRE_HOME"));
        LOGGER.debug("JRE_HOME : " + keyStore.toString());
    }
    keyStore.append(File.separator + "lib\\security\\CloudNinja.pfx");
    System.setProperty("javax.net.ssl.keyStore", keyStore.toString());
    System.setProperty("javax.net.debug", "ssl");
    System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);
    System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);

    SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    // form the URL which will return the response
    // containing info of roles and their instances.
    StringBuffer strURL = new StringBuffer(host);
    strURL.append(subscriptionId);
    strURL.append("/services/hostedservices/");
    strURL.append(hostedServiceName);
    strURL.append("/deploymentslots/");
    strURL.append(deploymentType);

    URL url = new URL(strURL.toString());

    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setSSLSocketFactory(sslSocketFactory);
    connection.setRequestMethod("GET");
    connection.setAllowUserInteraction(false);
    // set the x-ms-version in header which is a compulsory parameter to get response 
    connection.setRequestProperty("x-ms-version", "2011-10-01");
    connection.setRequestProperty("Content-type", "text/xml");
    connection.setRequestProperty("accept", "text/xml");
    // get the response as input stream
    InputStream inputStream = connection.getInputStream();
    InputStreamReader streamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(streamReader);
    String string = null;
    while ((string = bufferedReader.readLine()) != null) {
        response.append(string);
    }
    return response;
}

From source file:org.talend.librariesmanager.utils.nexus.NexusDownloader.java

private HttpURLConnection getHttpURLConnection(String nexusUrl, String repositoryId, String relativePath,
        String userName, String password) throws Exception {
    String path = nexusUrl;/*from  w ww  .  j  ava  2s.  com*/
    if (path.endsWith(NexusConstants.SLASH)) {
        path = path.substring(0, path.length() - 1);
    }
    path = path + NexusConstants.CONTENT_REPOSITORIES;
    path = path + repositoryId + NexusConstants.SLASH;
    URL url = new URL(path + relativePath);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    if (userName != null && !"".equals(userName)) {
        urlConnection.setRequestProperty("Authorization", //$NON-NLS-1$
                "Basic " + Base64.encodeBase64((userName + ":" + password).getBytes()));//$NON-NLS-1$
    }
    if (urlConnection instanceof HttpsURLConnection) {
        String userDir = Platform.getInstallLocation().getURL().getPath();
        final SSLSocketFactory socketFactory = SSLUtils.getSSLContext(userDir).getSocketFactory();
        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
        httpsConnection.setSSLSocketFactory(socketFactory);
        httpsConnection.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }

        });
    }
    urlConnection.setConnectTimeout(10000);
    urlConnection.setReadTimeout(10000);
    return urlConnection;
}

From source file:edu.mayo.xsltserver.controller.XsltServerController.java

protected InputStream createInputStreamFromUrl(URL url) throws IOException {
    final URLConnection urlCon = url.openConnection();

    if (urlCon instanceof HttpsURLConnection) {
        HttpsURLConnection connection = (HttpsURLConnection) urlCon;
        connection.setHostnameVerifier(VERIFY_ALL_HOST_NAMES);
        connection.setSSLSocketFactory(sslSocketFactory);
    }//from  ww w . j  av a 2s  .  c om

    return urlCon.getInputStream();
}

From source file:org.apache.hadoop.http.TestSSLHttpServer.java

/**
 * Test that verifies headers can be up to 64K long. The test adds a 63K
 * header leaving 1K for other headers. This is because the header buffer
 * setting is for ALL headers, names and values included.
 *//* w w w . j  ava2s  .co m*/
@Test
public void testLongHeader() throws Exception {
    URL url = new URL(baseUrl, "/longheader");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setSSLSocketFactory(clientSslFactory.createSSLSocketFactory());
    testLongHeader(conn);
}

From source file:org.apache.synapse.config.SynapseConfigUtils.java

/**
 * Helper method to create a HttpSURLConnection with provided KeyStores
 *
 * @param url Https URL/*from w w  w .j av a 2  s  .co  m*/
 * @param synapseProperties properties for extracting info
 * @param proxy if there is a proxy
 * @return gives out the connection created
 */
private static HttpsURLConnection getHttpsURLConnection(URL url, Properties synapseProperties, Proxy proxy) {

    if (log.isDebugEnabled()) {
        log.debug("Creating a HttpsURL Connection from given URL : " + url);
    }

    KeyManager[] keyManagers = null;
    TrustManager[] trustManagers = null;

    IdentityKeyStoreInformation identityInformation = KeyStoreInformationFactory
            .createIdentityKeyStoreInformation(synapseProperties);

    if (identityInformation != null) {
        KeyManagerFactory keyManagerFactory = identityInformation.getIdentityKeyManagerFactoryInstance();
        if (keyManagerFactory != null) {
            keyManagers = keyManagerFactory.getKeyManagers();
        }

    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no private key entry store configuration." + " Will use JDK's default one");
        }
    }

    TrustKeyStoreInformation trustInformation = KeyStoreInformationFactory
            .createTrustKeyStoreInformation(synapseProperties);

    if (trustInformation != null) {
        TrustManagerFactory trustManagerFactory = trustInformation.getTrustManagerFactoryInstance();
        if (trustManagerFactory != null) {
            trustManagers = trustManagerFactory.getTrustManagers();
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no trusted certificate store configuration." + " Will use JDK's default one");
        }
    }

    try {
        HttpsURLConnection connection;
        if (proxy != null) {
            connection = (HttpsURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpsURLConnection) url.openConnection();
        }
        //Create a SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);
        connection.setSSLSocketFactory(sslContext.getSocketFactory());

        if (trustInformation != null) {
            // Determine is it need to overwrite default Host Name verifier
            boolean enableHostnameVerifier = true;
            String value = trustInformation.getParameter(KeyStoreInformation.ENABLE_HOST_NAME_VERIFIER);
            if (value != null) {
                enableHostnameVerifier = Boolean.parseBoolean(value);
            }

            if (!enableHostnameVerifier) {

                if (log.isDebugEnabled()) {
                    log.debug("Overriding default HostName Verifier." + "HostName verification disabled");
                }

                connection.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
                    public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
                        if (log.isTraceEnabled()) {
                            log.trace("HostName verification disabled");
                            log.trace("Host:   " + hostname);
                            log.trace("Peer Host:  " + session.getPeerHost());
                        }
                        return true;
                    }
                });
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Using default HostName verifier...");
                }
            }
        }
        return connection;

    } catch (NoSuchAlgorithmException e) {
        handleException("Error loading SSLContext ", e);
    } catch (KeyManagementException e) {
        handleException("Error initiation SSLContext with KeyManagers", e);
    } catch (IOException e) {
        handleException("Error opening a https connection from URL : " + url, e);
    }
    return null;
}

From source file:org.apache.ambari.server.controller.internal.URLStreamProvider.java

protected HttpsURLConnection getSSLConnection(String spec) throws IOException {

    if (sslSocketFactory == null) {
        synchronized (this) {
            if (sslSocketFactory == null) {
                try {
                    FileInputStream in = new FileInputStream(new File(path));
                    KeyStore store = KeyStore.getInstance(type == null ? KeyStore.getDefaultType() : type);

                    store.load(in, password.toCharArray());
                    in.close();//from  www .jav a 2 s. c om

                    TrustManagerFactory tmf = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

                    tmf.init(store);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(null, tmf.getTrustManagers(), null);

                    sslSocketFactory = context.getSocketFactory();
                } catch (Exception e) {
                    throw new IOException("Can't get connection.", e);
                }
            }
        }
    }
    HttpsURLConnection connection = (HttpsURLConnection) (new URL(spec).openConnection());

    connection.setSSLSocketFactory(sslSocketFactory);

    return connection;
}