Example usage for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory

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

Introduction

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

Prototype

public static void setDefaultSSLSocketFactory(SSLSocketFactory sf) 

Source Link

Document

Sets the default SSLSocketFactory inherited by new instances of this class.

Usage

From source file:org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig.java

public void initConfig(Properties properties) throws SSOAgentException {

    requestQueryParameters = properties.getProperty("SAML.Request.Query.Param");
    if (properties.getProperty("SSL.EnableSSLVerification") != null) {
        enableSSLVerification = Boolean.parseBoolean(properties.getProperty("SSL.EnableSSLVerification"));
    }//from   w  w w . j av a 2 s.c o  m
    if (properties.getProperty("SSL.EnableSSLHostNameVerification") != null) {
        enableHostNameVerification = Boolean
                .parseBoolean(properties.getProperty("SSL.EnableSSLHostNameVerification"));
    }
    String isSAML2SSOLoginEnabledString = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.ENABLE_SAML2_SSO_LOGIN);
    if (isSAML2SSOLoginEnabledString != null) {
        isSAML2SSOLoginEnabled = Boolean.parseBoolean(isSAML2SSOLoginEnabledString);
    } else {
        LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.ENABLE_SAML2_SSO_LOGIN
                + " not configured. Defaulting to \'false\'");
        isSAML2SSOLoginEnabled = false;
    }

    String isOpenIdLoginEnabledString = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.ENABLE_OPENID_SSO_LOGIN);
    if (isOpenIdLoginEnabledString != null) {
        isOpenIdLoginEnabled = Boolean.parseBoolean(isOpenIdLoginEnabledString);
    } else {
        LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.ENABLE_OPENID_SSO_LOGIN
                + " not configured. Defaulting to \'false\'");
        isOpenIdLoginEnabled = false;
    }

    String isSAML2OAuth2GrantEnabledString = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.ENABLE_OAUTH2_SAML2_OAUTH2_GRANT);
    if (isSAML2OAuth2GrantEnabledString != null) {
        isOAuth2SAML2GrantEnabled = Boolean.parseBoolean(isSAML2OAuth2GrantEnabledString);
    } else {
        LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.ENABLE_OAUTH2_SAML2_OAUTH2_GRANT
                + " not configured. Defaulting to \'false\'");
        isOAuth2SAML2GrantEnabled = false;
    }

    saml2SSOURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2_SSO_URL);
    openIdURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.OPENID_URL);
    oauth2SAML2GrantURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.OAUTH2_SAML2_GRANT_URL);

    String skipURIsString = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SKIP_URIS);
    if (!StringUtils.isBlank(skipURIsString)) {
        String[] skipURIArray = skipURIsString.split(",");
        for (String skipURI : skipURIArray) {
            skipURIs.add(skipURI);
        }
    }

    String queryParamsString = properties.getProperty(SSOAgentConstants.SSOAgentConfig.QUERY_PARAMS);
    if (!StringUtils.isBlank(queryParamsString)) {
        String[] queryParamsArray = queryParamsString.split("&");
        Map<String, List<String>> queryParamMap = new HashMap<String, List<String>>();
        if (queryParamsArray.length > 0) {
            for (String queryParam : queryParamsArray) {
                String[] splitParam = queryParam.split("=");
                if (splitParam.length == 2) {
                    if (queryParamMap.get(splitParam[0]) != null) {
                        queryParamMap.get(splitParam[0]).add(splitParam[1]);
                    } else {
                        List<String> newList = new ArrayList<String>();
                        newList.add(splitParam[1]);
                        queryParamMap.put(splitParam[0], newList);
                    }
                }

            }
            for (Map.Entry<String, List<String>> entry : queryParamMap.entrySet()) {
                String[] valueArray = entry.getValue().toArray(new String[entry.getValue().size()]);
                queryParams.put(entry.getKey(), valueArray);
            }
        }
    }

    saml2.httpBinding = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.HTTP_BINDING);
    if (saml2.httpBinding == null || saml2.httpBinding.isEmpty()) {
        LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.HTTP_BINDING
                + " not configured. Defaulting to \'" + SAMLConstants.SAML2_POST_BINDING_URI + "\'");
        saml2.httpBinding = SAMLConstants.SAML2_POST_BINDING_URI;
    }
    saml2.spEntityId = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.SP_ENTITY_ID);
    saml2.acsURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ACS_URL);
    saml2.idPEntityId = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.IDP_ENTITY_ID);
    saml2.idPURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.IDP_URL);
    saml2.attributeConsumingServiceIndex = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ATTRIBUTE_CONSUMING_SERVICE_INDEX);

    String isSLOEnabledString = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_SLO);
    if (isSLOEnabledString != null) {
        saml2.isSLOEnabled = Boolean.parseBoolean(isSLOEnabledString);
    } else {
        LOGGER.info("\'" + SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_SLO
                + "\' not configured. Defaulting to \'false\'");
        saml2.isSLOEnabled = false;
    }
    saml2.sloURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.SLO_URL);

    String isAssertionSignedString = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_SIGNING);
    if (isAssertionSignedString != null) {
        saml2.isAssertionSigned = Boolean.parseBoolean(isAssertionSignedString);
    } else {
        LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_SIGNING
                + " not configured. Defaulting to \'false\'");
        saml2.isAssertionSigned = false;
    }

    String isAssertionEncryptedString = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_ENCRYPTION);
    if (isAssertionEncryptedString != null) {
        saml2.isAssertionEncrypted = Boolean.parseBoolean(isAssertionEncryptedString);
    } else {
        LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_ASSERTION_ENCRYPTION
                + " not configured. Defaulting to \'false\'");
        saml2.isAssertionEncrypted = false;
    }

    String isResponseSignedString = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_RESPONSE_SIGNING);
    if (isResponseSignedString != null) {
        saml2.isResponseSigned = Boolean.parseBoolean(isResponseSignedString);
    } else {
        LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_RESPONSE_SIGNING
                + " not configured. Defaulting to \'false\'");
        saml2.isResponseSigned = false;
    }

    if (saml2.isResponseSigned()) {
        String signatureValidatorImplClass = properties
                .getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.SIGNATURE_VALIDATOR);
        if (signatureValidatorImplClass != null) {
            saml2.signatureValidatorImplClass = signatureValidatorImplClass;
        } else {
            LOGGER.log(Level.FINE,
                    SSOAgentConstants.SSOAgentConfig.SAML2.SIGNATURE_VALIDATOR + " not configured.");
        }
    }

    String isRequestSignedString = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_REQUEST_SIGNING);
    if (isRequestSignedString != null) {
        saml2.isRequestSigned = Boolean.parseBoolean(isRequestSignedString);
    } else {
        LOGGER.log(Level.FINE, SSOAgentConstants.SSOAgentConfig.SAML2.ENABLE_REQUEST_SIGNING
                + " not configured. Defaulting to \'false\'");
        saml2.isRequestSigned = false;
    }

    String isPassiveAuthnString = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.IS_PASSIVE_AUTHN);
    if (isPassiveAuthnString != null) {
        saml2.isPassiveAuthn = Boolean.parseBoolean(isPassiveAuthnString);
    } else {
        LOGGER.log(Level.FINE, "\'" + SSOAgentConstants.SSOAgentConfig.SAML2.IS_PASSIVE_AUTHN
                + "\' not configured. Defaulting to \'false\'");
        saml2.isPassiveAuthn = false;
    }

    String isForceAuthnString = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.IS_FORCE_AUTHN);
    if (isForceAuthnString != null) {
        saml2.isForceAuthn = Boolean.parseBoolean(isForceAuthnString);
    } else {
        LOGGER.log(Level.FINE, "\'" + SSOAgentConstants.SSOAgentConfig.SAML2.IS_FORCE_AUTHN
                + "\' not configured. Defaulting to \'false\'");
        saml2.isForceAuthn = false;
    }

    saml2.relayState = properties.getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.RELAY_STATE);
    saml2.postBindingRequestHTMLPayload = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.SAML2.POST_BINDING_REQUEST_HTML_PAYLOAD);

    oauth2.tokenURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.OAuth2.TOKEN_URL);
    oauth2.clientId = properties.getProperty(SSOAgentConstants.SSOAgentConfig.OAuth2.CLIENT_ID);
    oauth2.clientSecret = properties.getProperty(SSOAgentConstants.SSOAgentConfig.OAuth2.CLIENT_SECRET);

    openId.providerURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.OpenID.PROVIDER_URL);
    openId.returnToURL = properties.getProperty(SSOAgentConstants.SSOAgentConfig.OpenID.RETURN_TO_URL);

    String isAttributeExchangeEnabledString = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.OpenID.ENABLE_ATTRIBUTE_EXCHANGE);
    if (isAttributeExchangeEnabledString != null) {
        openId.isAttributeExchangeEnabled = Boolean.parseBoolean(isAttributeExchangeEnabledString);
    } else {
        LOGGER.log(Level.FINE, "\'" + SSOAgentConstants.SSOAgentConfig.OpenID.ENABLE_ATTRIBUTE_EXCHANGE
                + "\' not configured. Defaulting to \'true\'");
        openId.isAttributeExchangeEnabled = true;
    }

    String isDumbModeEnabledString = properties
            .getProperty(SSOAgentConstants.SSOAgentConfig.OpenID.ENABLE_DUMB_MODE);
    if (isAttributeExchangeEnabledString != null) {
        openId.isDumbModeEnabled = Boolean.parseBoolean(isDumbModeEnabledString);
    } else {
        LOGGER.log(Level.FINE, "\'" + SSOAgentConstants.SSOAgentConfig.OpenID.ENABLE_DUMB_MODE
                + "\' not configured. Defaulting to \'false\'");
        openId.isDumbModeEnabled = false;
    }
    if (properties.getProperty("KeyStore") != null) {
        try {
            keyStoreStream = new FileInputStream(properties.getProperty("KeyStore"));
        } catch (FileNotFoundException e) {
            throw new SSOAgentException("Cannot find file " + properties.getProperty("KeyStore"), e);
        }
    }
    keyStorePassword = properties.getProperty("KeyStorePassword");

    SSLContext sc;
    try {
        // Get SSL context
        sc = SSLContext.getInstance("SSL");
        doHostNameVerification();
        TrustManager[] trustManagers = doSSLVerification();

        sc.init(null, trustManagers, new java.security.SecureRandom());
        SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);

    } catch (Exception e) {
        throw new SSOAgentException("An error in initializing SSL Context");
    }
}

