Example usage for org.apache.http.conn.ssl SSLSocketFactory setHostnameVerifier

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory setHostnameVerifier

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLSocketFactory setHostnameVerifier.

Prototype

public void setHostnameVerifier(final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:com.nookdevs.library.FictionwiseBooks.java

private boolean authenticate() {
    String url = AUTH_URL;
    try {//from   ww  w .  j a  v a2s.c o  m
        nookLib.waitForNetwork(lock);
        SSLSocketFactory factory = SSLSocketFactory.getSocketFactory();
        X509HostnameVerifier orgVerifier = factory.getHostnameVerifier();
        factory.setHostnameVerifier(new AllowAllHostnameVerifier());
        HttpPost request = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("loginid", m_User));
        nvps.add(new BasicNameValuePair("password", m_Pass));
        nvps.add(new BasicNameValuePair("login", "Login"));
        request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse response = httpClient.execute(request);
        m_BookShelfHtml = EntityUtils.toString(response.getEntity());
        factory.setHostnameVerifier(orgVerifier);
        m_Auth = true;
        return true;
    } catch (Exception ex) {
        Log.e("FictionwiseBooks", "exception during authentication", ex);
        return false;
    }
}

From source file:com.waltz3d.common.httpclient.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from   w w  w.  j ava2s  .c om*/
 */
public AsyncHttpClient() {

    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    SSLSocketFactory sf = null;
    try {
        sf = new SSLSocketFactoryEx(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    BasicHttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setUseExpectContinue(httpParams, false);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", sf, 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    //      threadPool = new ThreadPoolExecutor(1, 30, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:com.naryx.tagfusion.cfm.http.cfHttpConnection.java

private DefaultHttpClient getHttpClient(File pKeyFile, String pKeyPassword)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    InputStream keyInput = null;//from w  w w.j  a  v  a2  s  . c  o m
    try {
        keyInput = new FileInputStream(pKeyFile);
        keyStore.load(keyInput, pKeyPassword.toCharArray());
    } finally {
        if (keyInput != null)
            try {
                keyInput.close();
            } catch (IOException ignored) {
            }
    }

    keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());

    SSLSocketFactory sf = new SSLSocketFactory(keyStore, pKeyPassword);
    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);
}

From source file:com.pyj.http.AsyncHttpClient.java

private SSLSocketFactory getSSLSocketFactory() {
    SSLSocketFactory sf = null;
    try {// w  ww  . j  ava 2 s .  c om
        KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
        store.load(null, null);
        sf = new SSLSocketFactoryEx(store);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // ??
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return sf;
}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * Initializes the HTTPs connection//from   w w  w  .  j av  a 2s .  c om
 * 
 * @param sslPort
 *            the number of the port the server should be listening for
 *            SSL/TLS connections
 */
public void InitializeSecure(int sslPort) {
    if (sslPort != -1) {
        SSLSocketFactory sslf = null;
        SSLSocket s = null;
        port = sslPort;
        try {
            // notifyOfProggress(false);
            KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
            trusted.load(null, null);

            sslf = new MySSLSocketFactory(trusted);
            Log.w("Android mobile voting", "1");
            sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Log.w("Android mobile voting", "2");
            BasicHttpParams params = new BasicHttpParams();
            Log.w("Android mobile voting", "3");
            HttpConnectionParams.setConnectionTimeout(params, 500);
            Log.w("Android mobile voting", "4");
            s = (SSLSocket) sslf.connectSocket(sslf.createSocket(), server.getAddress(), sslPort, null, 0,
                    params);
            if (exc) {
                SSLSession ssls = null;
                ssls = s.getSession();
                final javax.security.cert.X509Certificate[] x = ssls.getPeerCertificateChain();

                for (int i = 0; i < x.length; i++) {

                    parent.mHandler.post(new Runnable() {

                        @Override
                        public void run() {

                            try {
                                parent.askForTrust(getThumbPrint(x[0]), instance);
                            } catch (NoSuchAlgorithmException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (CertificateEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (final Exception ex) {
                                parent.mHandler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        parent.showToast(ex.toString());

                                    }

                                });
                                Log.w("Android Mobile Voting", "400 Error");
                                parent.finish();
                            }

                        }
                    });

                }

            }

            s.startHandshake();

            Scheme https = new Scheme("https", sslf, sslPort);

            schemeRegistry.register(https);
            usingScheme = "https";
            port = sslPort;
            if (!exc)
                retrieveQuestions();
        } catch (final Exception ex) {
            parent.mHandler.post(new Runnable() {

                @Override
                public void run() {
                    parent.showToast(ex.toString());

                }

            });
            // Log.w("Android Mobile Voting", "400 Error");
            parent.finish();

        }
    } else {
        parent.mHandler.post(new Runnable() {

            @Override
            public void run() {
                parent.showNoSSLDialog(instance);

            }

        });
    }

}

