Example usage for javax.net.ssl SSLContext getSocketFactory

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

Introduction

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

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent event) {

    // request windows line breaks to make the files easier to edit (in particular the marshalled .xml files)
    System.setProperty("line.separator", "\r\n");

    // get a reference to the servlet context
    ServletContext servletContext = event.getServletContext();

    // set up logging
    try {//from  w ww  . j av  a2 s . c  o  m

        // set the log path
        System.setProperty("logPath", servletContext.getRealPath("/") + "/WEB-INF/logs/Rapid.log");

        // get a logger
        _logger = Logger.getLogger(RapidHttpServlet.class);

        // set the logger and store in servletConext
        servletContext.setAttribute("logger", _logger);

        // log!
        _logger.info("Logger created");

    } catch (Exception e) {

        System.err.println("Error initilising logging : " + e.getMessage());

        e.printStackTrace();
    }

    try {

        // we're looking for a password and salt for the encryption
        char[] password = null;
        byte[] salt = null;
        // look for the rapid.txt file with the saved password and salt
        File secretsFile = new File(servletContext.getRealPath("/") + "/WEB-INF/security/encryption.txt");
        // if it exists
        if (secretsFile.exists()) {
            // get a file reader
            BufferedReader br = new BufferedReader(new FileReader(secretsFile));
            // read the first line
            String className = br.readLine();
            // read the next line
            String s = br.readLine();
            // close the reader
            br.close();

            try {
                // get the class 
                Class classClass = Class.forName(className);
                // get the interfaces
                Class[] classInterfaces = classClass.getInterfaces();
                // assume it doesn't have the interface we want
                boolean gotInterface = false;
                // check we got some
                if (classInterfaces != null) {
                    for (Class classInterface : classInterfaces) {
                        if (com.rapid.utils.Encryption.EncryptionProvider.class.equals(classInterface)) {
                            gotInterface = true;
                            break;
                        }
                    }
                }
                // check the class extends com.rapid.Action
                if (gotInterface) {
                    // get the constructors
                    Constructor[] classConstructors = classClass.getDeclaredConstructors();
                    // check we got some
                    if (classConstructors != null) {
                        // assume we don't get the parameterless one we need
                        Constructor constructor = null;
                        // loop them
                        for (Constructor classConstructor : classConstructors) {
                            // check parameters
                            if (classConstructor.getParameterTypes().length == 0) {
                                constructor = classConstructor;
                                break;
                            }
                        }
                        // check we got what we want
                        if (constructor == null) {
                            _logger.error(
                                    "Encyption not initialised : Class in security.txt class must have a parameterless constructor");
                        } else {
                            // construct the class
                            EncryptionProvider encryptionProvider = (EncryptionProvider) constructor
                                    .newInstance();
                            // get the password
                            password = encryptionProvider.getPassword();
                            // get the salt
                            salt = encryptionProvider.getSalt();
                            // log
                            _logger.info("Encyption initialised");
                        }
                    }
                } else {
                    _logger.error(
                            "Encyption not initialised : Class in security.txt class must extend com.rapid.utils.Encryption.EncryptionProvider");
                }
            } catch (Exception ex) {
                _logger.error("Encyption not initialised : " + ex.getMessage(), ex);
            }
        } else {
            _logger.info("Encyption not initialised");
        }

        // create the encypted xml adapter (if the file above is not found there no encryption will occur)
        RapidHttpServlet.setEncryptedXmlAdapter(new EncryptedXmlAdapter(password, salt));

        // initialise the schema factory (we'll reuse it in the various loaders)
        _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        // initialise the list of classes we're going to want in the JAXB context (the loaders will start adding to it)
        _jaxbClasses = new ArrayList<Class>();

        _logger.info("Loading database drivers");

        // load the database drivers first
        loadDatabaseDrivers(servletContext);

        _logger.info("Loading connection adapters");

        // load the connection adapters 
        loadConnectionAdapters(servletContext);

        _logger.info("Loading security adapters");

        // load the security adapters 
        loadSecurityAdapters(servletContext);

        _logger.info("Loading form adapters");

        // load the form adapters
        loadFormAdapters(servletContext);

        _logger.info("Loading actions");

        // load the actions 
        loadActions(servletContext);

        _logger.info("Loading templates");

        // load templates
        loadThemes(servletContext);

        _logger.info("Loading controls");

        // load the controls 
        loadControls(servletContext);

        // add some classes manually
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.NameRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.EnumerationRestriction.class);
        _jaxbClasses.add(com.rapid.soa.Webservice.class);
        _jaxbClasses.add(com.rapid.soa.SQLWebservice.class);
        _jaxbClasses.add(com.rapid.soa.JavaWebservice.class);
        _jaxbClasses.add(com.rapid.core.Validation.class);
        _jaxbClasses.add(com.rapid.core.Action.class);
        _jaxbClasses.add(com.rapid.core.Event.class);
        _jaxbClasses.add(com.rapid.core.Style.class);
        _jaxbClasses.add(com.rapid.core.Control.class);
        _jaxbClasses.add(com.rapid.core.Page.class);
        _jaxbClasses.add(com.rapid.core.Application.class);
        _jaxbClasses.add(com.rapid.core.Device.class);
        _jaxbClasses.add(com.rapid.core.Device.Devices.class);

        // convert arraylist to array
        Class[] classes = _jaxbClasses.toArray(new Class[_jaxbClasses.size()]);
        // re-init the JAXB context to include our injectable classes               
        JAXBContext jaxbContext = JAXBContext.newInstance(classes);

        // this logs the JAXB classes
        _logger.trace("JAXB  content : " + jaxbContext.toString());

        // store the jaxb context in RapidHttpServlet
        RapidHttpServlet.setJAXBContext(jaxbContext);

        // load the devices
        Devices.load(servletContext);

        // load the applications!
        loadApplications(servletContext);

        // add some useful global objects 
        servletContext.setAttribute("xmlDateFormatter", new SimpleDateFormat("yyyy-MM-dd"));
        servletContext.setAttribute("xmlDateTimeFormatter", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

        String localDateFormat = servletContext.getInitParameter("localDateFormat");
        if (localDateFormat == null)
            localDateFormat = "dd/MM/yyyy";
        servletContext.setAttribute("localDateFormatter", new SimpleDateFormat(localDateFormat));

        String localDateTimeFormat = servletContext.getInitParameter("localDateTimeFormat");
        if (localDateTimeFormat == null)
            localDateTimeFormat = "dd/MM/yyyy HH:mm a";
        servletContext.setAttribute("localDateTimeFormatter", new SimpleDateFormat(localDateTimeFormat));

        boolean actionCache = Boolean.parseBoolean(servletContext.getInitParameter("actionCache"));
        if (actionCache)
            servletContext.setAttribute("actionCache", new ActionCache(servletContext));

        int pageAgeCheckInterval = MONITOR_CHECK_INTERVAL;
        try {
            String pageAgeCheckIntervalString = servletContext.getInitParameter("pageAgeCheckInterval");
            if (pageAgeCheckIntervalString != null)
                pageAgeCheckInterval = Integer.parseInt(pageAgeCheckIntervalString);
        } catch (Exception ex) {
            _logger.error("pageAgeCheckInterval is not an integer");
        }

        int pageMaxAge = MONITOR_MAX_AGE;
        try {
            String pageMaxAgeString = servletContext.getInitParameter("pageMaxAge");
            if (pageMaxAgeString != null)
                pageMaxAge = Integer.parseInt(pageMaxAgeString);
        } catch (Exception ex) {
            _logger.error("pageMaxAge is not an integer");
        }

        // start the monitor
        _monitor = new Monitor(servletContext, pageAgeCheckInterval, pageMaxAge);
        _monitor.start();

        // allow calling to https without checking certs (for now)
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new Https.TrustAllCerts() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    } catch (Exception ex) {

        _logger.error("Error loading applications : " + ex.getMessage());

        ex.printStackTrace();
    }

}

