Example usage for java.security KeyManagementException getMessage

List of usage examples for java.security KeyManagementException getMessage

Introduction

In this page you can find the example usage for java.security KeyManagementException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:test.integ.be.fedict.trust.util.SSLTrustManager.java

private static void initSocketFactory() {

    LOG.debug("init socket factory");
    SSLTrustManager trustManagerInstance = new SSLTrustManager();
    TrustManager[] trustManager = { trustManagerInstance };
    try {//from w  w  w .  ja va  2  s.co m
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());
        socketFactory = sslContext.getSocketFactory();
    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoapViaHttps(String hosturl, String ip, int port, String action, String method,
        String xml) {/*from   w ww  .  j  a v a2s  .co  m*/

    String reqURL = "https://" + ip + ":" + port + action;
    //      Map<String, String> params = null;
    long responseLength = 0; // ?
    String responseContent = null; // ?

    HttpClient httpClient = new DefaultHttpClient(); // httpClient
    httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);

    X509TrustManager xtm = new X509TrustManager() { // TrustManager
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    try {
        // TLS1.0SSL3.0??TLSSSL?SSLContext
        SSLContext ctx = SSLContext.getInstance("TLS");

        // TrustManager??TrustManager?SSLSocket
        ctx.init(null, new TrustManager[] { xtm }, null);

        // SSLSocketFactory
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);

        // SchemeRegistrySSLSocketFactoryHttpClient
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", port, socketFactory));

        HttpPost httpPost = new HttpPost(reqURL); // HttpPost

        // add the 3 headers below
        httpPost.addHeader("Accept-Encoding", "gzip,deflate");
        httpPost.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        httpPost.addHeader("uuid", "itest");// for editor token of DR-Api

        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8
        httpPost.setEntity(requestBody);
        log.info(">> Request URI: " + httpPost.getRequestLine().getUri());

        HttpResponse response = httpClient.execute(httpPost); // POST
        HttpEntity entity = response.getEntity(); // ??

        if (null != entity) {
            responseLength = entity.getContentLength();

            String contentEncoding = null;
            Header ce = response.getEntity().getContentEncoding();
            if (ce != null) {
                contentEncoding = ce.getValue();
            }

            if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
                GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
                Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
                StringBuilder sb = new StringBuilder();
                while (in.hasNextLine()) {
                    sb.append(in.nextLine()).append(System.getProperty("line.separator"));
                }
                responseContent = sb.toString();
            } else {
                responseContent = EntityUtils.toString(response.getEntity(), "UTF-8");
            }

            EntityUtils.consume(entity); // Consume response content
        }
        log.info("?: " + httpPost.getURI());
        log.info("??: " + response.getStatusLine());
        log.info("?: " + responseLength);
        log.info("?: " + responseContent);
    } catch (KeyManagementException e) {
        log.error(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    } catch (ClientProtocolException e) {
        log.error(e.getMessage(), e);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        httpClient.getConnectionManager().shutdown(); // ,?
        return responseContent;
    }
}

From source file:com.redhat.rcm.version.util.InputUtils.java

private static void setupClient() throws VManException {
    if (client == null) {
        SSLSocketFactory sslSocketFactory;
        try {/*ww w.  j  a v  a 2s.  c  o  m*/
            sslSocketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustKs, null,
                    new TrustSelfSignedStrategy(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            //                sslSocketFactory =
            //                    new SSLSocketFactory( SSLSocketFactory.TLS, null, null, trustKs, null, null,
            //                                          SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER );
        } catch (final KeyManagementException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final UnrecoverableKeyException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final NoSuchAlgorithmException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final KeyStoreException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        }

        final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager();
        ccm.getSchemeRegistry().register(new Scheme("https", 443, sslSocketFactory));

        final DefaultHttpClient hc = new DefaultHttpClient(ccm);
        hc.setRedirectStrategy(new DefaultRedirectStrategy());

        final String proxyHost = System.getProperty("http.proxyHost");
        final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1"));

        if (proxyHost != null && proxyPort > 0) {
            final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        }

        client = hc;
    }
}

From source file:com.cloud.network.resource.NccHttpCode.java

public static HttpClient getHttpClient() {

    HttpClient httpClient = null;/*from  w  w  w .j  av a  2s.  co  m*/
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };

    try {
        SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_PORT, sf));
        ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }
    return httpClient;
}

