Example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

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

Introduction

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

Prototype

public static void setDefaultHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the default HostnameVerifier inherited by a new instance of this class.

Usage

From source file:net.vexelon.mobileops.GLBClient.java

/**
 * Initialize Http Client// ww  w. j a v a 2  s . c  o  m
 */
private void initHttpClient() {

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setParameter(CoreProtocolPNames.USER_AGENT, UserAgentHelper.getRandomUserAgent());
    //params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
    // Bugfix #1: The target server failed to respond
    params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    DefaultHttpClient client = new DefaultHttpClient(params);

    httpCookieStore = new BasicCookieStore();
    client.setCookieStore(httpCookieStore);

    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, httpCookieStore);

    // Bugfix #1: Adding retry handler to repeat failed requests
    HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

            if (executionCount >= MAX_REQUEST_RETRIES) {
                return false;
            }

            if (exception instanceof NoHttpResponseException || exception instanceof ClientProtocolException) {
                return true;
            }

            return false;
        }
    };
    client.setHttpRequestRetryHandler(retryHandler);

    // SSL
    HostnameVerifier verifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    try {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", new PlainSocketFactory(), 80));
        registry.register(new Scheme("https", new TrustAllSocketFactory(), 443));

        SingleClientConnManager connMgr = new SingleClientConnManager(client.getParams(), registry);

        httpClient = new DefaultHttpClient(connMgr, client.getParams());
    } catch (InvalidAlgorithmParameterException e) {
        //         Log.e(Defs.LOG_TAG, "", e);

        // init without connection manager
        httpClient = new DefaultHttpClient(client.getParams());
    }

    HttpsURLConnection.setDefaultHostnameVerifier(verifier);

}

From source file:org.kuali.mobility.push.dao.PushDaoImpl.java

@SuppressWarnings("unchecked")
private boolean sendPushToAndroid(Push push, Device device) {

    try {//from w ww . java  2s.  c  om
        HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
        URL url = new URL("https://android.apis.google.com/c2dm/send");
        HttpsURLConnection request = (HttpsURLConnection) url.openConnection();

        LOG.info("---- Version: " + url.getClass().getPackage().getSpecificationVersion());
        LOG.info("---- Impl:    " + url.getClass().getPackage().getImplementationVersion());
        String handlers = System.getProperty("java.protocol.handler.pkgs");

        LOG.info(handlers);
        request.setDoOutput(true);
        request.setDoInput(true);

        StringBuilder buf = new StringBuilder();
        buf.append("registration_id").append("=").append((URLEncoder.encode(device.getRegId(), "UTF-8")));
        buf.append("&collapse_key").append("=")
                .append((URLEncoder.encode(push.getPostedTimestamp().toString(), "UTF-8")));
        buf.append("&data.message").append("=").append((URLEncoder.encode(push.getMessage(), "UTF-8")));
        buf.append("&data.title").append("=").append((URLEncoder.encode(push.getTitle(), "UTF-8")));
        buf.append("&data.id").append("=").append((URLEncoder.encode(push.getPushId().toString(), "UTF-8")));
        buf.append("&data.url").append("=").append((URLEncoder.encode(push.getUrl().toString(), "UTF-8")));

        String emer = (push.getEmergency()) ? "YES" : "NO";
        buf.append("&data.emer").append("=").append((URLEncoder.encode(emer, "UTF-8")));

        request.setRequestMethod("POST");
        request.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        request.setRequestProperty("Content-Length", buf.toString().getBytes().length + "");
        request.setRequestProperty("Authorization", "GoogleLogin auth=" + GoogleAuthToken);

        LOG.info("SEND Android Buffer: " + buf.toString());

        OutputStreamWriter post = new OutputStreamWriter(request.getOutputStream());
        post.write(buf.toString());
        post.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
        buf = new StringBuilder();
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            buf.append(inputLine);
        }
        post.close();
        in.close();

        LOG.info("response from C2DM server:\n" + buf.toString());

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:ddf.common.test.cometd.CometDClient.java

private void doTrustAllCertificates() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//from   w ww .  j  av a 2  s.  c o  m
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
            return;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
            return;
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HostnameVerifier hostnameVerifier = (s, sslSession) -> s.equalsIgnoreCase(sslSession.getPeerHost());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}

From source file:com.nubits.nubot.utils.Utils.java