From source file:com.arm.connector.bridge.transport.HttpTransport.java

@SuppressWarnings("empty-statement")
private String doHTTP(String verb, String url_str, String username, String password, String data,
        String content_type, String auth_domain, boolean doInput, boolean doOutput, boolean doSSL,
        boolean use_api_token, String api_token) {
    String result = "";
    String line = "";
    URLConnection connection = null;
    SSLContext sc = null;

    try {//from w w  w.j  a va2s . c o m
        URL url = new URL(url_str);

        // Http Connection and verb
        if (doSSL) {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

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

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

            // Install the all-trusting trust manager
            try {
                sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                // do nothing
                ;
            }

            // open the SSL connction
            connection = (HttpsURLConnection) (url.openConnection());
            ((HttpsURLConnection) connection).setRequestMethod(verb);
            ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
            ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } else {
            connection = (HttpURLConnection) (url.openConnection());
            ((HttpURLConnection) connection).setRequestMethod(verb);
        }

        connection.setDoInput(doInput);
        if (doOutput && data != null && data.length() > 0) {
            connection.setDoOutput(doOutput);
        } else {
            connection.setDoOutput(false);
        }

        // enable basic auth if requested
        if (use_api_token == false && username != null && username.length() > 0 && password != null
                && password.length() > 0) {
            String encoding = Base64.encodeBase64String((username + ":" + password).getBytes());
            connection.setRequestProperty("Authorization", this.m_basic_auth_qualifier + " " + encoding);
            //this.errorLogger().info("Basic Authorization: " + username + ":" + password + ": " + encoding);
        }

        // enable ApiTokenAuth auth if requested
        if (use_api_token == true && api_token != null && api_token.length() > 0) {
            // use qualification for the authorization header...
            connection.setRequestProperty("Authorization", this.m_auth_qualifier + " " + api_token);
            //this.errorLogger().info("ApiTokenAuth Authorization: " + api_token);

            // Always reset to the established default
            this.resetAuthorizationQualifier();
        }

        // ETag support if requested
        if (this.m_etag_value != null && this.m_etag_value.length() > 0) {
            // set the ETag header value
            connection.setRequestProperty("ETag", this.m_etag_value);
            //this.errorLogger().info("ETag Value: " + this.m_etag_value);

            // Always reset to the established default
            this.resetETagValue();
        }

        // If-Match support if requested
        if (this.m_if_match_header_value != null && this.m_if_match_header_value.length() > 0) {
            // set the If-Match header value
            connection.setRequestProperty("If-Match", this.m_if_match_header_value);
            //this.errorLogger().info("If-Match Value: " + this.m_if_match_header_value);

            // Always reset to the established default
            this.resetIfMatchValue();
        }

        // specify content type if requested
        if (content_type != null && content_type.length() > 0) {
            connection.setRequestProperty("Content-Type", content_type);
            connection.setRequestProperty("Accept", "*/*");
        }

        // add Connection: keep-alive (does not work...)
        //connection.setRequestProperty("Connection", "keep-alive");

        // special gorp for HTTP DELETE
        if (verb != null && verb.equalsIgnoreCase("delete")) {
            connection.setRequestProperty("Access-Control-Allow-Methods", "OPTIONS, DELETE");
        }

        // specify domain if requested
        if (auth_domain != null && auth_domain.length() > 0) {
            connection.setRequestProperty("Domain", auth_domain);
        }

        // DEBUG dump the headers
        //if (doSSL) 
        //    this.errorLogger().info("HTTP: Headers: " + ((HttpsURLConnection)connection).getRequestProperties()); 
        //else
        //    this.errorLogger().info("HTTP: Headers: " + ((HttpURLConnection)connection).getRequestProperties()); 

        // specify data if requested - assumes it properly escaped if necessary
        if (doOutput && data != null && data.length() > 0) {
            try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream())) {
                out.write(data);
            }
        }

        // setup the output if requested
        if (doInput) {
            try {
                try (InputStream content = (InputStream) connection.getInputStream();
                        BufferedReader in = new BufferedReader(new InputStreamReader(content))) {
                    while ((line = in.readLine()) != null) {
                        result += line;
                    }
                }
            } catch (java.io.FileNotFoundException ex) {
                this.errorLogger().info("HTTP(" + verb + ") empty response (OK).");
                result = "";
            }
        } else {
            // no result expected
            result = "";
        }

        // save off the HTTP response code...
        if (doSSL)
            this.saveResponseCode(((HttpsURLConnection) connection).getResponseCode());
        else
            this.saveResponseCode(((HttpURLConnection) connection).getResponseCode());

        // DEBUG
        //if (doSSL)
        //    this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpsURLConnection)connection).getResponseCode());
        //else
        //    this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpURLConnection)connection).getResponseCode());
    } catch (IOException ex) {
        this.errorLogger().warning("Caught Exception in doHTTP(" + verb + "): " + ex.getMessage());
        result = null;
    }

    // return the result
    return result;
}