From source file:com.cloud.network.resource.NccHttpCode.java

public static String postHttpRequest(final String jsonCmd, final URI agentUri, String sessionID)
        throws ExecutionException {
    // Using Apache's HttpClient for HTTP POST
    // Java-only approach discussed at on StackOverflow concludes with
    // comment to use Apache HttpClient
    // http://stackoverflow.com/a/2793153/939250, but final comment is to
    // use Apache.
    String logMessage = StringEscapeUtils.unescapeJava(jsonCmd);
    logMessage = cleanPassword(logMessage);
    s_logger.debug("POST request to " + agentUri.toString() + " with contents " + logMessage);

    // Create request
    HttpClient httpClient = getHttpClient();
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override/* w  ww. ja  v  a  2  s .c o m*/
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };

    try {
        SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_PORT, sf));
        ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }

    String result = null;

    // TODO: are there timeout settings and worker thread settings to tweak?
    try {
        HttpPost request = new HttpPost(agentUri);

        // JSON encode command
        // Assumes command sits comfortably in a string, i.e. not used for
        // large data transfers
        StringEntity cmdJson = new StringEntity(jsonCmd);
        request.addHeader("content-type", "application/json");
        request.addHeader("Cookie", "SessId=" + sessionID);
        request.setEntity(cmdJson);
        s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage + "SEssion id: "
                + sessionID);
        HttpResponse response = httpClient.execute(request);

        // Unsupported commands will not route.
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            String errMsg = "Failed : HTTP error code : " + response.getStatusLine().getStatusCode();
            throw new ExecutionException(NccHttpCode.NOT_FOUND);
        } else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                && (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED)) {
            String errMsg = "Command Not Success " + agentUri.toString() + " : HTTP error code : "
                    + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            throw new ExecutionException(NccHttpCode.INTERNAL_ERROR + " " + errMsg);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            //Successfully created the resource in the NCC, Now get the Job ID and send to the response
            // make login request and store new session id
            throw new ExecutionException(NccHttpCode.UNAUTHORIZED);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            //Successfully created the resource in the NCC, Now get the Job ID and send to the response
            result = response.getFirstHeader(NccHttpCode.JOB_ID).getValue();
        } else {
            result = EntityUtils.toString(response.getEntity());
            String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
            s_logger.debug("POST response is " + logResult);
        }

    } catch (ClientProtocolException protocolEx) {
        // Problem with HTTP message exchange
        s_logger.error(protocolEx);
    } catch (IOException connEx) {
        // Problem with underlying communications
        s_logger.error(connEx);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:securitytools.common.http.TrustingSSLConnectionSocketFactory.java

private SSLContext getSSLContext() throws IOException {
    if (sslContext == null) {
        try {//from w ww  .  j av  a 2  s  .c om
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { new TrustingX509TrustManager() }, null);
        } catch (NoSuchAlgorithmException nsae) {
            throw new IOException(nsae.getMessage(), nsae);
        } catch (KeyManagementException kme) {
            throw new IOException(kme.getMessage(), kme);
        }
    }
    return sslContext;
}

From source file:com.appfirst.communication.AFHttpClient.java