/**
 * Install a trust manager that does not validate certificate chains for https calls
 *
 * @throws Exception/* ww w. ja  v a 2 s.com*/
 */
private static void installTrustAllManager() throws Exception {

    // 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 = 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);
}

From source file:com.sitewhere.wso2.identity.scim.Wso2ScimAssetModule.java

protected SSLContext createContext() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }// ww  w.j  a va2  s.  c o m

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return sc;

    } catch (Exception e) {
    }
    return null;
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

public AAIService(URL propURL) {
    LOG.info("Entered AAIService.ctor");

    String runtime = System.getProperty("aaiclient.runtime");
    if (runtime != null && runtime.equals("OSGI")) {
        runtimeOSGI = true;//from   w  w  w.  j  av a2  s.  com
    } else {
        runtimeOSGI = false;
    }

    Properties props = null;
    try {
        props = initialize(propURL);
        AAIRequest.setProperties(props, this);

    } catch (Exception exc) {
        LOG.error("AicAAIResource.static", exc);
    }

    executor = new AAIRequestExecutor();

    user_name = props.getProperty(CLIENT_NAME);
    user_password = props.getProperty(CLIENT_PWWD);

    if (user_name == null || user_name.isEmpty()) {
        LOG.debug("Basic user name is not set");
    }
    if (user_password == null || user_password.isEmpty()) {
        LOG.debug("Basic password is not set");
    }

    truststore_path = props.getProperty(TRUSTSTORE_PATH);
    truststore_password = props.getProperty(TRUSTSTORE_PSSWD);
    keystore_path = props.getProperty(KEYSTORE_PATH);
    keystore_password = props.getProperty(KEYSTORE_PSSWD);

    target_uri = props.getProperty(TARGET_URI);
    query_path = props.getProperty(QUERY_PATH);
    update_path = props.getProperty(UPDATE_PATH);

    String applicationId = props.getProperty(APPLICATION_ID);
    if (applicationId == null || applicationId.isEmpty()) {
        applicationId = "SDNC";
    }
    application_id = applicationId;

    // connection timeout
    int tmpConnectionTimeout = 30000;
    int tmpReadTimeout = 30000;

    try {
        String tmpValue = null;
        tmpValue = props.getProperty(CONNECTION_TIMEOUT, "30000");
        tmpConnectionTimeout = Integer.parseInt(tmpValue);
        tmpValue = props.getProperty(READ_TIMEOUT, "30000");
        tmpReadTimeout = Integer.parseInt(tmpValue);
    } catch (Exception exc) {
        LOG.error("Failed setting connection timeout", exc);
        tmpConnectionTimeout = 30000;
        tmpReadTimeout = 30000;
    }
    connection_timeout = tmpConnectionTimeout;
    read_timeout = tmpReadTimeout;

    network_vserver_path = props.getProperty(NETWORK_VSERVER_PATH);

    svc_instance_path = props.getProperty(SVC_INSTANCE_PATH); // "/aai/v1/business/customers/customer/{customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances");
    //      "/aai/v1/business/customers/customer/ma9181-203-customerid/service-subscriptions/service-subscription/ma9181%20Hosted%20Voice/service-instances";

    //      svc_inst_qry_path   = props.getProperty(SVC_INST_QRY_PATH, "/aai/v1/search/generic-query?key=service-instance.service-instance-id:ma9181-204-instance&start-node-type=service-instance&include=service-instance");
    svc_inst_qry_path = props.getProperty(SVC_INST_QRY_PATH); // "/aai/v1/search/generic-query?key=service-instance.service-instance-id:{svc-instance-id}&start-node-type=service-instance&include=service-instance");

    param_service_type = props.getProperty(PARAM_SERVICE_TYPE, "service-type");

    // P-Interfaces
    p_interface_path = props.getProperty(P_INTERFACE_PATH);

    vnf_image_query_path = props.getProperty(VNF_IMAGE_QUERY_PATH);

    ubb_notify_path = props.getProperty(UBB_NOTIFY_PATH);
    selflink_avpn = props.getProperty(SELFLINK_AVPN);
    selflink_fqdn = props.getProperty(SELFLINK_FQDN);

    service_path = props.getProperty(SERVICE_PATH);

    site_pair_set_path = props.getProperty(SITE_PAIR_SET_PATH);

    query_nodes_path = props.getProperty(QUERY_NODES_PATH);

    String iche = props.getProperty(CERTIFICATE_HOST_ERROR);
    boolean host_error = false;
    if (iche != null && !iche.isEmpty()) {
        host_error = Boolean.valueOf(iche);
    }

    ignore_certificate_host_error = host_error;

    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String string, SSLSession ssls) {
            return ignore_certificate_host_error;
        }
    });

    if (truststore_path != null && truststore_password != null && (new File(truststore_path)).exists()) {
        System.setProperty("javax.net.ssl.trustStore", truststore_path);
        System.setProperty("javax.net.ssl.trustStorePassword", truststore_password);
    }

    if (keystore_path != null && keystore_password != null && (new File(keystore_path)).exists()) {
        DefaultClientConfig config = new DefaultClientConfig();
        //both jersey and HttpURLConnection can use this
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");

            KeyManagerFactory kmf = null;
            try {
                String def = "SunX509";
                String storeType = "PKCS12";
                def = KeyStore.getDefaultType();
                kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                FileInputStream fin = new FileInputStream(keystore_path);
                //                KeyStore ks = KeyStore.getInstance("PKCS12");

                String extension = keystore_path.substring(keystore_path.lastIndexOf(".") + 1);

                if (extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) {
                    storeType = "JKS";
                }
                KeyStore ks = KeyStore.getInstance(storeType);

                char[] pwd = keystore_password.toCharArray();
                ks.load(fin, pwd);
                kmf.init(ks, pwd);
            } catch (Exception ex) {
                LOG.error("AAIResource", ex);
            }

            ctx.init(kmf.getKeyManagers(), null, null);
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return ignore_certificate_host_error;
                        }
                    }, ctx));

            CTX = ctx;
            LOG.debug("SSLContext created");

        } catch (KeyManagementException | NoSuchAlgorithmException exc) {
            LOG.error("AAIResource", exc);
        }
    }

    LOG.info("AAIResource.ctor initialized.");

    try {
        Field methodsField = HttpURLConnection.class.getDeclaredField("methods");
        methodsField.setAccessible(true);
        // get the methods field modifiers
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        // bypass the "private" modifier
        modifiersField.setAccessible(true);

        // remove the "final" modifier
        modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);

        /* valid HTTP methods */
        String[] methods = { "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE", "PATCH" };
        // set the new methods - including patch
        methodsField.set(null, methods);

    } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) {
        e.printStackTrace();
    }

}