From source file:iracing.webapi.IracingWebApi.java

private void installCerts() throws Exception {
    String host = "members.iracing.com";
    int port = 443;

    char[] password = CERT_STORE_PASSWORD.toCharArray();

    File file = new File("jssecacerts");
    if (!file.isFile()) {
        char seperator = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + seperator + "lib" + seperator + "security");
        file = new File(dir, "jssecacerts");
        if (!file.isFile()) {
            file = new File(dir, "cacerts");
        }//w  w w. jav  a2 s .c om
    }
    KeyStore ks;
    InputStream in = new FileInputStream(file);
    ks = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        ks.load(in, password);
    } catch (Exception e) {
    }
    in.close();

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory factory = context.getSocketFactory();

    SSLSocket socket = null;
    try {
        socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        socket.startHandshake();
    } catch (Exception e) {
        //e.printStackTrace();
    } finally {
        if (socket != null)
            socket.close();
    }

    X509Certificate[] chain = tm.chain;
    if (chain == null)
        return;

    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        X509Certificate cert = chain[i];
        sha1.update(cert.getEncoded());
        md5.update(cert.getEncoded());
    }

    for (int count = 0; count < chain.length; count++) {
        X509Certificate cert = chain[count];
        String alias = host + "-" + (count + 1);
        ks.setCertificateEntry(alias, cert);
        OutputStream out = new FileOutputStream("jssecacerts");
        try {
            ks.store(out, password);
        } finally {
            out.close();
        }
    }
}

