Example usage for javax.net.ssl SSLContext getSocketFactory

List of usage examples for javax.net.ssl SSLContext getSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getSocketFactory.

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:org.globusonline.nexus.BaseNexusRestClient.java

/**
 * @param path/*  w  ww. ja  va  2s.  c  om*/
 * @return JSON Response from action
 * @throws NexusClientException
 */
protected JSONObject issueRestRequest(String path, String httpMethod, String contentType, String accept,
        JSONObject params, NexusAuthenticator auth) throws NexusClientException {

    JSONObject json = null;

    HttpsURLConnection connection;

    if (httpMethod.isEmpty()) {
        httpMethod = "GET";
    }
    if (contentType.isEmpty()) {
        contentType = "application/json";
    }
    if (accept.isEmpty()) {
        accept = "application/json";
    }
    int responseCode;

    try {

        URL url = new URL(getNexusApiUrl() + path);

        connection = (HttpsURLConnection) url.openConnection();

        if (ignoreCertErrors) {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            connection.setSSLSocketFactory(sc.getSocketFactory());
            connection.setHostnameVerifier(allHostsValid);
        }

        if (auth != null) {
            auth.authenticate(connection);
        }

        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod(httpMethod);
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Accept", accept);
        connection.setRequestProperty("X-Go-Community-Context", community);

        String body = "";

        if (params != null) {
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            body = params.toString();
            out.write(body);
            logger.debug("Body:" + body);
            out.close();
        }

        responseCode = connection.getResponseCode();

    } catch (Exception e) {
        logger.error("Unhandled connection error:", e);
        throw new ValueErrorException();
    }

    logger.info("ConnectionURL: " + connection.getURL());

    if (responseCode == 403 || responseCode == 400) {
        logger.error("Access is denied.  Invalid credentials.");
        throw new InvalidCredentialsException();
    }
    if (responseCode == 404) {
        logger.error("URL not found.");
        throw new InvalidUrlException();
    }
    if (responseCode == 500) {
        logger.error("Internal Server Error.");
        throw new ValueErrorException();
    }
    if (responseCode != 200) {
        logger.info("Response code is: " + responseCode);
    }

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String decodedString = in.readLine();

        json = new JSONObject(decodedString);
    } catch (JSONException e) {
        logger.error("JSON Error", e);
        throw new ValueErrorException();
    } catch (IOException e) {
        logger.error("IO Error", e);
        throw new ValueErrorException();
    }

    return json;
}

From source file:org.binding.openhab.samsungac.communicator.AirConditioner.java

private void connect() throws Exception {
    if (isConnected()) {
        return;//from   w w  w .j  av  a2  s . co  m
    } else {
        logger.debug("Disconnected so we'll try again");
        disconnect();
    }

    if (CERTIFICATE_FILE_NAME != null && new File(CERTIFICATE_FILE_NAME).isFile()) {
        if (CERTIFICATE_PASSWORD == null) {
            CERTIFICATE_PASSWORD = "";
        }
        try {
            SSLClient client = new SSLClient();

            client.addTrustMaterial(TrustMaterial.DEFAULT);
            client.setCheckHostname(false);
            client.setKeyMaterial(new KeyMaterial(CERTIFICATE_FILE_NAME, CERTIFICATE_PASSWORD.toCharArray()));
            client.setConnectTimeout(10000);
            socket = (SSLSocket) client.createSocket(IP, PORT);
            socket.setSoTimeout(30000);
            socket.startHandshake();
        } catch (Exception e) {
            throw new Exception("Could not connect using certificate: " + CERTIFICATE_FILE_NAME, e);
        }
    } else {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {
                }
            } };

            ctx.init(null, trustAllCerts, null);
            socket = (SSLSocket) ctx.getSocketFactory().createSocket(IP, PORT);
            socket.setSoTimeout(10000);
            socket.startHandshake();
        } catch (Exception e) {
            throw new Exception("Cannot connect to " + IP + ":" + PORT, e);
        }
    }
    handleResponse();
}

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