From source file:com.flexvdi.androidlauncher.LoginActivity.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    mContext = this;

    try {//  w ww.jav  a2  s. c o  m
        GStreamer.init(mContext);
    } catch (Exception e) {
        Log.e(TAG, "Can't initialize GStreamer" + e.getMessage());
        finish();
    }

    settings = getSharedPreferences("flexVDI", MODE_PRIVATE);
    settingsEditor = settings.edit();
    /* Uncomment this for clearing preferences (useful when debugging) */
    //settingsEditor.clear();
    //settingsEditor.apply();
    //settingsEditor.commit();

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.activity_login);

    textUser = (EditText) findViewById(R.id.textUser);
    textServer = (EditText) findViewById(R.id.textServer);
    textPassword = (EditText) findViewById(R.id.textPassword);

    goButton = (Button) findViewById(R.id.buttonGO);
    goButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ConnectivityManager cm = (ConnectivityManager) mContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

            if (!isConnected) {
                Toast.makeText(view.getContext(), getResources().getString(R.string.no_network),
                        Toast.LENGTH_LONG).show();
                return;
            }

            if (checkBoxGenericSpice.isChecked()) {
                String userField = textUser.getText().toString();
                if (userField.length() == 0 || !userField.contains(":")) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.invalid_spice_server),
                            Toast.LENGTH_LONG).show();
                    return;
                }

                String spiceAddress = userField.substring(0, userField.indexOf(":"));
                String spicePort = userField.substring(userField.indexOf(":") + 1);

                if (spiceAddress.length() == 0 || spicePort.length() == 0) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.invalid_spice_server),
                            Toast.LENGTH_LONG).show();
                    return;
                }

                String spicePassword = textPassword.getText().toString();

                settingsEditor.putBoolean("enableSound", checkBoxEnableSound.isChecked());
                settingsEditor.putBoolean("staticResolution", checkBoxStaticResolution.isChecked());
                settingsEditor.putBoolean("genericSpice", checkBoxGenericSpice.isChecked());
                settingsEditor.putString("flexServerName", textServer.getText().toString());

                settingsEditor.putString("spice_address", spiceAddress);
                settingsEditor.putString("spice_port", spicePort);
                settingsEditor.putString("spice_password", spicePassword);
                settingsEditor.putBoolean("use_ws", false);

                settingsEditor.apply();
                settingsEditor.commit();

                startMainActivity();
            } else {
                if (textServer.getText().length() == 0) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.empty_flexvdi_server),
                            Toast.LENGTH_LONG).show();
                } else {
                    if (textUser.getText().length() != 0 && textPassword.getText().length() != 0) {
                        new RequestTask().execute("authmode", textServer.getText().toString(),
                                textUser.getText().toString(), textPassword.getText().toString(), "");
                    } else
                        Toast.makeText(view.getContext(), getResources().getString(R.string.empty_credentials),
                                Toast.LENGTH_LONG).show();
                }
            }
        }
    });

    // The advanced settings button.
    checkBoxAdvancedOptions = (CheckBox) findViewById(R.id.checkBoxAdvancedSettings);
    layoutAdvancedOptions = (LinearLayout) findViewById(R.id.layoutAdvancedOptions2);
    checkBoxAdvancedOptions.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            if (checked)
                layoutAdvancedOptions.setVisibility(View.VISIBLE);
            else
                layoutAdvancedOptions.setVisibility(View.GONE);
        }
    });

    textServer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View field, boolean hasFocus) {
            if (!hasFocus && checkBoxGenericSpice.isChecked()) {
                if (textUser.getText().toString().length() == 0) {
                    textUser.setText(textServer.getText());
                }
            }
        }
    });

    checkBoxEnableSound = (CheckBox) findViewById(R.id.checkBoxEnableSound);
    if (settings.getBoolean("enableSound", true)) {
        checkBoxEnableSound.setChecked(true);
    } else {
        checkBoxEnableSound.setChecked(false);
    }

    if (!settings.contains("staticResolution")) {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        if ((size.x + size.y) > 2340) {
            /* 2340 = 1440+900 */
            settingsEditor.putBoolean("staticResolution", true);
        } else {
            settingsEditor.putBoolean("staticResolution", false);
        }
        settingsEditor.apply();
        settingsEditor.commit();
    }

    checkBoxStaticResolution = (CheckBox) findViewById(R.id.checkBoxStaticResolution);
    if (settings.getBoolean("staticResolution", true)) {
        checkBoxStaticResolution.setChecked(true);
    } else {
        checkBoxStaticResolution.setChecked(false);
    }

    checkBoxGenericSpice = (CheckBox) findViewById(R.id.checkBoxGenericSpice);
    if (settings.getBoolean("genericSpice", false)) {
        checkBoxGenericSpice.setChecked(true);
        checkBoxAdvancedOptions.setChecked(true);
        layoutAdvancedOptions.setVisibility(View.VISIBLE);

        if (settings.contains("flexServerName")) {
            textServer.setText(settings.getString("flexServerName", ""));
            textUser.setText(settings.getString("flexServerName", ""));
            textServer.setHint(getResources().getString(R.string.spice_server));
            textUser.setHint(getResources().getString(R.string.spice_server_port));
        }
    } else {
        checkBoxGenericSpice.setChecked(false);
        if (settings.contains("flexServerName")) {
            textServer.setText(settings.getString("flexServerName", ""));
            layoutAdvancedOptions.setVisibility(View.GONE);
        } else {
            textServer.setText("manager.flexvdi.com");
            checkBoxAdvancedOptions.setChecked(true);
        }
    }

    checkBoxGenericSpice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            if (checked) {
                textServer.setHint(getResources().getString(R.string.spice_server));
                textUser.setHint(getResources().getString(R.string.spice_server_port));
                String server = textServer.getText().toString();
                if (server.length() != 0) {
                    if (server.contains(":")) {
                        textUser.setText(server);
                    } else {
                        textUser.setText(server + ":5900");
                        textServer.setText(server + ":5900");
                    }
                }
            } else {
                textServer.setHint(getResources().getString(R.string.flexvdi_server));
                String server = textServer.getText().toString();
                if (server.length() != 0 && server.contains(":")) {
                    textServer.setText(server.substring(0, server.indexOf(":")));
                }
                textUser.setText("");
                textUser.setHint(getResources().getString(R.string.user));
            }
        }
    });

    deviceID = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);

    textViewDeviceID = (TextView) findViewById(R.id.textViewDeviceID);
    textViewDeviceID.setText("ID: " + deviceID + " (" + BuildConfig.VERSION_NAME + ")");

    try {
        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { new NullX509TrustManager() }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    } catch (NoSuchAlgorithmException nsae) {
        Log.e(TAG, nsae.getMessage());
    } catch (KeyManagementException kme) {
        Log.e(TAG, kme.getMessage());
    }
}