From source file:com.example.wechatsample.library.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from w w w.  j  av a 2s. c  o m
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));
    ThreadSafeClientConnManager cm = null;
    try {
        //  https?
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // ??

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", sf, 443));
        schemeRegistry.register(new Scheme("https", sf, 8443));
        cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Uploads the data, returns the HTTP result code*/
public int performUpload(HttpConnectionParameter connectionParameter, AS2Message message, Partner sender,
        Partner receiver, URL receiptURL) {
    String ediintFeatures = "multiple-attachments, CEM";
    //set the http connection/routing/protocol parameter
    HttpParams httpParams = new BasicHttpParams();
    if (connectionParameter.getConnectionTimeoutMillis() != -1) {
        HttpConnectionParams.setConnectionTimeout(httpParams, connectionParameter.getConnectionTimeoutMillis());
    }/*from  w  w w.  j  a va  2 s .  co m*/
    if (connectionParameter.getSoTimeoutMillis() != -1) {
        HttpConnectionParams.setSoTimeout(httpParams, connectionParameter.getSoTimeoutMillis());
    }
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, connectionParameter.isStaleConnectionCheck());
    if (connectionParameter.getHttpProtocolVersion() == null) {
        //default settings: HTTP 1.1
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_0)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_0);
    } else if (connectionParameter.getHttpProtocolVersion().equals(HttpConnectionParameter.HTTP_1_1)) {
        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    }
    HttpProtocolParams.setUseExpectContinue(httpParams, connectionParameter.isUseExpectContinue());
    HttpProtocolParams.setUserAgent(httpParams, connectionParameter.getUserAgent());
    if (connectionParameter.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpParams, connectionParameter.getLocalAddress());
    }
    int status = -1;
    HttpPost filePost = null;
    DefaultHttpClient httpClient = null;
    try {
        ClientConnectionManager clientConnectionManager = this.createClientConnectionManager(httpParams);
        httpClient = new DefaultHttpClient(clientConnectionManager, httpParams);
        //some ssl implementations have problems with a session/connection reuse
        httpClient.setReuseStrategy(new NoConnectionReuseStrategy());
        //disable SSL hostname verification. Do not confuse this with SSL trust verification!
        SSLSocketFactory sslFactory = (SSLSocketFactory) httpClient.getConnectionManager().getSchemeRegistry()
                .get("https").getSocketFactory();
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        //determine the receipt URL if it is not set
        if (receiptURL == null) {
            //async MDN requested?
            if (message.isMDN()) {
                if (this.runtimeConnection == null) {
                    throw new IllegalArgumentException(
                            "MessageHTTPUploader.performUpload(): A MDN receipt URL is not set, unable to determine where to send the MDN");
                }
                MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection,
                        this.runtimeConnection);
                AS2MessageInfo relatedMessageInfo = messageAccess
                        .getLastMessageEntry(((AS2MDNInfo) message.getAS2Info()).getRelatedMessageId());
                receiptURL = new URL(relatedMessageInfo.getAsyncMDNURL());
            } else {
                receiptURL = new URL(receiver.getURL());
            }
        }
        filePost = new HttpPost(receiptURL.toExternalForm());
        filePost.addHeader("as2-version", "1.2");
        filePost.addHeader("ediint-features", ediintFeatures);
        filePost.addHeader("mime-version", "1.0");
        filePost.addHeader("recipient-address", receiptURL.toExternalForm());
        filePost.addHeader("message-id", "<" + message.getAS2Info().getMessageId() + ">");
        filePost.addHeader("as2-from", AS2Message.escapeFromToHeader(sender.getAS2Identification()));
        filePost.addHeader("as2-to", AS2Message.escapeFromToHeader(receiver.getAS2Identification()));
        String originalFilename = null;
        if (message.getPayloads() != null && message.getPayloads().size() > 0) {
            originalFilename = message.getPayloads().get(0).getOriginalFilename();
        }
        if (originalFilename != null) {
            String subject = this.replace(message.getAS2Info().getSubject(), "${filename}", originalFilename);
            filePost.addHeader("subject", subject);
            //update the message infos subject with the actual content
            if (!message.isMDN()) {
                ((AS2MessageInfo) message.getAS2Info()).setSubject(subject);
                //refresh this in the database if it is requested
                if (this.runtimeConnection != null) {
                    MessageAccessDB access = new MessageAccessDB(this.configConnection, this.runtimeConnection);
                    access.updateSubject((AS2MessageInfo) message.getAS2Info());
                }
            }
        } else {
            filePost.addHeader("subject", message.getAS2Info().getSubject());
        }
        filePost.addHeader("from", sender.getEmail());
        filePost.addHeader("connection", "close, TE");
        //the data header must be always in english locale else there would be special
        //french characters (e.g. 13 dc. 2011 16:28:56 CET) which is not allowed after 
        //RFC 4130           
        DateFormat format = new SimpleDateFormat("EE, dd MMM yyyy HH:mm:ss zz", Locale.US);
        filePost.addHeader("date", format.format(new Date()));
        String contentType = null;
        if (message.getAS2Info().getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            contentType = "application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m";
        } else {
            contentType = message.getContentType();
        }
        filePost.addHeader("content-type", contentType);
        //MDN header, this is always the way for async MDNs
        if (message.isMDN()) {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("sending.mdn.async",
                                new Object[] { message.getAS2Info().getMessageId(), receiptURL }),
                        message.getAS2Info());
            }
            filePost.addHeader("server", message.getAS2Info().getUserAgent());
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            //outbound AS2/CEM message
            if (messageInfo.requestsSyncMDN()) {
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.sync",
                                        new Object[] { messageInfo.getMessageId(), receiver.getURL() }),
                                messageInfo);
                    }
                }
            } else {
                //Message with ASYNC MDN request
                if (this.logger != null) {
                    if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_CEM) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.cem.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    } else if (messageInfo.getMessageType() == AS2Message.MESSAGETYPE_AS2) {
                        this.logger.log(Level.INFO,
                                this.rb.getResourceString("sending.msg.async", new Object[] {
                                        messageInfo.getMessageId(), receiver.getURL(), sender.getMdnURL() }),
                                messageInfo);
                    }
                }
                //The following header indicates that this requests an asnc MDN.
                //When the header "receipt-delivery-option" is present,
                //the header "disposition-notification-to" serves as a request
                //for an asynchronous MDN.
                //The header "receipt-delivery-option" must always be accompanied by
                //the header "disposition-notification-to".
                //When the header "receipt-delivery-option" is not present and the header
                //"disposition-notification-to" is present, the header "disposition-notification-to"
                //serves as a request for a synchronous MDN.
                filePost.addHeader("receipt-delivery-option", sender.getMdnURL());
            }
            filePost.addHeader("disposition-notification-to", sender.getMdnURL());
            //request a signed MDN if this is set up in the partner configuration
            if (receiver.isSignedMDN()) {
                filePost.addHeader("disposition-notification-options",
                        messageInfo.getDispositionNotificationOptions().getHeaderValue());
            }
            if (messageInfo.getSignType() != AS2Message.SIGNATURE_NONE) {
                filePost.addHeader("content-disposition", "attachment; filename=\"smime.p7m\"");
            } else if (messageInfo.getSignType() == AS2Message.SIGNATURE_NONE
                    && message.getAS2Info().getSignType() == AS2Message.ENCRYPTION_NONE) {
                filePost.addHeader("content-disposition",
                        "attachment; filename=\"" + message.getPayload(0).getOriginalFilename() + "\"");
            }
        }
        int port = receiptURL.getPort();
        if (port == -1) {
            port = receiptURL.getDefaultPort();
        }
        filePost.addHeader("host", receiptURL.getHost() + ":" + port);
        InputStream rawDataInputStream = message.getRawDataInputStream();
        InputStreamEntity postEntity = new InputStreamEntity(rawDataInputStream, message.getRawDataSize());
        postEntity.setContentType(contentType);
        filePost.setEntity(postEntity);
        if (connectionParameter.getProxy() != null) {
            this.setProxyToConnection(httpClient, message, connectionParameter.getProxy());
        }
        this.setHTTPAuthentication(httpClient, receiver, message.getAS2Info().isMDN());
        this.updateUploadHttpHeader(filePost, receiver);
        HttpHost targetHost = new HttpHost(receiptURL.getHost(), receiptURL.getPort(),
                receiptURL.getProtocol());
        BasicHttpContext localcontext = new BasicHttpContext();
        // Generate BASIC scheme object and stick it to the local
        // execution context. Without this a HTTP authentication will not be sent
        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        HttpResponse httpResponse = httpClient.execute(targetHost, filePost, localcontext);
        rawDataInputStream.close();
        this.responseData = this.readEntityData(httpResponse);
        if (httpResponse != null) {
            this.responseStatusLine = httpResponse.getStatusLine();
            status = this.responseStatusLine.getStatusCode();
            this.responseHeader = httpResponse.getAllHeaders();
        }
        for (Header singleHeader : filePost.getAllHeaders()) {
            if (singleHeader.getValue() != null) {
                this.requestHeader.setProperty(singleHeader.getName(), singleHeader.getValue());
            }
        }
        //accept all 2xx answers
        //SC_ACCEPTED Status code (202) indicating that a request was accepted for processing, but was not completed.
        //SC_CREATED  Status code (201) indicating the request succeeded and created a new resource on the server.
        //SC_NO_CONTENT Status code (204) indicating that the request succeeded but that there was no new information to return.
        //SC_NON_AUTHORITATIVE_INFORMATION Status code (203) indicating that the meta information presented by the client did not originate from the server.
        //SC_OK Status code (200) indicating the request succeeded normally.
        //SC_RESET_CONTENT Status code (205) indicating that the agent SHOULD reset the document view which caused the request to be sent.
        //SC_PARTIAL_CONTENT Status code (206) indicating that the server has fulfilled the partial GET request for the resource.
        if (status != HttpServletResponse.SC_OK && status != HttpServletResponse.SC_ACCEPTED
                && status != HttpServletResponse.SC_CREATED && status != HttpServletResponse.SC_NO_CONTENT
                && status != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION
                && status != HttpServletResponse.SC_RESET_CONTENT
                && status != HttpServletResponse.SC_PARTIAL_CONTENT) {
            if (this.logger != null) {
                this.logger
                        .severe(this.rb.getResourceString("error.httpupload",
                                new Object[] { message.getAS2Info().getMessageId(),
                                        URLDecoder.decode(
                                                this.responseStatusLine == null ? ""
                                                        : this.responseStatusLine.getReasonPhrase(),
                                                "UTF-8") }));
            }
        }
    } catch (Exception ex) {
        if (this.logger != null) {
            StringBuilder errorMessage = new StringBuilder(message.getAS2Info().getMessageId());
            errorMessage.append(": MessageHTTPUploader.performUpload: [");
            errorMessage.append(ex.getClass().getSimpleName());
            errorMessage.append("]");
            if (ex.getMessage() != null) {
                errorMessage.append(": ").append(ex.getMessage());
            }
            this.logger.log(Level.SEVERE, errorMessage.toString(), message.getAS2Info());
        }
    } finally {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            //shutdown the HTTPClient to release the resources
            httpClient.getConnectionManager().shutdown();
        }
    }
    return (status);
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.HCAPAdapter.java