From source file:org.archive.crawler.fetcher.OptimizeFetchHTTP.java

public void initialTasks() {
    super.initialTasks();
    this.getController().addCrawlStatusListener(this);
    //configureHttp();

    // load cookies from a file if specified in the order file.
    loadCookies();/*  ww  w  .  jav a 2  s  . c  o m*/

    // I tried to get the default KeyManagers but doesn't work unless you
    // point at a physical keystore. Passing null seems to do the right
    // thing so we'll go w/ that.
    try {
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null,
                new TrustManager[] { new ConfigurableX509TrustManager((String) getAttribute(ATTR_TRUST)) },
                null);
        this.sslfactory = context.getSocketFactory();
    } catch (Exception e) {
        logger.warn("Failed configure of ssl context " + e.getMessage(), e);
    }
}

From source file:org.gcaldaemon.core.Configurator.java

public Configurator(String configPath, Properties properties, boolean userHome, byte mode) throws Exception {
    this.mode = mode;
    int i;/*from  ww w .ja  v a2 s.  c  o  m*/
    File programRootDir = null;
    if (mode == MODE_EMBEDDED) {

        // Embedded mode
        standaloneMode = false;
        config = properties;
        String workPath = getConfigProperty(WORK_DIR, null);
        workDirectory = new File(workPath);
    } else {

        // Load config
        if (configPath != null) {
            configFile = new File(configPath);
        }
        InputStream in = null;
        boolean configInClassPath = false;
        if (configFile == null || !configFile.isFile()) {
            try {
                in = Configurator.class.getResourceAsStream("/gcal-daemon.cfg");
                configInClassPath = in != null;
            } catch (Exception ignored) {
                in = null;
            }
            if (in == null) {
                System.out.println("INFO  | Searching main configuration file...");
                String path = (new File("x")).getAbsolutePath().replace('\\', '/');
                i = path.lastIndexOf('/');
                if (i > 1) {
                    i = path.lastIndexOf('/', i - 1);
                    if (i > 1) {
                        configFile = new File(path.substring(0, i), "conf/gcal-daemon.cfg");
                    }
                }
                if (configFile == null || !configFile.isFile()) {
                    configFile = new File("/usr/local/sbin/GCALDaemon/conf/gcal-daemon.cfg");
                }
                if (configFile == null || !configFile.isFile()) {
                    configFile = new File("/GCALDaemon/conf/gcal-daemon.cfg");
                }
                if (configFile == null || !configFile.isFile()) {
                    File root = new File("/");
                    String[] dirs = root.list();
                    if (dirs != null) {
                        for (i = 0; i < dirs.length; i++) {
                            configFile = new File('/' + dirs[i] + "/GCALDaemon/conf/gcal-daemon.cfg");
                            if (configFile.isFile()) {
                                break;
                            }
                        }
                    }
                }
                if (configFile == null || !configFile.isFile()) {
                    throw new FileNotFoundException("Missing main configuration file: " + configPath);
                }
                if (!userHome) {

                    // Open global config file
                    in = new FileInputStream(configFile);
                }
            }
        } else {
            if (!userHome) {

                // Open global config file
                in = new FileInputStream(configFile);
            }
        }
        standaloneMode = !configInClassPath;
        if (in != null) {

            // Load global config file
            config.load(new BufferedInputStream(in));
            in.close();
        }

        // Loading config from classpath
        if (configFile == null) {
            try {
                URL url = Configurator.class.getResource("/gcal-daemon.cfg");
                configFile = new File(url.getFile());
            } catch (Exception ignored) {
            }
        }
        programRootDir = configFile.getParentFile().getParentFile();
        System.setProperty("gcaldaemon.program.dir", programRootDir.getAbsolutePath());
        String workPath = getConfigProperty(WORK_DIR, null);
        File directory;
        if (workPath == null) {
            directory = new File(programRootDir, "work");
        } else {
            directory = new File(workPath);
        }
        if (!directory.isDirectory()) {
            if (!directory.mkdirs()) {
                directory = new File("work");
                directory.mkdirs();
            }
        }
        workDirectory = directory;

        // User-specific config file handler
        if (userHome) {
            boolean useGlobal = true;
            try {
                String home = System.getProperty("user.home", null);
                if (home != null) {
                    File userConfig = new File(home, ".gcaldaemon/gcal-daemon.cfg");
                    if (!userConfig.isFile()) {

                        // Create new user-specific config
                        File userDir = new File(home, ".gcaldaemon");
                        userDir.mkdirs();
                        copyFile(configFile, userConfig);
                        if (!userConfig.isFile()) {
                            userConfig.delete();
                            userDir.delete();
                        }
                    }
                    if (userConfig.isFile()) {

                        // Load user-specific config
                        configFile = userConfig;
                        in = new FileInputStream(configFile);
                        config.load(new BufferedInputStream(in));
                        in.close();
                        useGlobal = false;
                    }
                }
            } catch (Exception ignored) {
            }
            if (useGlobal) {

                // Load global config file
                config.load(new BufferedInputStream(in));
                in.close();
            }
        }
    }

    // Init logger
    ProgressMonitor monitor = null;
    if (standaloneMode && mode != MODE_CONFIGEDITOR) {

        // Compute log config path
        String logConfig = getConfigProperty(LOG_CONFIG, "logger-config.cfg");
        logConfig = logConfig.replace('\\', '/');
        File logConfigFile;
        if (logConfig.indexOf('/') == -1) {
            logConfigFile = new File(programRootDir, "conf/" + logConfig);
        } else {
            logConfigFile = new File(logConfig);
        }
        if (logConfigFile.isFile()) {
            String logConfigPath = logConfigFile.getAbsolutePath();
            System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
            System.setProperty("log4j.defaultInitOverride", "false");
            System.setProperty("log4j.configuration", logConfigPath);
            try {
                PropertyConfigurator.configure(logConfigPath);
            } catch (Throwable ignored) {
            }
        }
    }
    if (mode == MODE_CONFIGEDITOR) {

        // Show monitor
        try {
            monitor = new ProgressMonitor();
            monitor.setVisible(true);
            Thread.sleep(400);
        } catch (Exception ignored) {
        }

        // Init simple logger
        try {
            System.setProperty("log4j.defaultInitOverride", "false");
            Logger root = Logger.getRootLogger();
            root.removeAllAppenders();
            root.addAppender(new ConsoleAppender(new SimpleLayout()));
            root.setLevel(Level.INFO);
        } catch (Throwable ingored) {
        }
    }

    // Disable unnecessary INFO messages of the GData API
    try {
        java.util.logging.Logger logger = java.util.logging.Logger.getLogger("com.google");
        logger.setLevel(java.util.logging.Level.WARNING);
    } catch (Throwable ingored) {
    }

    Log log = LogFactory.getLog(Configurator.class);
    log.info(VERSION + " starting...");
    if (configFile != null && log.isDebugEnabled()) {
        log.debug("Config loaded successfully (" + configFile + ").");
    }

    // Check Java version
    double jvmVersion = 1.5;
    try {
        jvmVersion = Float.valueOf(System.getProperty("java.version", "1.5").substring(0, 3)).floatValue();
    } catch (Exception ignored) {
    }
    if (jvmVersion < 1.5) {
        log.fatal("GCALDaemon requires at least Java 1.5! Current version: "
                + System.getProperty("java.version"));
        throw new Exception("Invalid JVM version!");
    }

    // Check permission
    if (workDirectory.isDirectory() && !workDirectory.canWrite()) {
        if (System.getProperty("os.name", "unknown").toLowerCase().indexOf("windows") == -1) {
            String path = workDirectory.getCanonicalPath();
            if (programRootDir != null) {
                path = programRootDir.getCanonicalPath();
            }
            log.warn("Please check the file permissions on the '" + workDirectory.getCanonicalPath()
                    + "' folder!\r\n" + "Hint: [sudo] chmod -R 777 " + path);
        }
    }

    // Disable all ICS file syntax validators
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_NOTES_COMPATIBILITY, true);

    // Disable SSL validation
    try {

        // Create a trust manager that does not validate certificate chains
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[] {
                new javax.net.ssl.X509TrustManager() {

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

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

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

        // Install the all-trusting trust manager
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Throwable ignored) {
    }

    // Replace hostname verifier
    try {
        javax.net.ssl.HostnameVerifier hv[] = new javax.net.ssl.HostnameVerifier[] {
                new javax.net.ssl.HostnameVerifier() {

                    public final boolean verify(String hostName, javax.net.ssl.SSLSession session) {
                        return true;
                    }
                } };
        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv[0]);
    } catch (Throwable ignored) {
    }

    // Setup proxy
    String proxyHost = getConfigProperty(PROXY_HOST, null);
    if (proxyHost != null) {
        String proxyPort = getConfigProperty(PROXY_PORT, null);
        if (proxyPort == null) {
            log.warn("Missing 'proxy.port' configuration property!");
        } else {

            // HTTP proxy server properties
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
            System.setProperty("http.proxySet", "true");

            // HTTPS proxy server properties
            System.setProperty("https.proxyHost", proxyHost);
            System.setProperty("https.proxyPort", proxyPort);
            System.setProperty("https.proxySet", "true");

            // Setup proxy credentials
            String username = getConfigProperty(PROXY_USERNAME, null);
            String encodedPassword = getConfigProperty(PROXY_PASSWORD, null);
            if (username != null) {
                if (encodedPassword == null) {
                    log.warn("Missing 'proxy.password' configuration property!");
                } else {
                    String password = StringUtils.decodePassword(encodedPassword);

                    // HTTP auth credentials
                    System.setProperty("http.proxyUser", username);
                    System.setProperty("http.proxyUserName", username);
                    System.setProperty("http.proxyPassword", password);

                    // HTTPS auth credentials
                    System.setProperty("https.proxyUser", username);
                    System.setProperty("https.proxyUserName", username);
                    System.setProperty("https.proxyPassword", password);
                }
            }
        }
    }

    // Get iCal cache timeout
    long timeout = getConfigProperty(CACHE_TIMEOUT, 180000L);
    if (timeout < 60000L) {
        log.warn("The enabled minimal cache timeout is '1 min'!");
        timeout = 60000L;
    }
    calendarCacheTimeout = timeout;

    // Get backup file timeout
    timeout = getConfigProperty(ICAL_BACKUP_TIMEOUT, 604800000L);
    if (timeout < 86400000L && timeout != 0) {
        log.warn("The enabled minimal backup timeout is '1 day'!");
        timeout = 86400000L;
    }
    backupTimeout = timeout;

    // Get extended syncronization mode (alarms, url, category, etc)
    boolean enable = getConfigProperty(EXTENDED_SYNC_ENABLED, false);
    System.setProperty("gcaldaemon.extended.sync", Boolean.toString(enable));
    if (enable) {
        log.info("Extended synchronization enabled.");
    }

    // Google send an email to the attendees to invite them to attend
    enable = getConfigProperty(SEND_INVITATIONS, false);
    System.setProperty("gcaldaemon.send.invitations", Boolean.toString(enable));

    // Enabled alarm types in the Google Calendar (e.g. 'sms,popup,email')
    System.setProperty("gcaldaemon.remote.alarms", getConfigProperty(REMOTE_ALARM_TYPES, "email,sms,popup"));

    // Get parameters of the feed to iCal converter
    feedEnabled = getConfigProperty(FEED_ENABLED, true);
    feedEventLength = getConfigProperty(FEED_EVENT_LENGTH, 2700000L);
    timeout = getConfigProperty(FEED_CACHE_TIMEOUT, 3600000L);
    if (timeout < 60000L) {
        log.warn("The enabled minimal feed timeout is '1 min'!");
        timeout = 60000L;
    }
    feedCacheTimeout = timeout;
    if (feedEnabled) {
        log.info("RSS/ATOM feed converter enabled.");
    } else {
        log.info("RSS/ATOM feed converter disabled.");
    }

    // Get feed event duplication ratio
    String percent = getConfigProperty(FEED_DUPLICATION_FILTER, "70").trim();
    if (percent.endsWith("%")) {
        percent = percent.substring(0, percent.length() - 1).trim();
    }
    double ratio = Double.parseDouble(percent) / 100;
    if (ratio < 0.4) {
        ratio = 0.4;
        log.warn("The smallest enabled filter percent is '40%'!");
    } else {
        if (ratio > 1) {
            log.warn("The largest filter percent is '100%'!");
            ratio = 1;
        }
    }
    duplicationRatio = ratio;
    if (feedEnabled) {
        if (duplicationRatio == 1) {
            log.debug("Duplication filter disabled.");
        } else {
            log.debug("Sensibility of the duplication filter is " + percent + "%.");
        }
    }

    // Delete backup files
    if (backupTimeout == 0) {
        File backupDirectory = new File(workDirectory, "backup");
        if (backupDirectory.isDirectory()) {
            File[] backups = backupDirectory.listFiles();
            if (backups != null && backups.length != 0) {
                for (i = 0; i < backups.length; i++) {
                    backups[i].delete();
                }
            }
        }
    }

    // Displays time zone
    log.info("Local time zone is " + TimeZone.getDefault().getDisplayName() + ".");

    // Get main thread group
    ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
    while (mainGroup.getParent() != null) {
        mainGroup = mainGroup.getParent();
    }

    // Configurator mode - launch ConfigTool's window
    if (mode == MODE_CONFIGEDITOR) {
        synchronizer = new Synchronizer(mainGroup, this);
        gmailPool = startService(log, mainGroup, "org.gcaldaemon.core.GmailPool");
        new ConfigEditor(this, monitor);
        return;
    }

    // Init synchronizer
    boolean enableHTTP = getConfigProperty(HTTP_ENABLED, true);
    boolean enableFile = getConfigProperty(FILE_ENABLED, false);
    if (enableHTTP || enableFile || !standaloneMode) {
        synchronizer = new Synchronizer(mainGroup, this);
        if (mode == MODE_EMBEDDED) {
            return;
        }
    }

    // On demand mode - run once then quit
    if (mode == MODE_RUNONCE) {
        fileListener = startService(log, mainGroup, "org.gcaldaemon.core.file.OfflineFileListener");
        return;
    }

    // Init Gmail pool
    boolean enableLDAP = getConfigProperty(LDAP_ENABLED, false);
    boolean enableSendMail = getConfigProperty(SENDMAIL_ENABLED, false);
    boolean enableMailTerm = getConfigProperty(MAILTERM_ENABLED, false);
    if (enableLDAP || enableSendMail || enableMailTerm) {
        gmailPool = startService(log, mainGroup, "org.gcaldaemon.core.GmailPool");
    }

    if (standaloneMode) {

        // Init HTTP listener
        if (enableHTTP) {
            httpListener = startService(log, mainGroup, "org.gcaldaemon.core.http.HTTPListener");
        } else {
            log.info("HTTP server disabled.");
        }
    } else {

        // Init J2EE servlet listener
        servletListener = startService(log, mainGroup, "org.gcaldaemon.core.servlet.ServletListener");
    }

    // Init file listener
    if (enableFile) {
        if (getConfigProperty(FILE_OFFLINE_ENABLED, true)) {
            fileListener = startService(log, mainGroup, "org.gcaldaemon.core.file.OfflineFileListener");
        } else {
            fileListener = startService(log, mainGroup, "org.gcaldaemon.core.file.OnlineFileListener");
        }
    } else {
        if (standaloneMode) {
            log.info("File listener disabled.");
        }
    }

    // Init LDAP listener
    if (enableLDAP) {
        contactLoader = startService(log, mainGroup, "org.gcaldaemon.core.ldap.ContactLoader");
    } else {
        if (standaloneMode) {
            log.info("LDAP server disabled.");
        }
    }

    // Init Gmail notifier
    if (getConfigProperty(NOTIFIER_ENABLED, false)) {
        if (GraphicsEnvironment.isHeadless()) {
            log.warn("Unable to use Gmail notifier in headless mode!");
        } else {
            mailNotifier = startService(log, mainGroup, "org.gcaldaemon.core.notifier.GmailNotifier");
        }
    } else {
        if (standaloneMode) {
            log.info("Gmail notifier disabled.");
        }
    }

    // Init sendmail service
    if (enableSendMail) {
        sendMail = startService(log, mainGroup, "org.gcaldaemon.core.sendmail.SendMail");
    } else {
        if (standaloneMode) {
            log.info("Sendmail service disabled.");
        }
    }

    // Init mailterm service
    if (enableMailTerm) {
        mailTerm = startService(log, mainGroup, "org.gcaldaemon.core.mailterm.MailTerminal");
    } else {
        if (standaloneMode) {
            log.info("Mail terminal disabled.");
        }
    }

    // Clear configuration holder
    config.clear();
}