From source file:hudson.cli.CLI.java

public static int _main(String[] _args) throws Exception {
    List<String> args = Arrays.asList(_args);
    PrivateKeyProvider provider = new PrivateKeyProvider();
    boolean sshAuthRequestedExplicitly = false;
    String httpProxy = null;/*from  w  w  w.ja  va 2 s .c  o m*/

    String url = System.getenv("JENKINS_URL");

    if (url == null)
        url = System.getenv("HUDSON_URL");

    boolean tryLoadPKey = true;

    Mode mode = null;

    String user = null;
    String auth = null;

    String userIdEnv = System.getenv("JENKINS_USER_ID");
    String tokenEnv = System.getenv("JENKINS_API_TOKEN");

    boolean strictHostKey = false;

    while (!args.isEmpty()) {
        String head = args.get(0);
        if (head.equals("-version")) {
            System.out.println("Version: " + computeVersion());
            return 0;
        }
        if (head.equals("-http")) {
            if (mode != null) {
                printUsage("-http clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.HTTP;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-ssh")) {
            if (mode != null) {
                printUsage("-ssh clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.SSH;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-remoting")) {
            if (mode != null) {
                printUsage("-remoting clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.REMOTING;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-s") && args.size() >= 2) {
            url = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-noCertificateCheck")) {
            LOGGER.info("Skipping HTTPS certificate checks altogether. Note that this is not secure at all.");
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
            // bypass host name check, too.
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-noKeyAuth")) {
            tryLoadPKey = false;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-i") && args.size() >= 2) {
            File f = new File(args.get(1));
            if (!f.exists()) {
                printUsage(Messages.CLI_NoSuchFileExists(f));
                return -1;
            }

            provider.readFrom(f);

            args = args.subList(2, args.size());
            sshAuthRequestedExplicitly = true;
            continue;
        }
        if (head.equals("-strictHostKey")) {
            strictHostKey = true;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-user") && args.size() >= 2) {
            user = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-auth") && args.size() >= 2) {
            auth = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-p") && args.size() >= 2) {
            httpProxy = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-logger") && args.size() >= 2) {
            Level level = parse(args.get(1));
            for (Handler h : Logger.getLogger("").getHandlers()) {
                h.setLevel(level);
            }
            for (Logger logger : new Logger[] { LOGGER, FullDuplexHttpStream.LOGGER, PlainCLIProtocol.LOGGER,
                    Logger.getLogger("org.apache.sshd") }) { // perhaps also Channel
                logger.setLevel(level);
            }
            args = args.subList(2, args.size());
            continue;
        }
        break;
    }

    if (url == null) {
        printUsage(Messages.CLI_NoURL());
        return -1;
    }

    if (auth == null) {
        // -auth option not set
        if (StringUtils.isNotBlank(userIdEnv) && StringUtils.isNotBlank(tokenEnv)) {
            auth = StringUtils.defaultString(userIdEnv).concat(":").concat(StringUtils.defaultString(tokenEnv));
        } else if (StringUtils.isNotBlank(userIdEnv) || StringUtils.isNotBlank(tokenEnv)) {
            printUsage(Messages.CLI_BadAuth());
            return -1;
        } // Otherwise, none credentials were set

    }

    if (!url.endsWith("/")) {
        url += '/';
    }

    if (args.isEmpty())
        args = Arrays.asList("help"); // default to help

    if (tryLoadPKey && !provider.hasKeys())
        provider.readFromDefaultLocations();

    if (mode == null) {
        mode = Mode.HTTP;
    }

    LOGGER.log(FINE, "using connection mode {0}", mode);

    if (user != null && auth != null) {
        LOGGER.warning("-user and -auth are mutually exclusive");
    }

    if (mode == Mode.SSH) {
        if (user == null) {
            // TODO SshCliAuthenticator already autodetects the user based on public key; why cannot AsynchronousCommand.getCurrentUser do the same?
            LOGGER.warning("-user required when using -ssh");
            return -1;
        }
        return SSHCLI.sshConnection(url, user, args, provider, strictHostKey);
    }

    if (strictHostKey) {
        LOGGER.warning("-strictHostKey meaningful only with -ssh");
    }

    if (user != null) {
        LOGGER.warning("Warning: -user ignored unless using -ssh");
    }

    CLIConnectionFactory factory = new CLIConnectionFactory().url(url).httpsProxyTunnel(httpProxy);
    String userInfo = new URL(url).getUserInfo();
    if (userInfo != null) {
        factory = factory.basicAuth(userInfo);
    } else if (auth != null) {
        factory = factory.basicAuth(
                auth.startsWith("@") ? FileUtils.readFileToString(new File(auth.substring(1))).trim() : auth);
    }

    if (mode == Mode.HTTP) {
        return plainHttpConnection(url, args, factory);
    }

    CLI cli = factory.connect();
    try {
        if (provider.hasKeys()) {
            try {
                // TODO: server verification
                cli.authenticate(provider.getKeys());
            } catch (IllegalStateException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (UnsupportedOperationException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (GeneralSecurityException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.log(WARNING, null, e);
                    return -1;
                }
                LOGGER.warning("Failed to authenticate with your SSH keys. Proceeding as anonymous");
                LOGGER.log(FINE, null, e);
            }
        }

        // execute the command
        // Arrays.asList is not serializable --- see 6835580
        args = new ArrayList<String>(args);
        return cli.execute(args, System.in, System.out, System.err);
    } finally {
        cli.close();
    }
}

From source file:ca.spencerelliott.mercury.Changesets.java

private synchronized void startThread() {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    //Create the thread that will process the incoming feed
    load_thread = new Thread() {
        @Override//  w w  w .j a  v  a 2s. c o m
        public void run() {
            changesets_list.clear();

            DatabaseHelper db_helper = DatabaseHelper.getInstance(getApplicationContext());
            EncryptionHelper encrypt_helper = EncryptionHelper.getInstance("DEADBEEF".toCharArray(),
                    new byte[] { 'L', 'O', 'L' });

            //Get the repository information from the local database
            Beans.RepositoryBean repo_type = db_helper.getRepository(repo_id, encrypt_helper);
            AtomHandler feed_handler = null;

            //Detect the type of repository and create a parser based on that
            switch (repo_type.getType()) {
            case Mercury.RepositoryTypes.HGSERVE:
                feed_handler = new HGWebAtomHandler();
                break;
            case Mercury.RepositoryTypes.GOOGLECODE:
                feed_handler = new GoogleCodeAtomHandler();
                break;
            case Mercury.RepositoryTypes.BITBUCKET:
                feed_handler = new BitbucketAtomHandler();
                break;
            case Mercury.RepositoryTypes.CODEPLEX:
                feed_handler = new CodePlexAtomHandler();
                break;
            }

            HttpURLConnection conn = null;
            boolean connected = false;

            try {
                // XXX We need to use our own factory to make all ssl certs work
                HttpsURLConnection.setDefaultSSLSocketFactory(NaiveSSLSocketFactory.getSocketFactory());

                String repo_url_string = (repo_type.getUrl().endsWith("/") || repo_type.getUrl().endsWith("\\")
                        ? feed_handler
                                .formatURL(repo_type.getUrl().substring(0, repo_type.getUrl().length() - 1))
                        : feed_handler.formatURL(repo_type.getUrl()));

                switch (repo_type.getType()) {
                case Mercury.RepositoryTypes.BITBUCKET:
                    //Only add the token if the user requested it
                    if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.TOKEN)
                        repo_url_string = repo_url_string + "?token=" + repo_type.getSSHKey();
                    break;
                }

                URL repo_url = new URL(repo_url_string);
                conn = (HttpURLConnection) repo_url.openConnection();

                //Check to see if the user enabled HTTP authentication
                if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.HTTP) {
                    //Get their username and password
                    byte[] decrypted_info = (repo_type.getUsername() + ":" + repo_type.getPassword())
                            .getBytes();

                    //Add the header to the http request
                    conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBytes(decrypted_info));
                }
                conn.connect();
                connected = true;
            } catch (ClientProtocolException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("There was a problem with the HTTP protocol");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (IOException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("Server did not respond with a valid HTTP response");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (NullPointerException e3) {

            } catch (Exception e) {

            }

            BufferedReader reader = null;

            //Create a new reader based on the information retrieved
            if (connected) {
                try {
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                } catch (IllegalStateException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Make sure both the feed handler and info loaded from the web are not null
            if (reader != null && feed_handler != null) {
                try {
                    Xml.parse(reader, feed_handler);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Stored beans in the devices database
            ArrayList<Beans.ChangesetBean> stored_beans = null;

            if (prefs.getBoolean("caching", false)) {
                long last_insert = db_helper.getHighestID(DatabaseHelper.DB_TABLE_CHANGESETS, repo_id);

                if (last_insert >= 0) {
                    //Get all of the stored changesets
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                    String rev_id = "";

                    //Try to find the revision id of the bean that has the id of the last inserted value
                    for (Beans.ChangesetBean b : stored_beans) {
                        if (b.getID() == last_insert) {
                            rev_id = b.getRevisionID();
                            break;
                        }
                    }

                    //Trim the list starting from this revision
                    feed_handler.trimStartingFromRevision(rev_id);
                }
            }

            //Create a new bundle for the progress
            Bundle progress_bundle = new Bundle();

            //Retreive all the beans from the handler
            ArrayList<Beans.ChangesetBean> beans = feed_handler.getAllChangesets();
            int bean_count = beans.size();

            //Store the amount of changesets
            progress_bundle.putInt("max", bean_count);

            //Create a new message and store the bundle and what type of message it is
            Message msg = new Message();
            msg.setData(progress_bundle);
            msg.what = SETUP_COUNT;
            list_handler.sendMessage(msg);

            //Add each of the beans to the list
            for (int i = 0; i < bean_count; i++) {
                String commit_text = beans.get(i).getTitle();
                Date commit_date = new Date(beans.get(i).getUpdated());
                changesets_list.add(createChangeset(
                        (commit_text.length() > 30 ? commit_text.substring(0, 30) + "..." : commit_text),
                        beans.get(i).getRevisionID() + " - " + commit_date.toLocaleString()));

                //Store the current progress of the changeset loading
                progress_bundle.putInt("progress", i);

                //Reuse the old message and send an update progress message
                msg = new Message();
                msg.setData(progress_bundle);
                msg.what = UPDATE_PROGRESS;
                list_handler.sendMessage(msg);
            }

            //Get the current count of changesets and the shared preferences
            long changeset_count = db_helper.getChangesetCount(repo_id);

            if (prefs.getBoolean("caching", false)) {
                //Get all of the stored beans from the device if not already done
                if (stored_beans == null)
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                //Add all the changesets from the device
                for (Beans.ChangesetBean b : stored_beans) {
                    changesets_list.add(createChangeset(
                            (b.getTitle().length() > 30 ? (b.getTitle().substring(0, 30)) + "..."
                                    : b.getTitle()),
                            b.getRevisionID() + " - " + new Date(b.getUpdated()).toLocaleString()));
                }

                //Reverse the list so the oldest changesets are stored first
                Collections.reverse(beans);

                //Iterate through each bean and add it to the device's database
                for (Beans.ChangesetBean b : beans) {
                    db_helper.insert(b, repo_id);
                }

                //Get the amount of changesets allowed to be stored on the device
                int max_changes = Integer.parseInt(prefs.getString("max_changesets", "-1"));

                //Delete the oldest changesets if too many have been stored
                if (changeset_count > max_changes) {
                    db_helper.deleteNumChangesets(repo_id, (changeset_count - max_changes));
                }
            } else if (changeset_count > 0) {
                //Since the user does not have caching enabled, delete the changesets
                db_helper.deleteAllChangesets(repo_id);
            }

            //Update the tables to the newest revision
            if (!beans.isEmpty())
                db_helper.updateLastRev(repo_id, beans.get(0).getRevisionID());

            //Add all of the data to the changeset list
            changesets_data.addAll(beans);

            if (prefs.getBoolean("caching", false))
                changesets_data.addAll(stored_beans);

            //Clean up the sql connection
            db_helper.cleanup();
            db_helper = null;

            //Notify the handler that the loading of the list was successful
            list_handler.sendEmptyMessage(SUCCESSFUL);
        }
    };

    //Start the thread
    load_thread.start();
}

From source file:org.broad.igv.util.HttpUtils.java

/**
 * Code for disabling SSL certification//  w w w . j a v  a  2  s  . c  o m
 */
private void disableCertificateValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[0];
        }

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

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

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (NoSuchAlgorithmException e) {
    } catch (KeyManagementException e) {
    }

}

From source file:org.sharegov.cirm.StartUp.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 .  java  2  s  . c  o  m*/

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

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("Check server trusted");

        }
    } };

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            // TODO Auto-generated method stub
            return true;
        }
    };

    // Install the all-trusting trust manager
    try {
        // SSLContext sc = SSLContext.getInstance("SSL");
        // sc.init(null, trustAllCerts, new SecureRandom());
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        // see:http://stackoverflow.com/questions/1828775/how-to-handle-invalid-ssl-certificates-with-apache-httpclient
        // see:https://code.google.com/p/jsslutils/wiki/ApacheHttpClientUsage
        org.apache.commons.httpclient.protocol.Protocol.registerProtocol("https",
                new org.apache.commons.httpclient.protocol.Protocol("https",
                        (ProtocolSocketFactory) new SslContextedSecureProtocolSocketFactory(ctx, false), 443));
        SSLContext.setDefault(ctx);
    } catch (Exception e) {
    }
}