public SchemeRegistry getHcapProtocolSchemeRegistryForHttpClient(SSLCertificateCallback sslExceptionCallback)
        throws StorageAdapterException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    try {// w  w  w .  java  2 s . co  m
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        // Note: SSLContext.init takes an array of TrustManager instances, so we could in theory
        // provide more than one
        // implementation here.
        TrustManager X509TrustManager = new GetCertsX509TrustManager((HCAPProfile) getProfile(),
                sslExceptionCallback);
        sslcontext.init(null, new TrustManager[] { X509TrustManager }, null);
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslcontext);

        // We are doing this here because we did the verification that would be done if we had
        // set this to
        // STRICT_HOSTNAME_VERIFIER in the init we called above.
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        Scheme https = new Scheme("https", sslSocketFactory, 443);
        schemeRegistry.register(https);

        getAdditionalHcapProtocolSchemeRegistryForHttpClient(schemeRegistry, sslExceptionCallback);

    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    } catch (NoSuchProviderException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    } catch (KeyStoreException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    } catch (KeyManagementException e) {
        LOG.log(Level.INFO, "Unable to initialize SSL for https protocol!", e);
        throw new StorageAdapterException("Unable to initialize SSL for https protocol", e);
    }

    return schemeRegistry;
}

From source file:com.groupon.odo.proxylib.BackupService.java

