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.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java

/**
 * Send REST call//ww w.  java 2 s  .  c  o m
 */
private String sendRESTCall(String url, String urlParameters, String formParameters, String httpMethod) {
    String line;
    StringBuilder responseString = new StringBuilder();
    HttpsURLConnection connection = null;
    try {
        setHttpsClientCert(
                "/media/sf_SharedFoldersToVBox/is-connectors/wikid/wikid-authenticator/org.wso2.carbon.identity.authenticator/src/main/resources/localhostWiKID",
                "shakila");
        SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();

        URL wikidEP = new URL(url + urlParameters);
        connection = (HttpsURLConnection) wikidEP.openConnection();
        connection.setSSLSocketFactory(sslsocketfactory);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(httpMethod);
        connection.setRequestProperty(WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE,
                WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE_XWFUE);
        if (httpMethod.toUpperCase().equals(WiKIDAuthenticatorConstants.HTTP_POST)) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),
                    WiKIDAuthenticatorConstants.CHARSET);
            writer.write(formParameters);
            writer.close();
        }
        if (connection.getResponseCode() == 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = br.readLine()) != null) {
                responseString.append(line);
            }
            br.close();
        } else {
            return WiKIDAuthenticatorConstants.FAILED + WiKIDAuthenticatorConstants.REQUEST_FAILED;
        }
    } catch (ProtocolException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } catch (MalformedURLException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } finally {
        connection.disconnect();
    }
    return responseString.toString();
}

From source file:com.amazonaws.http.UrlHttpClient.java