From source file:org.kurento.test.base.BrowserTest.java

public void waitForHostIsReachable(URL url, int timeout) {
    long timeoutMillis = TimeUnit.MILLISECONDS.convert(timeout, TimeUnit.SECONDS);
    long endTimeMillis = System.currentTimeMillis() + timeoutMillis;

    log.debug("Waiting for {} to be reachable (timeout {} seconds)", url, timeout);

    try {/*from   w  w  w  .j  a  va  2s  .  co  m*/
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

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

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        int responseCode = 0;
        while (true) {
            try {
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout((int) timeoutMillis);
                connection.setReadTimeout((int) timeoutMillis);
                connection.setRequestMethod("HEAD");
                responseCode = connection.getResponseCode();

                break;
            } catch (SSLHandshakeException | SocketException e) {
                log.warn("Error {} waiting URL {}, trying again in 1 second", e.getMessage(), url);
                // Polling to wait a consistent SSL state
                Thread.sleep(1000);
            }
            if (System.currentTimeMillis() > endTimeMillis) {
                break;
            }
        }

        if (responseCode != HttpURLConnection.HTTP_OK) {
            log.warn("URL " + url + " not reachable. Response code=" + responseCode);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("URL " + url + " not reachable in " + timeout + " seconds (" + e.getClass().getName() + ", "
                + e.getMessage() + ")");
    }

    log.debug("URL {} already reachable", url);
}

From source file:com.createtank.payments.coinbase.RequestClient.java

public static void disableCertificateValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }//from   w w  w  .j  a v a 2 s  .  c  o  m

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

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

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {
        //Ignore
    }
}

