Example usage for javax.net.ssl SSLContext init

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

Introduction

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

Prototype

public final void init(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws KeyManagementException 

Source Link

Document

Initializes this context.

Usage

From source file:Main.java

@SuppressWarnings("resource")
public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) {
    Logd(TAG, "Starting post...");
    String html = "";
    Boolean cont = true;//from   w  w w .j a  v  a2  s .  c o m
    URL url = null;
    try {
        url = new URL(targetUrl);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Invalid url: " + targetUrl);
        cont = false;
        throw new IllegalArgumentException("Invalid url: " + targetUrl);
    }
    if (cont) {
        if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) {
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        } else {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }
            } };
            // Install the all-trusting trust manager
            SSLContext sc;
            try {
                sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                // Create all-trusting host name verifier
                HostnameVerifier allHostsValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                };
                // Install the all-trusting host verifier
                HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            } catch (NoSuchAlgorithmException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            } catch (KeyManagementException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            }
        }
        Logd(TAG, "Filename: " + file);
        Logd(TAG, "URL: " + targetUrl);
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        String pathToOurFile = file;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024;
        try {
            connection = (HttpURLConnection) url.openConnection();
            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header)
            //connection.setChunkedStreamingMode(1024);
            // Enable POST method
            connection.setRequestMethod("POST");
            setBasicAuthentication(connection, url);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            outputStream = new DataOutputStream(connection.getOutputStream());
            //outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> param = iterator.next();
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\""
                        + lineEnd + lineEnd);
                outputStream.write(param.getValue().getBytes("UTF-8"));
                outputStream.writeBytes(lineEnd);
            }
            String connstr = null;
            if (!file.equals("")) {
                FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\""
                        + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    while (bytesRead > 0) {
                        try {
                            outputStream.write(buffer, 0, bufferSize);
                        } catch (OutOfMemoryError e) {
                            e.printStackTrace();
                            html = "Error: outofmemoryerror";
                            return html;
                        }
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
                fileInputStream.close();
            } else if (data != null) {
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = data.length;
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    outputStream.write(data, 0, data.length);
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    html = "Error: outofmemoryerror";
                    return html;
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
            }
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();
            Logd(TAG, "Server Response Code " + serverResponseCode);
            Logd(TAG, "Server Response Message: " + serverResponseMessage);
            if (serverResponseCode == 200) {
                InputStreamReader in = new InputStreamReader(connection.getInputStream());
                BufferedReader br = new BufferedReader(in);
                String decodedString;
                while ((decodedString = br.readLine()) != null) {
                    html += decodedString;
                }
                in.close();
            }
            outputStream.flush();
            outputStream.close();
            outputStream = null;
        } catch (Exception ex) {
            // Exception handling
            html = "Error: Unknown error";
            Logd(TAG, "Send file Exception: " + ex.getMessage());
        }
    }
    if (html.startsWith("success:"))
        Logd(TAG, "Server returned: success:HIDDEN");
    else
        Logd(TAG, "Server returned: " + html);
    return html;
}

From source file:com.thejoshwa.ultrasonic.androidapp.service.ssl.SSLSocketFactory.java

private static SSLContext createSSLContext(String algorithm, final KeyStore keystore,
        final String keystorePassword, final KeyStore truststore, final SecureRandom random,
        final TrustStrategy trustStrategy)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;//from   w w w .  j a v a 2 s  .  co m
    }
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null);
    KeyManager[] keymanagers = kmfactory.getKeyManagers();
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    if (trustmanagers != null && trustStrategy != null) {
        for (int i = 0; i < trustmanagers.length; i++) {
            TrustManager tm = trustmanagers[i];
            if (tm instanceof X509TrustManager) {
                trustmanagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy);
            }
        }
    }

    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keymanagers, trustmanagers, random);
    return sslcontext;
}

From source file:com.amazonaws.http.HttpClientFactory.java

/**
 * @see SSLContexts#createDefault()//from w ww.  ja  va  2s . c  o m
 */
public static SSLContext createSSLContext(ClientConfiguration config) throws SSLInitializationException {
    try {
        final SSLContext sslcontext = SSLContext.getInstance("TLS");
        // http://download.java.net/jdk9/docs/technotes/guides/security/jsse/JSSERefGuide.html
        sslcontext.init(null, null, config.getSecureRandom());
        return sslcontext;
    } catch (final NoSuchAlgorithmException ex) {
        throw new SSLInitializationException(ex.getMessage(), ex);
    } catch (final KeyManagementException ex) {
        throw new SSLInitializationException(ex.getMessage(), ex);
    }
}