private void enableCustomTrustManager(HttpsURLConnection connection) {
    if (sc == null) {
        final TrustManager[] customTrustManagers = new TrustManager[] { config.getTrustManager() };
        try {/*w  ww . j a v a2  s. com*/
            sc = SSLContext.getInstance("TLS");
            sc.init(null, customTrustManagers, null);
        } catch (final GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }

    connection.setSSLSocketFactory(sc.getSocketFactory());
}

From source file:org.matrix.androidsdk.db.MXMediaWorkerTask.java

@Override
protected Bitmap doInBackground(Integer... params) {
    try {/*ww  w  .  j a v a 2 s .  c o m*/
        // check the in-memory cache
        String key = mUrl;

        URL url = new URL(mUrl);
        Log.d(LOG_TAG, "BitmapWorkerTask open >>>>> " + mUrl);

        InputStream stream = null;
        Bitmap bitmap = null;

        long filelen = -1;
        URLConnection connection = null;

        try {
            connection = url.openConnection();

            if (mHsConfig != null && connection instanceof HttpsURLConnection) {
                // Add SSL Socket factory.
                HttpsURLConnection sslConn = (HttpsURLConnection) connection;
                try {
                    sslConn.setSSLSocketFactory(CertUtil.newPinnedSSLSocketFactory(mHsConfig));
                    sslConn.setHostnameVerifier(CertUtil.newHostnameVerifier(mHsConfig));
                } catch (Exception e) {
                    Log.e(LOG_TAG, "doInBackground SSL exception " + e.getLocalizedMessage());
                }
            }

            // add a timeout to avoid infinite loading display.
            connection.setReadTimeout(10 * 1000);
            filelen = connection.getContentLength();
            stream = connection.getInputStream();
        } catch (FileNotFoundException e) {
            InputStream errorStream = ((HttpsURLConnection) connection).getErrorStream();

            if (null != errorStream) {
                try {
                    BufferedReader streamReader = new BufferedReader(
                            new InputStreamReader(errorStream, "UTF-8"));
                    StringBuilder responseStrBuilder = new StringBuilder();

                    String inputStr;

                    while ((inputStr = streamReader.readLine()) != null) {
                        responseStrBuilder.append(inputStr);
                    }

                    mErrorAsJsonElement = new JsonParser().parse(responseStrBuilder.toString());
                } catch (Exception ee) {
                }
            }

            Log.d(LOG_TAG, "MediaWorkerTask " + mUrl + " does not exist");
            if (isBitmapDownload()) {
                bitmap = BitmapFactory.decodeResource(mApplicationContext.getResources(),
                        android.R.drawable.ic_menu_gallery);

                // if some medias are not found
                // do not try to reload them until the next application launch.
                synchronized (mFileNotFoundUrlsList) {
                    mFileNotFoundUrlsList.add(mUrl);
                }
            }
        }

        sendStart();

        String filename = MXMediaWorkerTask.buildFileName(mUrl, mMimeType) + ".tmp";
        FileOutputStream fos = new FileOutputStream(new File(mDirectoryFile, filename));

        // a bitmap has been provided
        if (null != bitmap) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } else {
            try {
                int totalDownloaded = 0;

                byte[] buf = new byte[1024 * 32];
                int len;
                while ((len = stream.read(buf)) != -1) {
                    fos.write(buf, 0, len);

                    totalDownloaded += len;

                    int progress = 0;

                    if (filelen > 0) {
                        if (totalDownloaded >= filelen) {
                            progress = 99;
                        } else {
                            progress = (int) (totalDownloaded * 100 / filelen);
                        }
                    } else {
                        progress = -1;
                    }

                    Log.d(LOG_TAG, "download " + progress + " (" + mUrl + ")");

                    publishProgress(mProgress = progress);
                }

                mProgress = 100;
            } catch (OutOfMemoryError outOfMemoryError) {
                Log.e(LOG_TAG, "MediaWorkerTask : out of memory");
            } catch (Exception e) {
                Log.e(LOG_TAG, "MediaWorkerTask fail to read image " + e.getMessage());
            }

            close(stream);
        }

        fos.flush();
        fos.close();

        // the file has been successfully downloaded
        if (mProgress == 100) {
            try {
                File originalFile = new File(mDirectoryFile, filename);
                String newFileName = MXMediaWorkerTask.buildFileName(mUrl, mMimeType);
                File newFile = new File(mDirectoryFile, newFileName);
                if (newFile.exists()) {
                    // Or you could throw here.
                    mApplicationContext.deleteFile(newFileName);
                }
                originalFile.renameTo(newFile);
            } catch (Exception e) {
            }
        }

        Log.d(LOG_TAG, "download is done (" + mUrl + ")");

        synchronized (mPendingDownloadByUrl) {
            mPendingDownloadByUrl.remove(mUrl);
        }

        // load the bitmap from the cache
        if (isBitmapDownload()) {
            // get the bitmap from the filesytem
            if (null == bitmap) {
                bitmap = MXMediaWorkerTask.bitmapForURL(mApplicationContext, mDirectoryFile, key, mRotation,
                        mMimeType);
            }
        }

        return bitmap;
    } catch (Exception e) {
        // remove the image from the loading one
        // else the loading will be stucked (and never be tried again).
        synchronized (mPendingDownloadByUrl) {
            mPendingDownloadByUrl.remove(mUrl);
        }
        Log.e(LOG_TAG, "Unable to load bitmap: " + e);
        return null;
    }
}

From source file:com.tune.reporting.base.service.TuneServiceProxy.java

/**
 * Post request to TUNE Service API Service
 *
 * @return Boolean True if successful posting request, else False.
 * @throws TuneSdkException If error within SDK.
 *//*from ww w. j a  va  2s  .c  om*/
