Search in sources :

Example 56 with Scheme

use of org.apache.http.conn.scheme.Scheme in project cloudstack by apache.

the class HypervDirectConnectResource method postHttpRequest.

public static String postHttpRequest(final String jsonCmd, final URI agentUri) {
    // 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 = null;
    final TrustStrategy easyStrategy = new TrustStrategy() {

        @Override
        public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
            return true;
        }
    };
    try {
        final SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_AGENT_PORT, sf));
        final ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (final KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final 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 {
        final HttpPost request = new HttpPost(agentUri);
        // JSON encode command
        // Assumes command sits comfortably in a string, i.e. not used for
        // large data transfers
        final StringEntity cmdJson = new StringEntity(jsonCmd);
        request.addHeader("content-type", "application/json");
        request.setEntity(cmdJson);
        s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage);
        final HttpResponse response = httpClient.execute(request);
        // Unsupported commands will not route.
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            final String errMsg = "Failed to send : HTTP error code : " + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            final String unsupportMsg = "Unsupported command " + agentUri.getPath() + ".  Are you sure you got the right type of" + " server?";
            final Answer ans = new UnsupportedAnswer(null, unsupportMsg);
            s_logger.error(ans);
            result = s_gson.toJson(new Answer[] { ans });
        } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            final String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            return null;
        } else {
            result = EntityUtils.toString(response.getEntity());
            final String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
            s_logger.debug("POST response is " + logResult);
        }
    } catch (final ClientProtocolException protocolEx) {
        // Problem with HTTP message exchange
        s_logger.error(protocolEx);
    } catch (final IOException connEx) {
        // Problem with underlying communications
        s_logger.error(connEx);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) HttpResponse(org.apache.http.HttpResponse) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyManagementException(java.security.KeyManagementException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) UnsupportedAnswer(com.cloud.agent.api.UnsupportedAnswer) CheckSshAnswer(com.cloud.agent.api.check.CheckSshAnswer) GetDomRVersionAnswer(com.cloud.agent.api.GetDomRVersionAnswer) CheckS2SVpnConnectionsAnswer(com.cloud.agent.api.CheckS2SVpnConnectionsAnswer) SetPortForwardingRulesAnswer(com.cloud.agent.api.routing.SetPortForwardingRulesAnswer) SetSourceNatAnswer(com.cloud.agent.api.routing.SetSourceNatAnswer) PlugNicAnswer(com.cloud.agent.api.PlugNicAnswer) GetVmConfigAnswer(com.cloud.agent.api.GetVmConfigAnswer) NetworkUsageAnswer(com.cloud.agent.api.NetworkUsageAnswer) Answer(com.cloud.agent.api.Answer) UnPlugNicAnswer(com.cloud.agent.api.UnPlugNicAnswer) SetStaticNatRulesAnswer(com.cloud.agent.api.routing.SetStaticNatRulesAnswer) IpAssocAnswer(com.cloud.agent.api.routing.IpAssocAnswer) SetFirewallRulesAnswer(com.cloud.agent.api.routing.SetFirewallRulesAnswer) CheckRouterAnswer(com.cloud.agent.api.CheckRouterAnswer) SetStaticRouteAnswer(com.cloud.agent.api.routing.SetStaticRouteAnswer) UnsupportedAnswer(com.cloud.agent.api.UnsupportedAnswer) UnrecoverableKeyException(java.security.UnrecoverableKeyException) HttpClient(org.apache.http.client.HttpClient) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 57 with Scheme

use of org.apache.http.conn.scheme.Scheme in project cloudstack by apache.

the class HttpClientWrapper method wrapClient.

public static HttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLUtils.getSSLContext();
        X509TrustManager tm = new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String string, SSLSocket ssls) throws IOException {
            }

            @Override
            public void verify(String string, X509Certificate xc) throws SSLException {
            }

            @Override
            public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) SSLSocket(javax.net.ssl.SSLSocket) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) X509Certificate(java.security.cert.X509Certificate) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) X509TrustManager(javax.net.ssl.X509TrustManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 58 with Scheme

use of org.apache.http.conn.scheme.Scheme in project cloudstack by apache.

the class NexentaNmsClient method getHttpsClient.

protected DefaultHttpClient getHttpsClient() {
    try {
        SSLContext sslContext = SSLUtils.getSSLContext();
        X509TrustManager tm = new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        sslContext.init(null, new TrustManager[] { tm }, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", nmsUrl.getPort(), socketFactory));
        BasicClientConnectionManager mgr = new BasicClientConnectionManager(registry);
        return new DefaultHttpClient(mgr);
    } catch (NoSuchAlgorithmException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (KeyManagementException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    }
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyManagementException(java.security.KeyManagementException) X509TrustManager(javax.net.ssl.X509TrustManager) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 59 with Scheme

use of org.apache.http.conn.scheme.Scheme in project platform_external_apache-http by android.

the class AndroidHttpClient method newInstance.

/**
     * Create a new HttpClient with reasonable defaults (which you can update).
     *
     * @param userAgent to report in your HTTP requests
     * @param context to use for caching SSL sessions (may be null for no caching)
     * @return AndroidHttpClient for you to use for all your requests.
     */
public static AndroidHttpClient newInstance(String userAgent, Context context) {
    HttpParams params = new BasicHttpParams();
    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);
    // Use a session cache for SSL sockets
    SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);
    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLCertificateSocketFactory.getHttpSocketFactory(SOCKET_OPERATION_TIMEOUT, sessionCache), 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSessionCache(android.net.SSLSessionCache) BasicHttpParams(org.apache.http.params.BasicHttpParams) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager)

Example 60 with Scheme

use of org.apache.http.conn.scheme.Scheme in project cdap by caskdata.

the class ExternalLDAPAuthenticationServerSSLTest method getHTTPClient.

@Override
protected HttpClient getHTTPClient() throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {

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

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
        //
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {
        //
        }
    } }, new SecureRandom());
    SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    Scheme httpsScheme = new Scheme("https", getAuthServerPort(), sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    // apache HttpClient version >4.2 should use BasicClientConnectionManager
    ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
    return new DefaultHttpClient(cm);
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) X509TrustManager(javax.net.ssl.X509TrustManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Aggregations

Scheme (org.apache.http.conn.scheme.Scheme)104 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)64 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)54 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)41 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)40 BasicHttpParams (org.apache.http.params.BasicHttpParams)33 HttpParams (org.apache.http.params.HttpParams)31 ThreadSafeClientConnManager (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)30 HttpClient (org.apache.http.client.HttpClient)19 AllowAllHostnameVerifier (org.apache.http.conn.ssl.AllowAllHostnameVerifier)17 SSLContext (javax.net.ssl.SSLContext)16 HttpResponse (org.apache.http.HttpResponse)15 IOException (java.io.IOException)13 CertificateException (java.security.cert.CertificateException)13 HttpHost (org.apache.http.HttpHost)13 MockResponse (com.google.mockwebserver.MockResponse)12 RecordedRequest (com.google.mockwebserver.RecordedRequest)12 TestSSLContext (libcore.javax.net.ssl.TestSSLContext)12 HttpGet (org.apache.http.client.methods.HttpGet)12 InetAddress (java.net.InetAddress)9