private static void setupSslProps(Configuration conf) throws IOException {
    FileInputStream fis = null;/*from w ww.  j  a v  a  2 s .  c o  m*/
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        KeyManager[] kms = null;
        TrustManager[] tms = null;
        if (conf.get("ssl.client.keystore.location") != null) {
            // initialize default key manager with keystore file and pass
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            KeyStore ks = KeyStore.getInstance(conf.get("ssl.client.keystore.type", "JKS"));
            char[] ksPass = conf.get("ssl.client.keystore.password", "changeit").toCharArray();
            fis = new FileInputStream(conf.get("ssl.client.keystore.location", "keystore.jks"));
            ks.load(fis, ksPass);
            kmf.init(ks, conf.get("ssl.client.keystore.keypassword", "changeit").toCharArray());
            kms = kmf.getKeyManagers();
            fis.close();
            fis = null;
        }
        // initialize default trust manager with keystore file and pass
        if (conf.getBoolean("ssl.client.do.not.authenticate.server", false)) {
            // by pass trustmanager validation
            tms = new DummyTrustManager[] { new DummyTrustManager() };
        } else {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
            KeyStore ts = KeyStore.getInstance(conf.get("ssl.client.truststore.type", "JKS"));
            char[] tsPass = conf.get("ssl.client.truststore.password", "changeit").toCharArray();
            fis = new FileInputStream(conf.get("ssl.client.truststore.location", "truststore.jks"));
            ts.load(fis, tsPass);
            tmf.init(ts);
            tms = tmf.getTrustManagers();
        }
        sc.init(kms, tms, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        throw new IOException("Could not initialize SSLContext", e);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}

From source file:org.whispersystems.textsecure.internal.push.PushServiceSocket.java

private HttpURLConnection getConnection(String urlFragment, String method, String body)
        throws PushNetworkException {
    try {/*w ww . j  ava2s  .c  om*/
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, null);

        URL url = new URL(String.format("%s%s", serviceUrl, urlFragment));
        Log.w(TAG, "Push service URL: " + serviceUrl);
        Log.w(TAG, "Opening URL: " + url);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        if (ENFORCE_SSL) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(context.getSocketFactory());
            ((HttpsURLConnection) connection).setHostnameVerifier(new StrictHostnameVerifier());
        }

        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");

        if (credentialsProvider.getPassword() != null) {
            connection.setRequestProperty("Authorization", getAuthorizationHeader());
        }

        if (userAgent != null) {
            connection.setRequestProperty("X-Signal-Agent", userAgent);
        }

        if (body != null) {
            connection.setDoOutput(true);
        }

        connection.connect();

        if (body != null) {
            Log.w(TAG, method + "  --  " + body);
            OutputStream out = connection.getOutputStream();
            out.write(body.getBytes());
            out.close();
        }

        return connection;
    } catch (IOException e) {
        throw new PushNetworkException(e);
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new AssertionError(e);
    }
}

From source file:org.openhab.binding.samsungac.internal.AirConditioner.java

private void connect() throws Exception {
    if (isConnected()) {
        return;//from  www  . j  a  v a2  s.c o  m
    } else {
        logger.debug("Disconnected so we'll try again");
        disconnect();
    }

    if (CERTIFICATE_FILE_NAME != null && new File(CERTIFICATE_FILE_NAME).isFile()) {
        if (CERTIFICATE_PASSWORD == null) {
            CERTIFICATE_PASSWORD = "";
        }
        try {
            SSLClient client = new SSLClient();

            client.addTrustMaterial(TrustMaterial.DEFAULT);
            client.setCheckHostname(false);
            client.setKeyMaterial(new KeyMaterial(CERTIFICATE_FILE_NAME, CERTIFICATE_PASSWORD.toCharArray()));
            client.setConnectTimeout(10000);
            socket = (SSLSocket) client.createSocket(IP, PORT);
            socket.setSoTimeout(2000);
            socket.startHandshake();
        } catch (Exception e) {
            throw new Exception("Could not connect using certificate: " + CERTIFICATE_FILE_NAME, e);
        }
    } else {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {
                }
            } };

            ctx.init(null, trustAllCerts, null);
            socket = (SSLSocket) ctx.getSocketFactory().createSocket(IP, PORT);
            socket.setSoTimeout(2000);
            socket.startHandshake();
        } catch (Exception e) {
            throw new Exception("Cannot connect to " + IP + ":" + PORT, e);
        }
    }
    handleResponse();
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

private void setNoValidation() throws Exception {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*w w  w .  j av a  2 s. c  o m*/
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // Do nothing
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // Do nothing
        }
    } };

    // Install the all-trusting trust manager      
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

From source file:com.hybris.mobile.app.commerce.CommerceApplicationBase.java