From source file:org.apache.juddi.samples.JuddiAdminService.java

void printStatusSingleNode(Transport transport, String authtoken) throws Exception {
    String replicationUrl = clerkManager.getClientConfig().getUDDINode(curentnode).getReplicationUrl();

    SSLContext sc = SSLContext.getInstance("SSLv3");

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")),
            System.getProperty("javax.net.ssl.keyStorePassword").toCharArray());

    kmf.init(ks, System.getProperty("javax.net.ssl.keyStorePassword").toCharArray());

    sc.init(kmf.getKeyManagers(), null, null);

    UDDIReplicationPortType uddiReplicationPort = new UDDIService().getUDDIReplicationPort();
    ((BindingProvider) uddiReplicationPort).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
            replicationUrl);//  ww  w .  j  a  va 2s.  c  o  m
    ((BindingProvider) uddiReplicationPort).getRequestContext()
            .put("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory", sc.getSocketFactory());
    /*((BindingProvider) uddiReplicationPort).getRequestContext()
     .put(
     JAXWSProperties.SSL_SOCKET_FACTORY,
     sc.getSocketFactory());*/

    String doPing = uddiReplicationPort.doPing(new DoPing());
    System.out.println(doPing + ".., success");

}

From source file:org.apache.nifi.controller.livy.LivySessionController.java