protected boolean postRequest() throws TuneSdkException {
    URL url = null;
    HttpsURLConnection conn = null;

    try {
        url = new URL(this.uri);
    } catch (MalformedURLException ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: %s: '%s'", this.uri,
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    try {
        // connect to the server over HTTPS and submit the payload
        conn = (HttpsURLConnection) url.openConnection();

        // Create the SSL connection
        SSLContext sc;
        sc = SSLContext.getInstance("TLS");
        sc.init(null, null, new java.security.SecureRandom());
        conn.setSSLSocketFactory(sc.getSocketFactory());

        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.connect();

        // Gets the status code from an HTTP response message.
        final int responseHttpCode = conn.getResponseCode();

        // Returns an unmodifiable Map of the header fields.
        // The Map keys are Strings that represent the response-header
        // field names. Each Map value is an unmodifiable List of Strings
        // that represents the corresponding field values.
        final Map<String, List<String>> responseHeaders = conn.getHeaderFields();

        final String requestUrl = url.toString();

        // Gets the HTTP response message, if any, returned along
        // with the response code from a server.
        String responseRaw = conn.getResponseMessage();

        // Pull entire JSON raw response
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        responseRaw = sb.toString();

        // decode to JSON
        JSONObject responseJson = new JSONObject(responseRaw);

        this.response = new TuneServiceResponse(responseRaw, responseJson, responseHttpCode, responseHeaders,
                requestUrl.toString());
    } catch (Exception ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: '%s'",
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    return true;
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private HttpsURLConnection getConnection(String request, int connectTimeout, int readTimeout)
        throws IOException {
    String correctedRequest = request;
    if (StringUtils.isNotBlank(correctedRequest)) {
        correctedRequest = fixRequest(correctedRequest);
        URL url = new URL(this.uri + correctedRequest);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        if (connection != null) {
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(readTimeout);
            if (sslSocketFactory != null) {
                connection.setSSLSocketFactory(sslSocketFactory);
            }/*  w w  w. j a  va 2s  .  c o m*/
            if (hostnameVerifier != null) {
                connection.setHostnameVerifier(hostnameVerifier);
            }
        }
        return connection;
    }
    return null;
}

From source file:org.wso2.carbon.identity.authenticator.PushResult.java

/**
 * validate push result//from   ww w .  j  av  a  2 s.co m
 */
public JSONObject checkPushResult(String userId, String sessionId) throws AuthenticationFailedException {
    String urlParameters = null;
    JSONObject json = null;
    HttpsURLConnection conn = null;
    InputStream is = null;
    try {
        urlParameters = "action=checkPushResult" + "&serviceId="
                + URLEncoder.encode("" + serviceId, InweboConstants.ENCODING) + "&userId="
                + URLEncoder.encode(userId, InweboConstants.ENCODING) + "&sessionId="
                + URLEncoder.encode(sessionId, InweboConstants.ENCODING) + "&format=json";
        if (this.context == null) {
            this.context = PushAuthentication.setHttpsClientCert(this.p12file, this.p12password);
        }
        SSLSocketFactory sslsocketfactory = context.getSocketFactory();
        URL url = new URL(urlString + urlParameters);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(sslsocketfactory);
        conn.setRequestMethod("GET");
        is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, InweboConstants.ENCODING));
        JSONParser parser = new JSONParser();
        json = (JSONObject) parser.parse(br);
    } catch (UnsupportedEncodingException e) {
        throw new AuthenticationFailedException("Error while encoding the URL" + e.getMessage(), e);
    } catch (MalformedURLException e) {
        throw new AuthenticationFailedException("Error while creating the URL" + e.getMessage(), e);
    } catch (IOException e) {
        throw new AuthenticationFailedException("Error while creating the connection" + e.getMessage(), e);
    } catch (ParseException e) {
        throw new AuthenticationFailedException("Error while parsing the json object" + e.getMessage(), e);
    } catch (Exception e) {
        throw new AuthenticationFailedException("Error while pushing authentication" + e.getMessage(), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            throw new AuthenticationFailedException("Error while closing stream" + e.getMessage(), e);
        }
    }
    return json;
}

From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java

private SSLContext setSSLCallback(ISSLCertificateCallback sslAuthorizationCallback, URL url,
        HttpsURLConnection connection) {
    X509TrustManager trustManager = null;
    if (sslAuthorizationCallback != null) {
        connection.setHostnameVerifier(new CallbackHostnameVerifier());
        trustManager = createCallbackTrustManager(sslAuthorizationCallback, connection);
    }// w w w. ja  v a 2  s . c  om

    try {
        SSLContext sslContext = SSLUtils.getSSLContext(trustManager);
        connection.setSSLSocketFactory(sslContext.getSocketFactory());
        return sslContext;
    } catch (GeneralSecurityException e) {
        LOGGER.warn("Could not install trust manager callback", e);
        ;
        return null;
    }
}

From source file:de.bps.webservices.clients.onyxreporter.OnyxReporterConnector.java

private boolean isServiceAvailable(String target) {

    HostnameVerifier hv = new HostnameVerifier() {
        @Override/*from  w w  w.  j av  a  2s .c  o  m*/
        public boolean verify(String urlHostName, SSLSession session) {
            if (urlHostName.equals(session.getPeerHost())) {
                return true;
            } else {
                return false;
            }
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    try {
        URL url = new URL(target + "?wsdl");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection sslconn = (HttpsURLConnection) con;
            SSLContext context = SSLContext.getInstance("SSL");
            context.init(SSLConfigurationModule.getKeyManagers(), SSLConfigurationModule.getTrustManagers(),
                    new java.security.SecureRandom());
            sslconn.setSSLSocketFactory(context.getSocketFactory());
            sslconn.connect();
            if (sslconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                sslconn.disconnect();
                return true;
            }
        } else {
            con.connect();
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                con.disconnect();
                return true;
            }
        }
    } catch (Exception e) {
        Tracing.createLoggerFor(getClass()).error("Error while trying to connect to webservice: " + target, e);
    }
    return false;
}

From source file:android.webkit.cts.TestWebServer.java

private URLConnection openConnection(URL url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    if (mSsl) {//from   w w  w . j  a  v  a2  s. c o  m
        // Install hostname verifiers and trust managers that don't do
        // anything in order to get around the client not trusting
        // the test server due to a lack of certificates.

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(new TestHostnameVerifier());

        SSLContext context = SSLContext.getInstance("TLS");
        TestTrustManager trustManager = new TestTrustManager();
        context.init(null, new TestTrustManager[] { trustManager }, null);
        connection.setSSLSocketFactory(context.getSocketFactory());

        return connection;
    } else {
        return url.openConnection();
    }
}

From source file:org.exoplatform.services.videocall.AuthService.java

public String authenticate(VideoCallModel videoCallModel, String profile_id) {
    VideoCallService videoCallService = new VideoCallService();
    if (videoCallModel == null) {
        caFile = videoCallService.getPemCertInputStream();
        p12File = videoCallService.getP12CertInputStream();
        videoCallModel = videoCallService.getVideoCallProfile();
    } else {/*from   w w w. j  ava 2  s. c  om*/
        caFile = videoCallModel.getPemCert();
        p12File = videoCallModel.getP12Cert();
    }

    if (videoCallModel != null) {
        domain_id = videoCallModel.getDomainId();
        clientId = videoCallModel.getAuthId();
        clientSecret = videoCallModel.getAuthSecret();
        passphrase = videoCallModel.getCustomerCertificatePassphrase();
    }
    String responseContent = null;
    if (StringUtils.isEmpty(passphrase))
        return null;
    if (caFile == null || p12File == null)
        return null;

    try {
        String userId = ConversationState.getCurrent().getIdentity().getUserId();
        SSLContext ctx = SSLContext.getInstance("SSL");
        URL url = null;
        try {
            StringBuilder urlBuilder = new StringBuilder();
            urlBuilder.append(authUrl).append("?client_id=" + clientId).append("&client_secret=" + clientSecret)
                    .append("&uid=weemo" + userId)
                    .append("&identifier_client=" + URLEncoder.encode(domain_id, "UTF-8"))
                    .append("&id_profile=" + URLEncoder.encode(profile_id, "UTF-8"));
            url = new URL(urlBuilder.toString());
        } catch (MalformedURLException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not create valid URL with base", e);
            }
        }
        HttpsURLConnection connection = null;
        try {
            connection = (HttpsURLConnection) url.openConnection();
        } catch (IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not connect", e);
            }
        }
        TrustManager[] trustManagers = getTrustManagers(caFile, passphrase);
        KeyManager[] keyManagers = getKeyManagers("PKCS12", p12File, passphrase);

        ctx.init(keyManagers, trustManagers, new SecureRandom());
        try {
            connection.setSSLSocketFactory(ctx.getSocketFactory());
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not configure request for POST", e);
            }
        }

        try {
            connection.connect();
        } catch (IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not connect to weemo", e);
            }
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sbuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sbuilder.append(line + "\n");
        }
        br.close();
        responseContent = sbuilder.toString();
        // Set new token key
        String tokenKey = "";
        if (!StringUtils.isEmpty(responseContent)) {
            JSONObject json = new JSONObject(responseContent);
            tokenKey = json.get("token").toString();
        } else {
            tokenKey = "";
        }
        videoCallService.setTokenKey(tokenKey);
    } catch (Exception ex) {
        LOG.error("Have problem during authenticating process.", ex);
        videoCallService.setTokenKey("");
    }
    return responseContent;
}