Example usage for java.security KeyStore getDefaultType

List of usage examples for java.security KeyStore getDefaultType

Introduction

In this page you can find the example usage for java.security KeyStore getDefaultType.

Prototype

public static final String getDefaultType() 

Source Link

Document

Returns the default keystore type as specified by the keystore.type security property, or the string "jks" (acronym for "Java keystore" ) if no such property exists.

Usage

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * Method to get the information of the certificate.
 *
 * @param alias : Alias of the certificate which information should be retrieved
 * @return : The details of the certificate as a MAP.
 *//*  ww w.  j  a v a2 s . com*/
public CertificateInformationDTO getCertificateInformation(String alias) throws CertificateManagementException {

    CertificateInformationDTO certificateInformation = new CertificateInformationDTO();
    File trustStoreFile = new File(TRUST_STORE);
    try {
        localTrustStoreStream = new FileInputStream(trustStoreFile);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD);

        if (trustStore.containsAlias(alias)) {
            X509Certificate certificate = (X509Certificate) trustStore.getCertificate(alias);
            certificateInformation = getCertificateMetaData(certificate);
        }
    } catch (IOException e) {
        throw new CertificateManagementException("Error wile loading the keystore.", e);
    } catch (CertificateException e) {
        throw new CertificateManagementException("Error loading the keystore from the stream.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateManagementException("Could not find the algorithm to load the certificate.", e);
    } catch (KeyStoreException e) {
        throw new CertificateManagementException("Error reading certificate contents.", e);
    } finally {
        closeStreams(localTrustStoreStream);
    }
    return certificateInformation;
}

From source file:com.vmware.bdd.utils.CommonUtil.java

public static KeyStore loadAppMgrKeyStore(String keystorePath) {
    File file = new File(keystorePath + Constants.APPMANAGER_KEYSTORE_FILE);
    if (file.isFile() == false) {
        char SEP = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        file = new File(dir, Constants.APPMANAGER_KEYSTORE_FILE);
        if (file.isFile() == false) {
            file = new File(dir, "cacerts");
        }//  w w  w .  j a va 2s.co m
    }

    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e) {
        logger.error("Can't get KeyStore instance. ", e);
        return null;
    }
    InputStream in = null;
    try {
        in = new FileInputStream(file);
        keyStore.load(in, Constants.APPMANAGER_KEYSTORE_PASSWORD);
    } catch (FileNotFoundException e) {
        logger.error("Can't find file " + file.getAbsolutePath(), e);
        return null;
    } catch (NoSuchAlgorithmException e) {
        logger.error("No such algorithm error during loading keystore.", e);
        return null;
    } catch (CertificateException e) {
        logger.error("Certificate exception during loading keystore.", e);
        return null;
    } catch (IOException e) {
        logger.error("Caught IO Exception.", e);
        return null;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.warn("Input stream of appmanagers.jks close failed.");
            }
        }
    }
    return keyStore;
}

From source file:org.archive.crawler.Heritrix.java

/**
 * Perform preparation to use an ad-hoc, created-as-necessary 
 * certificate/keystore for HTTPS access. A keystore with new
 * cert is created if necessary, as adhoc.keystore in the working
 * directory. Otherwise, a preexisting adhoc.keystore is read 
 * and the certificate fingerprint shown to assist in operator
 * browser-side verification./* w  w  w .ja v  a  2s  .  com*/
 * @param startupOut where to report fingerprint
 */
protected void useAdhocKeystore(PrintStream startupOut) {
    try {
        File keystoreFile = new File(ADHOC_KEYSTORE);
        if (!keystoreFile.exists()) {
            String[] args = { "-keystore", ADHOC_KEYSTORE, "-storepass", ADHOC_PASSWORD, "-keypass",
                    ADHOC_PASSWORD, "-alias", "adhoc", "-genkey", "-keyalg", "RSA", "-dname",
                    "CN=Heritrix Ad-Hoc HTTPS Certificate", "-validity", "3650" }; // 10 yr validity
            KeyTool.main(args);
        }

        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream inStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(keystoreFile));
        keystore.load(inStream, ADHOC_PASSWORD.toCharArray());
        Certificate cert = keystore.getCertificate("adhoc");
        byte[] certBytes = cert.getEncoded();
        byte[] sha1 = MessageDigest.getInstance("SHA1").digest(certBytes);
        startupOut.print("Using ad-hoc HTTPS certificate with fingerprint...\nSHA1");
        for (byte b : sha1) {
            startupOut.print(String.format(":%02X", b));
        }
        startupOut.println("\nVerify in browser before accepting exception.");
    } catch (Exception e) {
        // fatal, rethrow
        throw new RuntimeException(e);
    }
}

