Example usage for java.security KeyManagementException printStackTrace

List of usage examples for java.security KeyManagementException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:se.simonsoft.cms.testing.svn.SvnTestSetup.java

private boolean isHttpUrlSvnParent(String httpUrl) {

    RestURL restUrl = new RestURL(httpUrl);
    RestAuthenticationClientCert auth = null;
    try {/*from  w ww .  ja  v a 2  s . co m*/
        auth = new RestAuthenticationClientCert(getIgnoringTrustManager(), null, "testuser", "testpassword");
    } catch (KeyManagementException e1) {
        //Should not happen, so won't handle the error.
        e1.printStackTrace();
    }
    RestClient restClientJavaNet = new RestClientJavaNet(restUrl.r(), auth);
    ResponseHeaders head;

    try {

        head = restClientJavaNet.head(restUrl.p());
    } catch (java.net.ConnectException ec) {
        logger.debug("Rejecting URL", restUrl, "due to connection error:", ec.toString());
        return false;
    } catch (IOException e) {
        throw new RuntimeException("Svn test setup failed", e);
    }
    if (head.getStatus() != 200 && head.getStatus() != 401) {
        logger.debug("Rejecting URL", restUrl, "due to status", head.getStatus());
        return false;
    }
    // TODO check for "Colleciton of repositories"
    logger.debug("URL", restUrl, "ok with content type", head.getContentType());
    return true;
}

From source file:org.openmuc.framework.driver.rest.RestConnection.java

public RestConnection(String deviceAddress, String credentials, int timeout) throws ConnectionException {

    this.timeout = timeout;
    wrapper = new JsonWrapper();
    authString = new String(Base64.encodeBase64(credentials.getBytes()));

    if (!deviceAddress.endsWith("/")) {
        this.deviceAddress = deviceAddress + "/channels/";
    } else {/*from ww  w. j av a 2 s  .c o m*/
        this.deviceAddress = deviceAddress + "channels/";
    }

    if (deviceAddress.startsWith("https://")) {
        isHTTPS = true;
    } else {
        isHTTPS = false;
    }

    if (isHTTPS) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

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

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (KeyManagementException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        // HttpsURLConnection.setFollowRedirects(false);
    }
}

From source file:net.shopxx.controller.shop.OAuthController.java

/**
 * QQ??//from   w w  w. j  a v  a 2  s  .co m
 * 
 * @param code
 * @param state
 * @return
 */