private void setSslSocketFactory(HttpsURLConnection httpsURLConnection, SSLContextService sslService,
        SSLContext sslContext) throws IOException, KeyStoreException, CertificateException,
        NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    final String keystoreLocation = sslService.getKeyStoreFile();
    final String keystorePass = sslService.getKeyStorePassword();
    final String keystoreType = sslService.getKeyStoreType();

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);

    try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
        keyStore.load(keyStoreStream, keystorePass.toCharArray());
    }//ww w  .  j  ava2s  .com

    final KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePass.toCharArray());

    // load truststore
    final String truststoreLocation = sslService.getTrustStoreFile();
    final String truststorePass = sslService.getTrustStorePassword();
    final String truststoreType = sslService.getTrustStoreType();

    KeyStore truststore = KeyStore.getInstance(truststoreType);
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
    truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray());
    trustManagerFactory.init(truststore);

    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
}

From source file:com.photon.phresco.framework.commons.FrameworkUtil.java

public static int getHttpsResponse(String url) throws PhrescoException {
    URL httpsUrl;/*  w  w w . j  a  v a 2s .c  om*/
    try {
        SSLContext ssl_ctx = SSLContext.getInstance("SSL");
        TrustManager[] trust_mgr = get_trust_mgr();
        ssl_ctx.init(null, trust_mgr, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory());
        httpsUrl = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) httpsUrl.openConnection();
        con.setHostnameVerifier(new HostnameVerifier() {
            // Guard against "bad hostname" errors during handshake.   
            public boolean verify(String host, SSLSession sess) {
                return true;
            }
        });
        return con.getResponseCode();
    } catch (MalformedURLException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new PhrescoException(e);
    } catch (KeyManagementException e) {
        throw new PhrescoException(e);
    }
}