From source file:org.projectforge.core.ConfigXml.java

private SSLSocketFactory createSSLSocketFactory(final InputStream is, final String passphrase)
        throws Exception {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(is, passphrase.toCharArray());
    is.close();/*w w  w.j a v  a  2 s  .com*/
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    final X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    final SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { defaultTrustManager }, null);
    return context.getSocketFactory();
}

From source file:com.haoqee.chatsdk.net.Utility.java

public static HttpClient getNewHttpClient(long timeout) {
    try {// w  ww .  j  ava  2 s  .  co m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        //HttpConnectionParams.setConnectionTimeout(params, 10000);
        //HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        //HttpProtocolParams.setContentCharset(params, HTTP.);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
        long soc_time = Utility.SET_SOCKET_TIMEOUT + timeout;
        HttpConnectionParams.setSoTimeout(params, (int) soc_time);
        HttpClient client = new DefaultHttpClient(ccm, params);
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:self.philbrown.droidQuery.Ajax.java

protected TaskResponse doInBackground(Void... arg0) {
    if (this.isCancelled)
        return null;

    //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming.
    if (!beforeSendIsAsync) {
        try {/*w w  w.  ja  v  a  2  s  .co  m*/
            mutex.acquire();
        } catch (InterruptedException e) {
            Log.w("AjaxTask", "Synchronization Error. Running Task Async");
        }
        final Thread asyncThread = Thread.currentThread();
        isLocked = true;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (options.beforeSend() != null) {
                    if (options.context() != null)
                        options.beforeSend().invoke($.with(options.context()), options);
                    else
                        options.beforeSend().invoke(null, options);
                }

                if (options.isAborted()) {
                    cancel(true);
                    return;
                }

                if (options.global()) {
                    synchronized (globalTasks) {
                        if (globalTasks.isEmpty()) {
                            $.ajaxStart();
                        }
                        globalTasks.add(Ajax.this);
                    }
                    $.ajaxSend();
                } else {
                    synchronized (localTasks) {
                        localTasks.add(Ajax.this);
                    }
                }
                isLocked = false;
                LockSupport.unpark(asyncThread);
            }
        });
        if (isLocked)
            LockSupport.park();
    }

    //here is where to use the mutex

    //handle cached responses
    Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options);
    //handle ajax caching option
    if (cachedResponse != null && options.cache()) {
        Success s = new Success(cachedResponse);
        s.reason = "cached response";
        s.allHeaders = null;
        return s;

    }

    if (connection == null) {
        try {
            String type = options.type();
            URL url = new URL(options.url());
            if (type == null) {
                type = "GET";
            }
            if (type.equalsIgnoreCase("CUSTOM")) {

                try {
                    connection = options.customConnection();
                } catch (Exception e) {
                    connection = null;
                }

                if (connection == null) {
                    Log.w("droidQuery.ajax",
                            "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET.");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                }
            } else {
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod(type);
                if (type.equalsIgnoreCase("POST") || type.equalsIgnoreCase("PUT")) {
                    connection.setDoOutput(true);
                }
            }
        } catch (Throwable t) {
            if (options.debug())
                t.printStackTrace();
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = 0;
            e.reason = "Bad Configuration";
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = new Headers();
            e.error = error;
            return e;
        }

    }

    Map<String, Object> args = new HashMap<String, Object>();
    args.put("options", options);
    args.put("request", null);
    args.put("connection", connection);
    EventCenter.trigger("ajaxPrefilter", args, null);

    if (options.headers() != null) {
        if (options.headers().authorization() != null) {
            options.headers()
                    .authorization(options.headers().authorization() + " " + options.getEncodedCredentials());
        } else if (options.username() != null) {
            //guessing that authentication is basic
            options.headers().authorization("Basic " + options.getEncodedCredentials());
        }

        for (Entry<String, String> entry : options.headers().map().entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    if (options.data() != null) {
        try {
            OutputStream os = connection.getOutputStream();
            os.write(options.data().toString().getBytes());
            os.close();
        } catch (Throwable t) {
            Log.w("Ajax", "Could not post data");
        }
    }

    if (options.timeout() != 0) {
        connection.setConnectTimeout(options.timeout());
        connection.setReadTimeout(options.timeout());
    }

    if (options.trustedCertificate() != null) {

        Certificate ca = options.trustedCertificate();

        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = null;
        try {
            keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);
        } catch (KeyStoreException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (CertificateException e) {
            if (options.debug())
                e.printStackTrace();
        } catch (IOException e) {
            if (options.debug())
                e.printStackTrace();
        }

        if (keyStore == null) {
            Log.w("Ajax", "Could not configure trusted certificate");
        } else {
            try {
                //Create a TrustManager that trusts the CAs in our KeyStore
                String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
                tmf.init(keyStore);

                //Create an SSLContext that uses our TrustManager
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, tmf.getTrustManagers(), null);
                ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
            } catch (KeyManagementException e) {
                if (options.debug())
                    e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                if (options.debug())
                    e.printStackTrace();
            } catch (KeyStoreException e) {
                if (options.debug())
                    e.printStackTrace();
            }
        }
    }

    try {

        if (options.cookies() != null) {
            CookieManager cm = new CookieManager();
            CookieStore cookies = cm.getCookieStore();
            URI uri = URI.create(options.url());
            for (Entry<String, String> entry : options.cookies().entrySet()) {
                HttpCookie cookie = new HttpCookie(entry.getKey(), entry.getValue());
                cookies.add(uri, cookie);
            }
            connection.setRequestProperty("Cookie", TextUtils.join(",", cookies.getCookies()));
        }

        connection.connect();
        final int statusCode = connection.getResponseCode();
        final String message = connection.getResponseMessage();

        if (options.dataFilter() != null) {
            if (options.context() != null)
                options.dataFilter().invoke($.with(options.context()), connection, options.dataType());
            else
                options.dataFilter().invoke(null, connection, options.dataType());
        }

        final Function function = options.statusCode().get(statusCode);
        if (function != null) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (options.context() != null)
                        function.invoke($.with(options.context()), statusCode, options.clone());
                    else
                        function.invoke(null, statusCode, options.clone());
                }

            });

        }

        //handle dataType
        String dataType = options.dataType();
        if (dataType == null)
            dataType = "text";
        if (options.debug())
            Log.i("Ajax", "dataType = " + dataType);
        Object parsedResponse = null;
        InputStream stream = null;
        try {
            if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) {
                if (options.debug())
                    Log.i("Ajax", "parsing text");
                stream = AjaxUtil.getInputStream(connection);
                parsedResponse = parseText(stream);
            } else if (dataType.equalsIgnoreCase("xml")) {
                if (options.debug())
                    Log.i("Ajax", "parsing xml");
                if (options.customXMLParser() != null) {
                    stream = AjaxUtil.getInputStream(connection);
                    if (options.SAXContentHandler() != null)
                        options.customXMLParser().parse(stream, options.SAXContentHandler());
                    else
                        options.customXMLParser().parse(stream, new DefaultHandler());
                    parsedResponse = "Response handled by custom SAX parser";
                } else if (options.SAXContentHandler() != null) {
                    stream = AjaxUtil.getInputStream(connection);
                    SAXParserFactory factory = SAXParserFactory.newInstance();

                    factory.setFeature("http://xml.org/sax/features/namespaces", false);
                    factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                    SAXParser parser = factory.newSAXParser();

                    XMLReader reader = parser.getXMLReader();
                    reader.setContentHandler(options.SAXContentHandler());
                    reader.parse(new InputSource(stream));
                    parsedResponse = "Response handled by custom SAX content handler";
                } else {
                    parsedResponse = parseXML(connection);
                }
            } else if (dataType.equalsIgnoreCase("json")) {
                if (options.debug())
                    Log.i("Ajax", "parsing json");
                parsedResponse = parseJSON(connection);
            } else if (dataType.equalsIgnoreCase("script")) {
                if (options.debug())
                    Log.i("Ajax", "parsing script");
                parsedResponse = parseScript(connection);
            } else if (dataType.equalsIgnoreCase("image")) {
                if (options.debug())
                    Log.i("Ajax", "parsing image");
                stream = AjaxUtil.getInputStream(connection);
                parsedResponse = parseImage(stream);
            } else if (dataType.equalsIgnoreCase("raw")) {
                if (options.debug())
                    Log.i("Ajax", "parsing raw data");
                parsedResponse = parseRawContent(connection);
            }
        } catch (ClientProtocolException cpe) {
            if (options.debug())
                cpe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = statusCode;
            e.reason = message;
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            e.error = error;
            return e;
        } catch (Exception ioe) {
            if (options.debug())
                ioe.printStackTrace();
            Error e = new Error(parsedResponse);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            e.status = statusCode;
            e.reason = message;
            error.status = e.status;
            error.reason = e.reason;
            error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            e.error = error;
            return e;
        } finally {
            connection.disconnect();
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
            }
        }

        if (statusCode >= 300) {
            //an error occurred
            Error e = new Error(parsedResponse);
            Log.e("Ajax Test", parsedResponse.toString());
            //AjaxError error = new AjaxError();
            //error.request = request;
            //error.options = options;
            e.status = e.status;
            e.reason = e.reason;
            //error.status = e.status;
            //error.reason = e.reason;
            //error.response = e.response;
            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            //e.error = error;
            if (options.debug())
                Log.i("Ajax", "Error " + e.status + ": " + e.reason);
            return e;
        } else {
            //handle ajax ifModified option
            List<String> lastModifiedHeaders = connection.getHeaderFields().get("last-modified");
            if (lastModifiedHeaders.size() >= 1) {
                try {
                    String h = lastModifiedHeaders.get(0);
                    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
                    Date lastModified = format.parse(h);
                    if (options.ifModified() && lastModified != null) {
                        Date lastModifiedDate;
                        synchronized (lastModifiedUrls) {
                            lastModifiedDate = lastModifiedUrls.get(options.url());
                        }

                        if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) {
                            //request response has not been modified. 
                            //Causes an error instead of a success.
                            Error e = new Error(parsedResponse);
                            AjaxError error = new AjaxError();
                            error.connection = connection;
                            error.options = options;
                            e.status = e.status;
                            e.reason = e.reason;
                            error.status = e.status;
                            error.reason = e.reason;
                            error.response = e.response;
                            e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
                            e.error = error;
                            Function func = options.statusCode().get(304);
                            if (func != null) {
                                if (options.context() != null)
                                    func.invoke($.with(options.context()));
                                else
                                    func.invoke(null);
                            }
                            return e;
                        } else {
                            synchronized (lastModifiedUrls) {
                                lastModifiedUrls.put(options.url(), lastModified);
                            }
                        }
                    }
                } catch (Throwable t) {
                    Log.e("Ajax", "Could not parse Last-Modified Header", t);
                }

            }

            //Now handle a successful request

            Success s = new Success(parsedResponse);
            s.reason = message;
            s.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            return s;
        }

    } catch (Throwable t) {
        if (options.debug())
            t.printStackTrace();
        if (t instanceof java.net.SocketTimeoutException) {
            Error e = new Error(null);
            AjaxError error = new AjaxError();
            error.connection = connection;
            error.options = options;
            error.response = e.response;
            e.status = 0;
            String reason = t.getMessage();
            if (reason == null)
                reason = "Socket Timeout";
            e.reason = reason;
            error.status = e.status;
            error.reason = e.reason;
            if (connection != null)
                e.allHeaders = Headers.createHeaders(connection.getHeaderFields());
            else
                e.allHeaders = new Headers();
            e.error = error;
            return e;
        }
        return null;
    }
}

From source file:com.curso.listadapter.net.RESTClient.java

/**
 *
 * this private method obtains the httpclient that support https
 * and set the timeout in 30 secconds/*from w  w  w.  j a  va  2  s  .  co m*/
 *
 *
 * */
public HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, RequestTimeOut);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}