From source file:de.unidue.stud.sehawagn.oidcclient.SimpleOIDCClient.java

public static void trustEverybody(HttpsURLConnection connection) {
    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }/* w w w  . ja  va2s.  com*/
    };

    // Install the all-trusting trust manager and host name verifier
    SSLContext sc = getTrustEverybodySSLContext();

    if (connection == null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } else {
        connection.setSSLSocketFactory(sc.getSocketFactory());
        connection.setHostnameVerifier(allHostsValid);
    }
}

From source file:org.ejbca.core.ejb.ocsp.OcspKeyRenewalSessionBean.java

/** @return the EJBCA WS object. */
private EjbcaWS getEjbcaWS() {
    String webUrl = OcspConfiguration.getEjbcawsracliUrl();
    if (StringUtils.isEmpty(webUrl)) {
        // Automatic renewal is not enabled
        if (log.isDebugEnabled()) {
            log.debug("Automatic OCSP key/certificate renewal is not enabled, "
                    + OcspConfiguration.REKEYING_WSURL + " is empty.");
        }//  ww  w  .j av  a 2  s. co  m
        return null;
    }
    final SSLSocketFactory sslSocketFactory = getSSLSocketFactory();
    if (sslSocketFactory == null) {
        log.warn("No AuthenticationKeyBinding is configured. Unable to authenticate to EJBCA WebService.");
        return null;
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
    final URL ws_url;
    try {
        ws_url = new URL(webUrl + "?wsdl");
    } catch (MalformedURLException e) {
        log.warn("Problem with URL: '" + webUrl + "'", e);
        return null;
    }
    final QName qname = new QName("http://ws.protocol.core.ejbca.org/", "EjbcaWSService");
    if (log.isDebugEnabled()) {
        log.debug("web service. URL: " + ws_url + " QName: " + qname);
    }
    return new EjbcaWSService(ws_url, qname).getEjbcaWSPort();
}

From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java

private static void trustAllHosts() {

    X509TrustManager easyTrustManager = new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }/*from w  w  w  . j  ava 2s  . co m*/

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub

        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub

        }

    };

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { easyTrustManager };

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

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

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

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

