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:com.intuit.karate.ScriptContext.java

public void buildClient() {
    ClientBuilder clientBuilder = ClientBuilder.newBuilder().register(new LoggingFilter()) // must be first
            .register(MultiPartFeature.class).register(new RequestFilter());
    if (sslEnabled) {
        logger.info("ssl enabled, initializing generic trusted certificate / key-store with algorithm: {}",
                sslAlgorithm);/*from w  ww .  j a  va 2s .  c  om*/
        SSLContext ssl = SslUtils.getSslContext(sslAlgorithm);
        HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
        clientBuilder.sslContext(ssl);
        clientBuilder.hostnameVerifier((host, session) -> true);
    }
    client = clientBuilder.build();
    if (connectTimeout != -1) {
        client.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout);
    }
    if (readTimeout != -1) {
        client.property(ClientProperties.READ_TIMEOUT, readTimeout);
    }
    if (proxyUri != null) {
        client.property(ClientProperties.PROXY_URI, proxyUri);
    }
    if (proxyUsername != null) {
        client.property(ClientProperties.PROXY_USERNAME, proxyUsername);
    }
    if (proxyPassword != null) {
        client.property(ClientProperties.PROXY_PASSWORD, proxyPassword);
    }
}

From source file:hudson.remoting.Launcher.java

/**
 * Bypass HTTPS security check by using free-for-all trust manager.
 *
 * @param _// w w w .j ava  2 s .c om
 *      This is ignored.
 */
@Option(name = "-noCertificateCheck")
public void setNoCertificateCheck(boolean _) throws NoSuchAlgorithmException, KeyManagementException {
    System.out.println("Skipping HTTPS certificate checks altoghether. Note that this is not secure at all.");
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    // bypass host name check, too.
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
}

From source file:it.infn.ct.downtime.Downtime.java