From source file:net.myrrix.client.ClientRecommender.java

private SSLSocketFactory buildSSLSocketFactory() throws IOException {

    final HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override// ww  w. j  a va2 s  .c  o  m
        public boolean verify(String hostname, SSLSession sslSession) {
            return ignoreHTTPSHost || "localhost".equals(hostname) || "127.0.0.1".equals(hostname)
                    || defaultVerifier.verify(hostname, sslSession);
        }
    });

    try {

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File trustStoreFile = config.getKeystoreFile().getAbsoluteFile();
        String password = config.getKeystorePassword();
        Preconditions.checkNotNull(password);

        InputStream in = new FileInputStream(trustStoreFile);
        try {
            keyStore.load(in, password.toCharArray());
        } finally {
            in.close();
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        SSLContext ctx;
        try {
            ctx = SSLContext.getInstance("TLSv1.1"); // Java 7 only
        } catch (NoSuchAlgorithmException ignored) {
            log.info("TLSv1.1 unavailable, falling back to TLSv1");
            ctx = SSLContext.getInstance("TLSv1"); // Java 6       
            // This also seems to be necessary:
            if (System.getProperty("https.protocols") == null) {
                System.setProperty("https.protocols", "TLSv1");
            }
        }
        ctx.init(null, tmf.getTrustManagers(), null);
        return ctx.getSocketFactory();

    } catch (NoSuchAlgorithmException nsae) {
        // can't happen?
        throw new IllegalStateException(nsae);
    } catch (KeyStoreException kse) {
        throw new IOException(kse);
    } catch (KeyManagementException kme) {
        throw new IOException(kme);
    } catch (CertificateException ce) {
        throw new IOException(ce);
    }
}