From source file:com.glaf.core.util.http.HttpUtils.java

/**
 * ?https?//w  ww  . j a va  2s  .c om
 * 
 * @param requestUrl
 *            ?
 * @param method
 *            ?GET?POST
 * @param content
 *            ???
 * @return
 */
public static String doRequest(String requestUrl, String method, String content, boolean isSSL) {
    log.debug("requestUrl:" + requestUrl);
    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    InputStreamReader inputStreamReader = null;
    StringBuffer buffer = new StringBuffer();
    try {
        URL url = new URL(requestUrl);
        conn = (HttpsURLConnection) url.openConnection();
        if (isSSL) {
            // SSLContext??
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // SSLContextSSLSocketFactory
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            conn.setSSLSocketFactory(ssf);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // ?GET/POST
        conn.setRequestMethod(method);
        if ("GET".equalsIgnoreCase(method)) {
            conn.connect();
        }

        // ????
        if (StringUtils.isNotEmpty(content)) {
            OutputStream outputStream = conn.getOutputStream();
            // ????
            outputStream.write(content.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
        }

        // ???
        inputStream = conn.getInputStream();
        inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        log.debug("response:" + buffer.toString());

    } catch (ConnectException ce) {
        ce.printStackTrace();
        log.error(" http server connection timed out.");
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("http request error:{}", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(inputStreamReader);
        if (conn != null) {
            conn.disconnect();
        }
    }
    return buffer.toString();
}

From source file:org.wso2.bam.integration.tests.reciever.RESTAPITestCase.java

@BeforeClass(groups = { "wso2.bam" })
private static void init() {

    DATA_RECEIVER = "/datareceiver/1.0.0";

    //        host = FrameworkSettings.HOST_NAME;
    //        httpsPort = Integer.parseInt(FrameworkSettings.HTTPS_PORT);

    restAppParentURL = "https://" + host + ":" + httpsPort + DATA_RECEIVER;
    streamsURL = restAppParentURL + "/streams";

    streamURL = restAppParentURL + "/stream";
    stockQuoteVersion1URL = streamURL + "/stockquote.stream/1.0.2/";

    stockQuoteVersion2URL = streamURL + "/stockquote.stream.2/2.0.0";

    stockQuoteVersion3URL = streamURL + "/labit.stream/0.0.3";
    stockQuoteVersion4URL = streamURL + "/eu.ima.event.stream/1.2.0";
    stockQuoteVersion5URL = streamURL + "/eu.ima.event.stream.2/1.3.0";

    try {//from   w ww.j  av  a2s .co  m
        events1 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events1.json"));
        events2 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events2.json"));
        events3 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events3.json"));
        events4 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events4.json"));
        events5 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/events5.json"));

        streamdefn1 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn1.json"));
        streamdefn2 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn2.json"));
        streamdefn3 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn3.json"));
        streamdefn4 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn4.json"));
        streamdefn5 = IOUtils
                .toString(RESTAPITestCase.class.getClassLoader().getResourceAsStream("rest/streamdefn5.json"));

        TrustManager easyTrustManager = new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {
            }

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

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", sf, httpsPort);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "utf-8");
        params.setBooleanParameter("http.protocol.expect-continue", false);

        client = new DefaultHttpClient(params);
        client.getConnectionManager().getSchemeRegistry().register(httpsScheme);

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}

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

@SuppressWarnings("deprecation")
private static HttpClient getHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
    // Standard HTTP parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, false);
    // Initialize the HTTP client
    HttpClient httpclient = new DefaultHttpClient(params);

    // Initialize/setup SSL
    TrustManager easyTrustManager = new X509TrustManager() {
        @Override//from  www .j  a  va2 s.  c o m
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
        }

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

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme sch = new Scheme("https", sf, 443);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);

    // Return the initialized instance of our httpclient
    return httpclient;
}

From source file:ch.admin.vbs.cube.core.webservice.CubeSSLSocketFactory.java

/**
 * Create a new SSL socket factory.//from  w  ww  .  j  av a  2  s . c o  m
 * 
 * @param keyStoreBuilder
 *            the key store builder
 * @param trustStore
 *            the trust store
 * @param checkRevocation
 *            <code>true</code> if certificate revocations should be
 *            checked, else <code>false</code>
 * @throws WebServiceException
 *             if the creation failed
 */
public static SSLSocketFactory newSSLSocketFactory(KeyStore.Builder keyStoreBuilder, KeyStore trustStore,
        boolean checkRevocation) throws WebServiceException {
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance("NewSunX509");
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create key manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    KeyStoreBuilderParameters keyStoreBuilderParameters = new KeyStoreBuilderParameters(keyStoreBuilder);
    try {
        keyManagerFactory.init(keyStoreBuilderParameters);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "Unable to initialize key manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    TrustManagerFactory trustManagerFactory;
    try {
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create trust manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    PKIXBuilderParameters pkixBuilderParameters;
    try {
        pkixBuilderParameters = new PKIXBuilderParameters(trustStore, null);
    } catch (KeyStoreException e) {
        String message = "The trust store is not initialized";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "The trust store does not contain any trusted certificate";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    } catch (NullPointerException e) {
        String message = "The trust store is null";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    pkixBuilderParameters.setRevocationEnabled(checkRevocation);
    CertPathTrustManagerParameters certPathTrustManagerParameters = new CertPathTrustManagerParameters(
            pkixBuilderParameters);
    try {
        trustManagerFactory.init(certPathTrustManagerParameters);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "Unable to initialize trust manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create SSL context";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    try {
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    } catch (KeyManagementException e) {
        String message = "Unable to initialize SSL context";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    return sslSocketFactory;
}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception {
    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;
        }//from ww w.  j a  va 2 s.  c  o m

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

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

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String arg0) {
                    // TODO Auto-generated method stub
                    return super.isRedirectable(arg0);
                }

                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    // TODO Auto-generated method stub
                    return super.isRedirected(request, response, context);
                }
            }).setDefaultCookieStore(new BasicCookieStore())
            .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0")
            .build();

    Executor exec = Executor.newInstance(httpclient);

    URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html");

    String fullURL = ub.build().toASCIIString();
    Request req = HttpUtils.get(fullURL, sp);
    HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    String tgtID = readData(exec, req, monitor);
    String action = getFormAction(tgtID);
    if (action != null) {
        action = action.replaceFirst("/", "");
        int indx = action.indexOf(";jsession");
        if (indx >= 0)
            action = action.substring(0, indx);
    } else
        action = "cas/login";
    String url = srv.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub = new URIBuilder(url + action);
    //
    fullURL = ub.build().toASCIIString();
    req = HttpUtils.get(fullURL, sp);
    proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    tgtID = readData(exec, req, monitor);
    action = getFormAction(tgtID);
    action = action.replaceFirst("/", "");

    ub = new URIBuilder(url + action);
    Map<String, String> map = getInputs(tgtID);
    Form form = Form.form();
    for (String key : map.keySet()) {
        if (key.equals("btn-reset"))
            continue;
        else if (key.equals("username")) {
            form.add(key, srv.getUser());
            continue;
        } else if (key.equals("password")) {
            form.add(key, Pass.getPass(srv.getPassword()));
            continue;
        }
        form.add(key, map.get(key));
    }
    //
    req = HttpUtils.post(ub.build().toASCIIString(), form, sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // Header header = null;
    readData(exec, req, monitor);
    // for (Header h : headers) {
    // for (HeaderElement he : h.getElements()) {
    // if (he.getName().equals("CASTGC")) {
    // header = new BasicHeader("Cookie", h.getValue());
    // break;
    // }
    // }
    // }
    ub = new URIBuilder(url + action);
    url = sp.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub.addParameter("service", url + "j_spring_security_check");

    req = HttpUtils.get(ub.build().toASCIIString(), sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // req.addHeader("Accept",
    // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value");
    req.addHeader("Referrer", sp.getUrl());
    // req.addHeader(header);
    String html = readData(exec, req, monitor);
    Matcher matcher = ahrefPattern.matcher(html);
    while (matcher.find()) {
        Map<String, String> attributes = parseAttributes(matcher.group(1));
        String v = attributes.get("href");
        int ind = v.indexOf("ticket=");
        if (ind > 0) {
            return v.substring(ind + "ticket=".length());
        }
    }
    return null;
}

From source file:it.zero11.acme.Acme.java

private static SSLContext getTrustAllCertificateSSLContext()
        throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/* w w  w  . ja  v  a  2s  .c o  m*/
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

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

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

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new SecureRandom());
    return sc;
}

From source file:com.dh.perfectoffer.event.framework.net.network.NetworkConnectionImpl.java

private static SSLSocketFactory getAllHostsValidSocketFactory()
        throws NoSuchAlgorithmException, KeyManagementException {
    if (sAllHostsValidSocketFactory == null) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }/*from w  w w  .  j ava 2s .c o  m*/

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

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

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        sAllHostsValidSocketFactory = sc.getSocketFactory();
    }

    return sAllHostsValidSocketFactory;
}