public DefaultHttpClient getAFHttpClient() {
    try {//from  w  w  w. j a v  a2 s  . c o m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            trustStore.load(null, null);
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

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

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        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 (NoSuchAlgorithmException nsae) {
        Log.e(TAG, nsae.getMessage());
        return new DefaultHttpClient();
    } catch (KeyManagementException kme) {
        Log.e(TAG, kme.getMessage());
        return new DefaultHttpClient();
    } catch (KeyStoreException kse) {
        Log.e(TAG, kse.getMessage());
        return new DefaultHttpClient();
    } catch (UnrecoverableKeyException uke) {
        Log.e(TAG, uke.getMessage());
        return new DefaultHttpClient();
    }
}

From source file:com.adito.boot.CustomSSLSocketFactory.java

private SSLSocketFactory getSocketFactory() throws IOException {
    try {/*w  ww .  j a v a  2s . c o m*/
        SSLContext sslCtx = SSLContext.getInstance("SSL");
        KeyManager[] aKM = SSLKeyManager.getKeyManagerArray();
        TrustManager[] aTM = SSLTrustManager.getTrustManagerArray();
        sslCtx.init(aKM, aTM, null);
        SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
        return socketFactory;
    } catch (KeyManagementException e) {
        log.error("Cannot create SSL socket", e);
        throw new IOException("Cannot create SSL socket: " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        log.error("Cannot create SSL socket", e);
        throw new IOException("Cannot create SSL socket: " + e.getMessage());
    }
}

From source file:org.ckan.Connection.java

/**
* Makes a POST request/*from  w ww .  j a va  2  s .c  o  m*/
*
* Submits a POST HTTP request to the CKAN instance configured within
* the constructor, returning the entire contents of the response.
*
* @param  path The URL path to make the POST request to
* @param  data The data to be posted to the URL
* @returns The String contents of the response
* @throws A CKANException if the request fails
*/
protected String post(String path, String data) throws CKANException {
    URL url = null;

    try {
        url = new URL(this.m_host + ":" + this.m_port + path);
    } catch (MalformedURLException mue) {
        System.err.println(mue);
        return null;
    }

    String body = "";

    BasicClientConnectionManager bccm = null;
    ClientConnectionManager cm = null;
    try {
        /***********************************************************************/
        SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", 443, sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        //bccm = new BasicClientConnectionManager(schemeRegistry);
        // apache HttpClient version >4.2 should use BasicClientConnectionManager
        cm = new SingleClientConnManager(schemeRegistry);
        /***********************************************************************/
    } catch (KeyManagementException kme) {
        System.out.println("Con ex: " + kme.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        System.out.println("Con ex: " + nsae.getMessage());
    }

    //HttpClient httpclient = new DefaultHttpClient(cm);
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpPost postRequest = new HttpPost(url.toString());
        postRequest.setHeader("X-CKAN-API-Key", this._apikey);

        StringEntity input = new StringEntity(data);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpclient.execute(postRequest);
        int statusCode = response.getStatusLine().getStatusCode();

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String line = "";
        while ((line = br.readLine()) != null) {
            body += line;
        }
    } catch (IOException ioe) {
        System.out.println(ioe);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return body;
}

From source file:ucar.httpservices.CustomSSLProtocolSocketFactory.java

private SSLContext createSSLContext(HttpParams params) throws IOException {
    if (this.sslcontext == null)
        try {// w  w  w.  j a  v  a 2s  .  co m
            // Get the Desired kind of authentication
            this.sslcontext = trustedauthentication(params);
            if (this.sslcontext == null)
                this.sslcontext = stdauthentication();
        } catch (KeyManagementException e) {
            throw new HTTPException("Key Management exception: " + e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            throw new HTTPException("Unsupported algorithm exception: " + e.getMessage());
        } catch (KeyStoreException e) {
            throw new HTTPException("Keystore exception: " + e.getMessage());
        } catch (GeneralSecurityException e) {
            throw new HTTPException("Key management exception: " + e.getMessage());
        } catch (IOException e) {
            throw new HTTPException("I/O error reading keystore/truststore file: " + e.getMessage());
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    return this.sslcontext;
}