From source file:org.apache.stratos.cli.RestCommandLineService.java

/**
 * Authenticate and login to stratos server.
 *
 * @param serverURL     URL of the server
 * @param username      username/*  ww  w  .  j av a 2s  .  co  m*/
 * @param password      password
 * @param validateLogin validate login
 * @return boolean
 * @throws Exception
 */
public boolean login(String serverURL, String username, String password, boolean validateLogin)
        throws Exception {
    try {
        // Avoid validating SSL certificate
        SSLContext sc = SSLContext.getInstance("SSL");
        // Create empty HostnameVerifier
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        // 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(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {
        throw new RuntimeException("Error while authentication process!", e);
    }

    // Initialize client
    try {
        initializeRestClient(serverURL, username, password);

        if (log.isDebugEnabled()) {
            log.debug("Initialized REST Client for user {}", username);
        }
    } catch (AxisFault e) {
        String message = "Error connecting to the stratos server";
        printError(message, e);
        throw new CommandException(e);
    }

    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        if (validateLogin) {
            HttpResponse response = restClient.doGet(httpClient, restClient.getBaseURL() + ENDPOINT_INIT);

            if (response != null) {
                int responseCode = response.getStatusLine().getStatusCode();
                if (responseCode == 200) {
                    return true;
                } else {
                    System.out.println("Invalid value is set for STRATOS_URL");
                }
            }
            return false;
        } else {
            // Just return true as we don't need to validate
            return true;
        }
    } catch (ConnectException e) {
        String message = "Could not connect to stratos manager";
        printError(message, e);
        return false;
    } catch (java.lang.NoSuchMethodError e) {
        String message = "Authentication failed!";
        printError(message, e);
        return false;
    } catch (Exception e) {
        if (e.getCause() instanceof MalformedChallengeException) {
            String message = "Authentication failed. Please check your username/password";
            printError(message, e);
            return false;
        }
        String message = "An unknown error occurred: " + e.getMessage();
        printError(message, e);
        return false;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}