/**
 * Restore configuration from backup data
 *
 * @param streamData InputStream for configuration to restore
 * @return true if succeeded, false if operation failed
 *//*ww  w  .j  a v a2  s. c  o  m*/
public boolean restoreBackupData(InputStream streamData) {
    // convert stream to string
    java.util.Scanner s = new java.util.Scanner(streamData).useDelimiter("\\A");
    String data = s.hasNext() ? s.next() : "";

    // parse JSON
    ObjectMapper mapper = new ObjectMapper();
    Backup backupData = null;
    try {
        backupData = mapper.readValue(data, Backup.class);
    } catch (Exception e) {
        logger.error("Could not parse input data: {}, {}", e.getClass(), e.getMessage());
        return false;
    }

    // TODO: validate json against a schema for safety

    // GROUPS
    try {
        logger.info("Number of groups: {}", backupData.getGroups().size());

        for (Group group : backupData.getGroups()) {
            // determine if group already exists.. if not then add it
            Integer groupId = PathOverrideService.getInstance().getGroupIdFromName(group.getName());
            if (groupId == null) {
                groupId = PathOverrideService.getInstance().addGroup(group.getName());
            }

            // get all methods from the group.. we are going to remove ones that don't exist in the new configuration
            List<Method> originalMethods = EditService.getInstance().getMethodsFromGroupId(groupId, null);

            for (Method originalMethod : originalMethods) {
                Boolean matchInImportGroup = false;

                int importCount = 0;
                for (Method importMethod : group.getMethods()) {
                    if (originalMethod.getClassName().equals(importMethod.getClassName())
                            && originalMethod.getMethodName().equals(importMethod.getMethodName())) {
                        matchInImportGroup = true;
                        break;
                    }
                    importCount++;
                }

                if (!matchInImportGroup) {
                    // remove it from current database since it is a delta to the current import
                    PathOverrideService.getInstance().removeOverride(originalMethod.getId());
                } else {
                    // remove from import list since it already exists
                    group.getMethods().remove(importCount);
                }
            }

            // add methods to groups
            for (Method method : group.getMethods()) {
                PathOverrideService.getInstance().createOverride(groupId, method.getMethodName(),
                        method.getClassName());
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // PROFILES
    try {
        logger.info("Number of profiles: {}", backupData.getProfiles().size());

        // remove all servers
        // don't care about deltas here.. we'll just recreate them all
        // removed default servers (belong to group id=0)
        ServerRedirectService.getInstance().deleteServerGroup(0);

        for (com.groupon.odo.proxylib.models.backup.Profile profile : backupData.getProfiles()) {
            // see if a profile with this name already exists
            Integer profileId = ProfileService.getInstance().getIdFromName(profile.getName());
            com.groupon.odo.proxylib.models.Profile newProfile;
            if (profileId == null) {
                // create new profile
                newProfile = ProfileService.getInstance().add(profile.getName());
            } else {
                // get the existing profile
                newProfile = ProfileService.getInstance().findProfile(profileId);
            }

            // add new servers
            if (profile.getServers() != null) {
                for (ServerRedirect server : profile.getServers()) {
                    ServerRedirectService.getInstance().addServerRedirect(server.getRegion(),
                            server.getSrcUrl(), server.getDestUrl(), server.getHostHeader(), newProfile.getId(),
                            0);
                }
            }

            // remove all server groups
            for (ServerGroup group : ServerRedirectService.getInstance()
                    .tableServerGroups(newProfile.getId())) {
                ServerRedirectService.getInstance().deleteServerGroup(group.getId());
            }

            // add new server groups
            if (profile.getServerGroups() != null) {
                for (ServerGroup group : profile.getServerGroups()) {
                    int groupId = ServerRedirectService.getInstance().addServerGroup(group.getName(),
                            newProfile.getId());
                    for (ServerRedirect server : group.getServers()) {
                        ServerRedirectService.getInstance().addServerRedirect(server.getRegion(),
                                server.getSrcUrl(), server.getDestUrl(), server.getHostHeader(),
                                newProfile.getId(), groupId);
                    }
                }
            }

            // remove all paths
            // don't care about deltas here.. we'll just recreate them all
            for (EndpointOverride path : PathOverrideService.getInstance().getPaths(newProfile.getId(),
                    Constants.PROFILE_CLIENT_DEFAULT_ID, null)) {
                PathOverrideService.getInstance().removePath(path.getPathId());
            }

            // add new paths
            if (profile.getPaths() != null) {
                for (EndpointOverride path : profile.getPaths()) {
                    int pathId = PathOverrideService.getInstance().addPathnameToProfile(newProfile.getId(),
                            path.getPathName(), path.getPath());

                    PathOverrideService.getInstance().setContentType(pathId, path.getContentType());
                    PathOverrideService.getInstance().setRequestType(pathId, path.getRequestType());
                    PathOverrideService.getInstance().setGlobal(pathId, path.getGlobal());

                    // add groups to path
                    for (String groupName : path.getGroupNames()) {
                        int groupId = PathOverrideService.getInstance().getGroupIdFromName(groupName);
                        PathOverrideService.getInstance().AddGroupByNumber(newProfile.getId(), pathId, groupId);
                    }
                }
            }

            // set active
            ClientService.getInstance().updateActive(newProfile.getId(), Constants.PROFILE_CLIENT_DEFAULT_ID,
                    profile.getActive());
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // SCRIPTS
    try {
        // delete all scripts
        for (Script script : ScriptService.getInstance().getScripts()) {
            ScriptService.getInstance().removeScript(script.getId());
        }

        // add scripts
        for (Script script : backupData.getScripts()) {
            ScriptService.getInstance().addScript(script.getName(), script.getScript());
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // tell http/https proxies to reload plugins
    try {
        org.apache.http.conn.ssl.SSLSocketFactory sslsf = new org.apache.http.conn.ssl.SSLSocketFactory(
                new TrustStrategy() {
                    @Override
                    public boolean isTrusted(final X509Certificate[] chain, String authType)
                            throws CertificateException {
                        // ignore SSL cert issues
                        return true;
                    }
                });
        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        sslsf.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        for (String connectstring : getConnectorStrings("https_proxy")) {
            HttpGet request = new HttpGet(connectstring + "/proxy/reload");

            HttpClient httpClient = new org.apache.http.impl.client.DefaultHttpClient();
            String[] parts = connectstring.split(":");
            httpClient.getConnectionManager().getSchemeRegistry()
                    .register(new org.apache.http.conn.scheme.Scheme("https",
                            Integer.parseInt(parts[parts.length - 1]), sslsf));
            HttpResponse response = httpClient.execute(request);
        }
    } catch (Exception e) {
        e.printStackTrace();
        logger.info("Exception caught during proxy reload.  Things may be in an inconsistent state.");
    }

    // restart plugin service for this process
    PluginManager.destroy();

    return true;
}