public void onCreate() {
    super.onCreate();
    mInstance = this;

    String urlBackend = getStringFromSharedPreferences(getString(R.string.preference_key_value_base_url), "");
    String catalogStore = getStringFromSharedPreferences(getString(R.string.preference_key_value_catalog_store),
            "");// w  w  w  .  ja  va  2  s  . c o  m
    String catalogId = getStringFromSharedPreferences(getString(R.string.preference_key_value_catalog_id), "");
    String catalogMainCategory = getStringFromSharedPreferences(
            getString(R.string.preference_key_value_catalog_main_category_id), "");

    // Setting the default backend url
    if (StringUtils.isBlank(urlBackend)) {
        urlBackend = getString(R.string.url_backend);

        int index = ArrayUtils.indexOf(getResources().getStringArray(R.array.backend_url_values), urlBackend);

        // Update the settings
        setStringToSharedPreferences(getString(R.string.preference_key_value_base_url), urlBackend);
        setStringToSharedPreferences(getString(R.string.preference_key_key_base_url),
                getResources().getStringArray(R.array.backend_url_keys)[index]);
    }

    // Setting the default catalog
    if (StringUtils.isBlank(catalogStore)) {
        catalogStore = getString(R.string.url_path_catalog);
        setStringToSharedPreferences(getString(R.string.preference_key_value_catalog_store), catalogStore);
    }

    if (StringUtils.isBlank(catalogId)) {
        catalogId = getString(R.string.url_path_catalog_id);
        setStringToSharedPreferences(getString(R.string.preference_key_value_catalog_id), catalogId);
    }

    if (StringUtils.isBlank(catalogMainCategory)) {
        catalogMainCategory = getString(R.string.id_category_main);
        setStringToSharedPreferences(getString(R.string.preference_key_value_catalog_main_category_id),
                catalogMainCategory);
    }

    // Updating the pre-defined catalog key
    String catalogKey = catalogStore + "|" + catalogId + "|" + catalogMainCategory;
    int index = ArrayUtils.indexOf(getResources().getStringArray(R.array.backend_catalog_values), catalogKey);
    setStringToSharedPreferences(getString(R.string.preference_key_key_catalog),
            getResources().getStringArray(R.array.backend_catalog_keys)[index]);

    // Configuration for the backend url
    com.hybris.mobile.lib.commerce.Configuration configuration = new com.hybris.mobile.lib.commerce.Configuration();
    configuration.setBackendUrl(urlBackend);
    configuration.setCatalogId(catalogId);
    configuration.setCatalog(catalogStore);
    configuration.setCatalogVersionId(mInstance.getString(R.string.url_path_catalog_version_id));
    configuration.setCatalogAuthority(getString(R.string.provider_authority));
    configuration.setCatalogIdMainCategory(catalogMainCategory);

    // Bypassing SSLHelperSyncService
    TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

    SSLContext sslContext = null;

    try {
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustManager, new java.security.SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        Log.e(TAG, "Error with SSLHelperSyncService. Details: " + e.getLocalizedMessage());
    }

    if (sslContext == null) {
        throw new IllegalStateException("Unable to get an instance of SSLContext");
    }

    // Creating the content service helper
    mInstance.mContentServiceHelper = buildContentServiceHelper(configuration, sslContext.getSocketFactory(),
            new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

    // Build the configuration for the app
    mConfiguration = Configuration.buildConfiguration(this);

    // Barcode scanner instance
    mScannerHelper = new ScannerHelper(new CommerceBarcodeCheckerFactory());

    // Register local broadcast to Logout
    LocalBroadcastManager.getInstance(this).registerReceiver(new LogoutBroadcastReceiver(),
            new IntentFilter(getString(R.string.intent_action_logout)));

    // Register local broadcast to update cache on the content service helper
    LocalBroadcastManager.getInstance(this).registerReceiver(new UpdateCacheBroadcastReceiver(),
            new IntentFilter(getString(R.string.intent_action_update_cache)));

    // Default account for the sync adapter
    addCatalogSyncAdapterDefaultAccount();

    // We sync in advance the main category of the catalog to create the sync adapter and accelerate the process
    Bundle bundle = new Bundle();
    bundle.putString(CatalogSyncConstants.SYNC_PARAM_GROUP_ID, catalogMainCategory);
    bundle.putInt(CatalogSyncConstants.SYNC_PARAM_CURRENT_PAGE, 0);
    bundle.putInt(CatalogSyncConstants.SYNC_PARAM_PAGE_SIZE, mConfiguration.getDefaultPageSize());
    requestCatalogSyncAdapter(bundle);
}

From source file:org.kawanfw.commons.client.http.HttpTransferOne.java

/**
 * If called, self signed SSL certificates will be accepted
 *//*ww  w.  java2 s .  com*/
private void acceptSelfSignedSslCert() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Install the all-trusting trust manager
    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");

        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

}

From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java