@Override
protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    try {//from  w w  w . j av a 2s .co m
        PortletPreferences portletPreferences = (PortletPreferences) request.getPreferences();

        response.setContentType("text/html");

        PortletRequestDispatcher dispatcher = null;
        String[] downtime_endpoints = new String[15];

        String downtime_REFRESH = portletPreferences.getValue("downtime_REFRESH", "1440000");
        String downtime_LOGLEVEL = portletPreferences.getValue("downtime_LOGLEVEL", "INFO");
        downtime_endpoints = portletPreferences.getValues("downtime_endpoints", new String[15]);
        String downtime_IDs = portletPreferences.getValue("downtime_IDs", "-1");
        String SMTP_HOST = portletPreferences.getValue("SMTP_HOST", "N/A");
        String SENDER_MAIL = portletPreferences.getValue("SENDER_MAIL", "N/A");

        File df_full = new File("/tmp/full_report.xml");
        File df = null;
        BufferedReader bufReader = null;
        String endpoints = "";
        boolean flag = false;

        // Create a file containing all the downtimes.
        FileWriter fileWritter = new FileWriter(df_full, false);
        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);

        String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        String results_tag_start = "<results>";
        String results_tag_end = "</results>";

        bufferWritter.write(header + "\n");
        bufferWritter.write(results_tag_start + "\n");

        for (int i = 0; i < downtime_endpoints.length; i++) {
            if (downtime_endpoints[i] != null && !downtime_endpoints[i].isEmpty()) {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());

                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

                String downtime_url = "https://goc.egi.eu/gocdbpi/public/"
                        + "?method=get_downtime_nested_services" + "&topentity=" + downtime_endpoints[i]
                        + "&page=1&ongoing_only=yes";

                log.info("GOC-DB endpoint: " + downtime_url);

                // Get the list of ongoing downtime
                URL url = new URL(downtime_url);
                try {
                    df = File.createTempFile("result_", ".xml");

                    org.apache.commons.io.FileUtils.copyURLToFile(url, df);
                    log.info("File: " + df.getAbsolutePath());

                    // our XML file for this example
                    File xmlFile = new File(df.getAbsolutePath());
                    Reader fileReader = new FileReader(xmlFile);
                    bufReader = new BufferedReader(fileReader);

                    StringBuilder sb = new StringBuilder();
                    // Skip the first 2 rows
                    bufReader.readLine();
                    bufReader.readLine();

                    String line = bufReader.readLine();
                    while (line != null) {
                        if ((!line.contains("results")))
                            sb.append(line).append("\n");

                        line = bufReader.readLine();
                    }

                    String xml2String = sb.toString();
                    if (xml2String != null && !xml2String.isEmpty()) {
                        log.info("XML to String using BufferedReader: ");
                        log.info(xml2String);

                        bufferWritter.write(xml2String);

                        flag = true;
                    }

                    bufReader.close();
                    df.deleteOnExit();

                } catch (IOException ex) {
                    log.error(ex);
                } finally {
                    df.delete();
                }
            }
        }

        bufferWritter.write(results_tag_end + "\n");
        bufferWritter.close();

        boolean sending = false;
        if (flag) {
            //request.setAttribute("downtime_IDs", getIDs(df_full));

            // Store the new IDs in the portlet preferences
            if (downtime_IDs.equals("-1")) {
                portletPreferences.setValue("downtime_IDs", getIDs(df_full));
                sending = true; // enable the notification
            } else {
                String[] array1 = getIDs(df_full).split(",");
                String[] array2 = downtime_IDs.trim().split(",");

                log.info("XML = " + Arrays.toString(array1));
                log.info("Preferences = " + Arrays.toString(array2));

                String ids = "";
                String[] list = getIntersection(array1, array2);
                for (String id : list)
                    ids += id + ",";

                // Check if we need to add new IDs and remove old ones
                for (int i1 = 0; i1 < array1.length; i1++) {
                    if (!ids.contains(array1[i1])) {
                        ids += array1[i1] + ",";
                        sending = true; // enable the notification
                    }
                }

                List<String> listwithduplicate = new ArrayList<String>(Arrays.asList(ids));

                Set<String> s = new LinkedHashSet<String>(listwithduplicate);
                //log.info("ids(after)= " + s);

                log.info("Preferences to store = " + ids.substring(0, ids.length() - 1));
                portletPreferences.setValue("downtime_IDs", ids.substring(0, ids.length() - 1));
            }

            // Get list of users in Liferay
            int countUser = UserLocalServiceUtil.getUsersCount();
            List<User> users = UserLocalServiceUtil.getUsers(0, countUser);
            for (User liferay_user : users) {
                /*log.info("UserID = " + liferay_user.getUserId() 
                + " UserCompanyID = " + liferay_user.getCompanyId() 
                + " UserEmail = " + liferay_user.getEmailAddress() 
                + " UserScreenName = " + liferay_user.getScreenName());*/

                if (sending) {
                    if ((SMTP_HOST == null) || (SMTP_HOST.trim().equals("")) || (SMTP_HOST.trim().equals("N/A"))
                            || (SENDER_MAIL == null) || (SENDER_MAIL.trim().equals(""))
                            || (SENDER_MAIL.trim().equals("N/A")))
                        log.info("\nThe Notification Service is not properly configured!!");

                    else {
                        log.info("\nSending notification to the user [ OK ]");
                        sendHTMLEmail(liferay_user.getEmailAddress(), SENDER_MAIL, SMTP_HOST, df_full);
                    }
                }
            }
        } else {
            // Recover original setting.
            portletPreferences.setValue("downtime_IDs", "-1");
        }

        // Save the portlet preferences
        request.setAttribute("downtime_REFRESH", downtime_REFRESH.trim());
        request.setAttribute("downtime_LOGLEVEL", downtime_LOGLEVEL.trim());
        request.setAttribute("downtime_endpoints", endpoints);
        request.setAttribute("SMTP_HOST", SMTP_HOST.trim());
        request.setAttribute("SENDER_MAIL", SENDER_MAIL.trim());
        request.setAttribute("DOWNTIME_XML", df_full.toString().trim());

        // Storing the preferences
        portletPreferences.store();

        dispatcher = getPortletContext().getRequestDispatcher("/view.jsp");
        dispatcher.include(request, response);

    } catch (SystemException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Downtime.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

/**
 * <pre>/*from ww w. j a v a2 s.  com*/
 *  ? ??   HTTPS   HandShake Exception ? ??  Exception? ? ?
 * RHEV Manager(host) ? SSL ??  ?   ? ?? ?.
 * </pre>
 * @throws Exception
 */
public void init() throws Exception {
    // http://javaresolutions.blogspot.kr/2014/07/javaxnetsslsslprotocolexception.html
    // -Djsse.enableSNIExtension=false
    // System.setProperty("jsse.enableSNIExtension", "false");

    System.setProperty("jsse.enableSNIExtension", "false");

    // Create a hostname verifier that does not validate hostname
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            /*
            if (hostname.equals(host)) {
            return true;
            }
                    
            return false;
            */
            return true;
        }
    });

    // Create a trust manager that does not validate certificate chains
    // Refer to https://code.google.com/p/misc-utils/wiki/JavaHttpsUrl
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // nothing to do.
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // nothing to do.
        }

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

    try {
        // Install the all-trusting trust manager
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (KeyManagementException e) {
        logger.error("KeyManagementException has occurred.", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException has occurred.", e);
    }
}

From source file:org.apache.falcon.client.FalconClient.java

public static AuthenticatedURL.Token getToken(String baseUrl) throws FalconCLIException {
    AuthenticatedURL.Token currentToken = new AuthenticatedURL.Token();
    try {/*from   w  ww . j  ava2  s  .c  om*/
        URL url = new URL(baseUrl + AUTH_URL);
        // using KerberosAuthenticator which falls back to PsuedoAuthenticator
        // instead of passing authentication type from the command line - bad factory
        HttpsURLConnection.setDefaultSSLSocketFactory(getSslContext().getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(ALL_TRUSTING_HOSTNAME_VERIFIER);
        new AuthenticatedURL(AUTHENTICATOR).openConnection(url, currentToken);
    } catch (Exception ex) {
        throw new FalconCLIException("Could not authenticate, " + ex.getMessage(), ex);
    }

    return currentToken;
}

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

static EventSource openAsynch(WebTarget target, String auth) {
    target.request(MediaType.APPLICATION_JSON_TYPE).header("Authorization", auth);
    EventSource eventSource = new EventSource(target, false);
    HttpsURLConnection.setDefaultSSLSocketFactory(RunFromSrfBuilder._factory);
    new OpenThread(eventSource).start();
    return eventSource;
}

From source file:com.jaspersoft.jrx.query.JRXPathQueryExecuter.java

private Document getDocumentFromUrl(Map<String, ? extends JRValueParameter> parametersMap) throws Exception {
    // Get the url...
    String urlString = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_URL);

    // add GET parameters to the urlString...
    Iterator<String> i = parametersMap.keySet().iterator();

    String div = "?";
    URL url = new URL(urlString);
    if (url.getQuery() != null)
        div = "&";

    while (i.hasNext()) {
        String keyName = "" + i.next();
        if (keyName.startsWith("XML_GET_PARAM_")) {
            String paramName = keyName.substring("XML_GET_PARAM_".length());
            String value = (String) getParameterValue(keyName);

            urlString += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
            div = "&";
        }//www.  j a  va 2 s .  co  m
    }

    url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("file")) {
        // do nothing
        return JRXmlUtils.parse(url.openStream());
    } else if (url.getProtocol().toLowerCase().equals("http")
            || url.getProtocol().toLowerCase().equals("https")) {
        String username = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_USERNAME);
        String password = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_PASSWORD);

        if (url.getProtocol().toLowerCase().equals("https")) {
            JRPropertiesUtil dPROP = PropertiesHelper.DPROP;
            String socketFactory = dPROP
                    .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultSSLSocketFactory");
            if (socketFactory == null) {
                socketFactory = dPROP.getProperty(
                        "net.sf.jasperreports.query.executer.factory.XPath.DefaultSSLSocketFactory");
            }

            if (socketFactory != null) {
                // setSSLSocketFactory
                HttpsURLConnection.setDefaultSSLSocketFactory(
                        (SSLSocketFactory) Class.forName(socketFactory).newInstance());
            } else {
                log.debug("No SSLSocketFactory defined, using default");
            }

            String hostnameVerifyer = dPROP
                    .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultHostnameVerifier");
            if (hostnameVerifyer == null) {
                hostnameVerifyer = dPROP.getProperty(
                        "net.sf.jasperreports.query.executer.factory.XPath.DefaultHostnameVerifier");
            }

            if (hostnameVerifyer != null) {
                // setSSLSocketFactory
                HttpsURLConnection.setDefaultHostnameVerifier(
                        (HostnameVerifier) Class.forName(hostnameVerifyer).newInstance());
            } else {
                log.debug("No HostnameVerifier defined, using default");
            }
        }

        URLConnection conn = url.openConnection();

        if (username != null && username.length() > 0 && password != null) {
            ByteArrayInputStream bytesIn = new ByteArrayInputStream((username + ":" + password).getBytes());
            ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
            Base64Encoder enc = new Base64Encoder(bytesIn, dataOut);
            enc.process();
            String encoding = dataOut.toString();
            conn.setRequestProperty("Authorization", "Basic " + encoding);
        }

        // add POST parameters to the urlString...
        i = parametersMap.keySet().iterator();

        String data = "";
        div = "";
        while (i.hasNext()) {
            String keyName = "" + i.next();
            if (keyName.startsWith("XML_POST_PARAM_")) {
                String paramName = keyName.substring("XML_POST_PARAM_".length());
                String value = (String) getParameterValue(keyName);
                data += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
                div = "&";
            }
        }

        conn.setDoOutput(true);

        if (data.length() > 0) {
            conn.setDoInput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
        }

        try {
            return XMLUtils.parseNoValidation(conn.getInputStream());
        } catch (SAXException e) {
            throw new JRException("Failed to parse the xml document", e);
        } catch (IOException e) {
            throw new JRException("Failed to parse the xml document", e);
        } catch (ParserConfigurationException e) {
            throw new JRException("Failed to create a document builder factory", e);
        }

        // return JRXmlUtils.parse(conn.getInputStream());
    } else {
        throw new JRException("URL protocol not supported");
    }
}