From source file:com.ebridgevas.android.ebridgeapp.messaging.mqttservice.MqttAndroidClient.java

/**
 * Get the SSLSocketFactory using SSL key store and password
 * <p>/*ww w .j a v  a 2  s  .co m*/
 * A convenience method, which will help user to create a SSLSocketFactory
 * object
 * </p>
 * 
 * @param keyStore
 *            the SSL key store which is generated by some SSL key tool,
 *            such as keytool in Java JDK
 * @param password
 *            the password of the key store which is set when the key store
 *            is generated
 * @return SSLSocketFactory used to connect to the server with SSL
 *         authentication
 * @throws MqttSecurityException
 *             if there was any error when getting the SSLSocketFactory
 */
public SSLSocketFactory getSSLSocketFactory(InputStream keyStore, String password)
        throws MqttSecurityException {
    try {
        SSLContext ctx = null;
        SSLSocketFactory sslSockFactory = null;
        KeyStore ts;
        ts = KeyStore.getInstance("BKS");
        ts.load(keyStore, password.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(ts);
        TrustManager[] tm = tmf.getTrustManagers();
        ctx = SSLContext.getInstance("TLSv1");
        ctx.init(null, tm, null);

        sslSockFactory = ctx.getSocketFactory();
        return sslSockFactory;

    } catch (KeyStoreException e) {
        throw new MqttSecurityException(e);
    } catch (CertificateException e) {
        throw new MqttSecurityException(e);
    } catch (FileNotFoundException e) {
        throw new MqttSecurityException(e);
    } catch (IOException e) {
        throw new MqttSecurityException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new MqttSecurityException(e);
    } catch (KeyManagementException e) {
        throw new MqttSecurityException(e);
    }
}