@Override
public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, BuildListener _listener)
        throws InterruptedException, IOException {

    this.logger = _listener.getLogger();
    Dispatcher.TRACE = true;//from  w  w w.  ja va  2  s  .c om
    Dispatcher.TRACE_PER_REQUEST = true;

    this._token = null; // Important in order to get only this run events
    this.build = build;
    this.sseEventListener = new SseEventListener(this.logger);
    this.sseEventListener.addObserver(this);
    this.srfExecutionFuture = new CompletableFuture<>();
    this.runningCount = new HashSet<>();

    JSONObject conData = getSrfConnectionData(build, logger);
    if (conData == null)
        return false;

    _app = conData.getString("app");
    _secret = conData.getString("secret");
    _ftaasServerAddress = conData.getString("server");
    _https = conData.getBoolean("https");
    _tenant = conData.getString("tenant");
    String srfProxy = conData.getString("proxy");

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        _trustMgr = new SrfTrustManager();
        sslContext.init(null, new SrfTrustManager[] { _trustMgr }, null);
        SSLContext.setDefault(sslContext);
        _factory = sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    }

    if ((srfProxy != null) && (srfProxy.length() != 0)) {
        URL proxy = new URL(srfProxy);
        String proxyHost = proxy.getHost();
        String proxyPort = String.format("%d", proxy.getPort());
        Properties systemProperties = System.getProperties();
        systemProperties.setProperty("https.proxyHost", proxyHost);
        systemProperties.setProperty("http.proxyHost", proxyHost);
        systemProperties.setProperty("https.proxyPort", proxyPort);
        systemProperties.setProperty("http.proxyPort", proxyPort);
    }

    jobIds = null;
    try {
        initSrfEventListener();
        _secretApplied = false;

        try {
            jobIds = executeTestsSet();
            if (jobIds.size() > 0 && eventSrc == null)
                initSrfEventListener();

        } catch (AuthenticationException e) {
            initSrfEventListener();
            if (_token == null)
                _token = loginToSrf();
            _secretApplied = true;
        }

    } catch (UnknownHostException | ConnectException | SSLHandshakeException | IllegalArgumentException e) {
        cleanUp();
        logger.println(
                String.format("ERROR: Failed logging in to SRF server: %s %s", this._ftaasServerAddress, e));
        return false;
    } catch (IOException | SrfException e) {
        cleanUp();
        logger.println(String.format("ERROR: Failed executing test, %s", e));
        return false;
    }

    try {
        boolean buildResult = this.srfExecutionFuture.get();
        return buildResult;
    } catch (ExecutionException e) {
        e.printStackTrace();
        return false;
    } catch (InterruptedException e) {
        e.printStackTrace();
        build.setResult(Result.ABORTED);
        // postSrfJobCancellation();
        return false;
    } finally {
        cleanUp();
    }
}

From source file:com.ibm.iotf.client.AbstractClient.java

/**
 * Call to the configureConnOptionsWithToken() method is made, when the User chooses to connect to the
 * Watson IoT Platform using Device Token as the preferred Authentication mechanism. The Device Properties
 * file allows you enable either Token based or Certificate based or both mechanisms to authenticate.
 * However, setting the value to either 'True' or 'False' against the parameter 'Use-Secure-Certificate',
 * facilitates usage of Certificates for authentication or not, respectively.
 * Setting the value of parameter 'Use-Secure-Certificate' to 'False' in the Device.Properties file will
 * make a call to the following method. 
 *///w ww.j  av  a 2 s.c  om

private void connectUsingToken() {
    String protocol = null;
    int port = getPortNumber();
    if (isWebSocket()) {
        protocol = "wss://";
        // If there is no port specified use default
        if (port == -1) {
            port = WSS_PORT;
        }
    } else {
        protocol = "ssl://";
        // If there is no port specified use default
        if (port == -1) {
            port = MQTTS_PORT;
        }
    }

    String mqttServer = getMQTTServer();
    if (mqttServer != null) {
        serverURI = protocol + mqttServer + ":" + port;
    } else {
        serverURI = protocol + getOrgId() + "." + MESSAGING + "." + this.getDomain() + ":" + port;
    }
    try {
        mqttAsyncClient = new MqttAsyncClient(serverURI, clientId, DATA_STORE);
        mqttAsyncClient.setCallback(mqttCallback);
        mqttClientOptions = new MqttConnectOptions();
        if (clientUsername != null) {
            mqttClientOptions.setUserName(clientUsername);
        }
        if (clientPassword != null) {
            mqttClientOptions.setPassword(clientPassword.toCharArray());
        }
        mqttClientOptions.setCleanSession(this.isCleanSession());
        if (this.keepAliveInterval != -1) {
            mqttClientOptions.setKeepAliveInterval(this.keepAliveInterval);
        }
        mqttClientOptions.setMaxInflight(getMaxInflight());
        mqttClientOptions.setAutomaticReconnect(isAutomaticReconnect());

        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");

        sslContext.init(null, null, null);

        mqttClientOptions.setSocketFactory(sslContext.getSocketFactory());

    } catch (Exception e) {
        e.printStackTrace();
    }
}