@RequestMapping("/qq/callback")
public String qq_callback(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        String code, String state) {
    JSONObject object;
    try {
        object = qq_oauthPlugin.getUserInfoByCode(code);
        return this.qqOAuthInfo(request, response, session, object, "qqOAuthPlugin");
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "redirect:/";
}

From source file:net.shopxx.controller.shop.OAuthController.java

/**
 * sina??//from   w  w w.  j  a  v  a 2  s.co m
 * 
 * @param code
 * @param state
 * @return
 */
@RequestMapping("/sina/callback")
public String sina_callback(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        String code, String state) {
    JSONObject object;
    try {
        object = sina_oauthPlugin.getUserInfoByCode(code);
        return this.sinaOAuthInfo(request, response, session, object, "oAuthSinaPlugin");
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "redirect:/";
}

From source file:net.shopxx.controller.shop.OAuthController.java

/**
 * baidu??/*w  w w.j av a2 s.c o m*/
 * 
 * @param code
 * @param state
 * @return
 */
@RequestMapping("/baidu/callback")
public String baidu_callback(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        String code, String state) {
    JSONObject object;
    try {
        object = baidu_oauthPlugin.getUserInfoByCode(code);
        return this.baiduOAuthInfo(request, response, session, object, "oAuthBaiduPlugin");
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "redirect:/";
}

From source file:iristk.speech.nuancecloud.NuanceCloudRecognizerListener.java

public NuanceCloudRecognizerListener(NuanceCloudLicense license) {
    try {// w ww.j a v  a2  s .c om
        if (license == null)
            this.license = NuanceCloudLicense.read();
        else
            this.license = license;
        httpclient = getHttpClient();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.addhen.smssync.net.MainHttpClient.java

public MainHttpClient(String url, Context context) {

    this.url = url;
    this.context = context;
    this.params = new ArrayList<NameValuePair>();
    this.headers = new HashMap<String, String>();

    // default to GET
    this.method = "GET";
    request = new HttpGet(url);

    httpParameters = new BasicHttpParams();
    httpParameters.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    httpParameters.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));

    httpParameters.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, "utf8");
    // Set the timeout in milliseconds until a connection is established.
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

    // in milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    SchemeRegistry schemeRegistry = new SchemeRegistry();

    // http scheme
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // https scheme
    try {/*  w w w  . j a  va2 s  .  c  o m*/
        schemeRegistry.register(new Scheme("https", new TrustedSocketFactory(url, false), 443));
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParameters, schemeRegistry);

    httpClient = new DefaultHttpClient(manager, httpParameters);

    // support basic auth header
    try {
        URI uri = new URI(url);
        String userInfo = uri.getUserInfo();
        if (userInfo != null) {
            setHeader("Authorization", "Basic " + base64Encode(userInfo));
        }
    } catch (URISyntaxException e) {
        debug(e);
    }

    // add user-agent header
    try {
        final String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(),
                0).versionName;
        // Add version name to user agent
        userAgent = new StringBuilder("SMSSync-Android/");
        userAgent.append("v");
        userAgent.append(versionName);
        setHeader("User-Agent", userAgent.toString());
    } catch (NameNotFoundException e) {
        debug(e);
    }
}

From source file:org.addhen.smssync.net.BaseHttpClient.java

public BaseHttpClient(String url, Context context) {

    this.url = url;
    this.context = context;
    this.params = new ArrayList<>();
    this.headers = new HashMap<>();

    // default to GET
    this.method = HttpMethod.GET;
    request = new HttpGet(url);

    httpParameters = new BasicHttpParams();
    httpParameters.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    httpParameters.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));

    httpParameters.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, "utf8");
    // Set the timeout in milliseconds until a connection is established.
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

    // in milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    SchemeRegistry schemeRegistry = new SchemeRegistry();

    // http scheme
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // https scheme
    try {/*from   w  ww .  j ava 2s  . co m*/
        schemeRegistry.register(new Scheme("https", new TrustedSocketFactory(url, false), 443));
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParameters, schemeRegistry);

    httpClient = new DefaultHttpClient(manager, httpParameters);

    // support basic auth header
    try {
        URI uri = new URI(url);
        String userInfo = uri.getUserInfo();
        if (userInfo != null) {
            setHeader("Authorization", "Basic " + base64Encode(userInfo));
        }
    } catch (URISyntaxException e) {
        debug(e);
    }

    // add user-agent header
    try {
        final String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(),
                0).versionName;
        // Add version name to user agent
        userAgent = new StringBuilder("SMSSync-Android/");
        userAgent.append("v");
        userAgent.append(versionName);
        setHeader("User-Agent", userAgent.toString());
    } catch (NameNotFoundException e) {
        debug(e);
    }
}

From source file:foam.littlej.android.app.net.MainHttpClient.java

public MainHttpClient(Context context) {
    this.context = context;
    httpParameters = new BasicHttpParams();
    httpParameters.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    httpParameters.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));

    httpParameters.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, "utf8");

    // Set the timeout in milliseconds until a connection is established.
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

    // in milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    SchemeRegistry schemeRegistry = new SchemeRegistry();

    // http scheme
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // https scheme
    try {//from   w ww  .  j a v a  2 s  .co  m
        schemeRegistry.register(new Scheme("https", new TrustedSocketFactory(Preferences.domain, false), 443));
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParameters, schemeRegistry),
            httpParameters);
    httpClient.setParams(httpParameters);

}

From source file:fr.univsavoie.ltp.client.map.Session.java

/**
 * Procdure qui s'authentifie sur le serveur REST avec les donnes utilisateurs de faon scuris (protocole HTTPS).
 * Appeler secureAuth() avant chaque nouvelles requtes HTTP (get, post, ...)
 *//*from   w  ww  . j av  a  2 s .c  o m*/
private void secureAuth() {
    try {
        // Instance de SharedPreferences pour lire les donnes dans un fichier
        SharedPreferences myPrefs = activity.getSharedPreferences("UserPrefs", activity.MODE_WORLD_READABLE);
        String login = myPrefs.getString("Login", null);
        String password = myPrefs.getString("Password", null);

        HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                if (authState.getAuthScheme() == null) {
                    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    Credentials creds = credsProvider.getCredentials(authScope);
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }
        };

        // Setup a custom SSL Factory object which simply ignore the certificates validation and accept all type of self signed certificates
        SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null);
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

        // Register the HTTP and HTTPS Protocols. For HTTPS, register our custom SSL Factory object.
        SchemeRegistry registry = new SchemeRegistry();
        // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sslFactory, 443));

        // Create a new connection manager using the newly created registry and then create a new HTTP client using this connection manager
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        httpClient = new DefaultHttpClient(ccm, params);

        CredentialsProvider authCred = new BasicCredentialsProvider();
        Credentials creds = new UsernamePasswordCredentials(login, password);
        authCred.setCredentials(AuthScope.ANY, creds);

        httpClient.addRequestInterceptor(preemptiveAuth, 0);
        httpClient.setCredentialsProvider(authCred);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
}