From source file:org.apache.geode.management.internal.cli.commands.ConnectCommand.java

private void configureHttpsURLConnection(SSLConfig sslConfig, boolean skipSslVerification) throws Exception {
    KeyManager[] keyManagers = getKeyManagers(sslConfig);
    TrustManager[] trustManagers = getTrustManagers(sslConfig, skipSslVerification);

    if (skipSslVerification) {
        HttpsURLConnection.setDefaultHostnameVerifier((String s, SSLSession sslSession) -> true);
    }//www  .j av a  2s .co m

    SSLContext ssl = SSLContext.getInstance(SSLUtil.getSSLAlgo(SSLUtil.readArray(sslConfig.getProtocols())));

    ssl.init(keyManagers, trustManagers, new SecureRandom());

    HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
}

From source file:org.accada.epcis.repository.query.QuerySubscription.java

/**
 * Retrieves an "all-trusting" HTTP URL connection object, by disabling the
 * validation of certificates and overriding the default trust manager with
 * one that trusts all certificates.//from   www  .  ja v a 2  s .  com
 * 
 * @param url
 *            The URL on which a connection will be opened.
 * @return A HttpURLConnection connection object.
 * @throws IOException
 *             If an I/O error occurred.
 */
private HttpURLConnection getAllTrustingConnection(URL url) throws IOException {
    // 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) {
        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        LOG.error("Unable to install the all-trusting trust manager", e);
    }
    return getConnection(url);
}