From source file:org.jab.docsearch.spider.LinkFinder.java

/**
 * Method init/*from w  w  w  .  ja  va2  s  .c o  m*/
 */
private void init() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

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

From source file:org.hyperic.plugin.vrealize.automation.VRAUtils.java

public static String getWGet(String path) {
    String retValue = null;/*  ww w.j a  v  a 2 s .  c o  m*/
    try {
        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);
        URL url = new URL(path);
        URLConnection con;
        try {
            con = url.openConnection();
        } catch (Exception e) {
            log.debug("Couldnt connect to vRa API");
            return "";
        }

        Reader reader = new InputStreamReader(con.getInputStream());
        while (true) {
            int ch = reader.read();
            if (ch == -1) {
                break;
            }
            retValue += (char) ch;
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return retValue;
}

From source file:nl.armatiek.xslweb.configuration.Context.java

private void initProperties() throws Exception {
    File propsFile = new File(homeDir, "config" + File.separatorChar + Definitions.FILENAME_PROPERTIES);
    this.properties = XSLWebUtils.readProperties(propsFile);
    this.trustAllCerts = new Boolean(properties.getProperty(Definitions.PROPERTYNAME_TRUST_ALL_CERTS, "false"));
    if (trustAllCerts) {
        TrustManager[] trustAllCertsManager = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }/* w  ww.j  ava2s.  c  o  m*/

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

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCertsManager, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }
    this.parserHardening = new Boolean(
            this.properties.getProperty(Definitions.PROPERTYNAME_PARSER_HARDENING, "false"));
}