Search in sources :

Example 81 with SchemeRegistry

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

the class NetScalerControlCenterResource method postHttpRequest.

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

        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_PORT, sf));
        ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }
    String result = null;
    // TODO: are there timeout settings and worker thread settings to tweak?
    try {
        HttpPost request = new HttpPost(agentUri);
        // JSON encode command
        // Assumes command sits comfortably in a string, i.e. not used for
        // large data transfers
        StringEntity cmdJson = new StringEntity(jsonCmd);
        request.addHeader("content-type", "application/json");
        request.addHeader("Cookie", "SessId=" + sessionID);
        request.setEntity(cmdJson);
        s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage + "SEssion id: " + sessionID);
        HttpResponse response = httpClient.execute(request);
        // Unsupported commands will not route.
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            String errMsg = "Failed : HTTP error code : " + response.getStatusLine().getStatusCode();
            throw new ExecutionException(NccHttpCode.NOT_FOUND);
        } else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) && (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED)) {
            String errMsg = "Command Not Success " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            throw new ExecutionException(NccHttpCode.INTERNAL_ERROR + " " + errMsg);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            // make login request and store new session id
            throw new ExecutionException(NccHttpCode.UNAUTHORIZED);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            // Successfully created the resource in the NCC, Now get the Job ID and send to the response
            result = response.getFirstHeader(NccHttpCode.JOB_ID).getValue();
        } else {
            result = EntityUtils.toString(response.getEntity());
            String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
            s_logger.debug("POST response is " + logResult);
        }
    } catch (ClientProtocolException protocolEx) {
        // Problem with HTTP message exchange
        s_logger.error(protocolEx);
    } catch (IOException connEx) {
        // Problem with underlying communications
        s_logger.error(connEx);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}
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) UnrecoverableKeyException(java.security.UnrecoverableKeyException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) ExecutionException(com.cloud.utils.exception.ExecutionException)

Example 82 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project qi4j-sdk by Qi4j.

the class AbstractSecureJettyTest method beforeSecure.

@Before
public void beforeSecure() throws GeneralSecurityException, IOException {
    // Trust HTTP Client
    KeyStore truststore = KeyStore.getInstance("JCEKS");
    truststore.load(new FileInputStream(TRUSTSTORE_FILE), KS_PASSWORD.toCharArray());
    AllowAllHostnameVerifier verifier = new AllowAllHostnameVerifier();
    DefaultHttpClient trustClient = new DefaultHttpClient();
    SSLSocketFactory trustSslFactory = new SSLSocketFactory(truststore);
    trustSslFactory.setHostnameVerifier(verifier);
    SchemeRegistry trustSchemeRegistry = trustClient.getConnectionManager().getSchemeRegistry();
    trustSchemeRegistry.unregister(HTTPS);
    trustSchemeRegistry.register(new Scheme(HTTPS, HTTPS_PORT, trustSslFactory));
    trustHttpClient = trustClient;
    // Mutual HTTP Client
    KeyStore keystore = KeyStore.getInstance("JCEKS");
    keystore.load(new FileInputStream(CLIENT_KEYSTORE_FILE), KS_PASSWORD.toCharArray());
    DefaultHttpClient mutualClient = new DefaultHttpClient();
    SSLSocketFactory mutualSslFactory = new SSLSocketFactory(keystore, KS_PASSWORD, truststore);
    mutualSslFactory.setHostnameVerifier(verifier);
    SchemeRegistry mutualSchemeRegistry = mutualClient.getConnectionManager().getSchemeRegistry();
    mutualSchemeRegistry.unregister(HTTPS);
    mutualSchemeRegistry.register(new Scheme(HTTPS, HTTPS_PORT, mutualSslFactory));
    mutualHttpClient = mutualClient;
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) Before(org.junit.Before)

Example 83 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project RoboZombie by sahan.

the class ConfigurationService method getDefault.

/**
 * <p>The <i>out-of-the-box</i> configuration for an instance of {@link HttpClient} which will be used for
 * executing all endpoint requests. Below is a detailed description of all configured properties.</p>
 * <br>
 * <ul>
 * <li>
 * <p><b>HttpClient</b></p>
 * <br>
 * <p>It registers two {@link Scheme}s:</p>
 * <br>
 * <ol>
 * 	<li><b>HTTP</b> on port <b>80</b> using sockets from {@link PlainSocketFactory#getSocketFactory}</li>
 * 	<li><b>HTTPS</b> on port <b>443</b> using sockets from {@link SSLSocketFactory#getSocketFactory}</li>
 * </ol>
 *
 * <p>It uses a {@link ThreadSafeClientConnManager} with the following parameters:</p>
 * <br>
 * <ol>
 * 	<li><b>Redirecting:</b> enabled</li>
 * 	<li><b>Connection Timeout:</b> 30 seconds</li>
 * 	<li><b>Socket Timeout:</b> 30 seconds</li>
 * 	<li><b>Socket Buffer Size:</b> 12000 bytes</li>
 * 	<li><b>User-Agent:</b> via <code>System.getProperty("http.agent")</code></li>
 * </ol>
 * </li>
 * </ul>
 * @return the instance of {@link HttpClient} which will be used for request execution
 * <br><br>
 * @since 1.3.0
 */
@Override
public Configuration getDefault() {
    return new Configuration() {

        @Override
        public HttpClient httpClient() {
            try {
                HttpParams params = new BasicHttpParams();
                HttpClientParams.setRedirecting(params, true);
                HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
                HttpConnectionParams.setSoTimeout(params, 30 * 1000);
                HttpConnectionParams.setSocketBufferSize(params, 12000);
                HttpProtocolParams.setUserAgent(params, System.getProperty("http.agent"));
                SchemeRegistry schemeRegistry = new SchemeRegistry();
                schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
                ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
                return new DefaultHttpClient(manager, params);
            } catch (Exception e) {
                throw new ConfigurationFailedException(e);
            }
        }
    };
}
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) Configuration(com.lonepulse.robozombie.proxy.Zombie.Configuration) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicHttpParams(org.apache.http.params.BasicHttpParams) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 84 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project RoboZombie by sahan.

the class ZombieConfig method httpClient.

@Override
public HttpClient httpClient() {
    HttpParams params = new BasicHttpParams();
    // to simulate a socket timeout
    HttpConnectionParams.setSoTimeout(params, 2 * 1000);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
    return new DefaultHttpClient(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) BasicHttpParams(org.apache.http.params.BasicHttpParams) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 85 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project ribbon by Netflix.

the class RestClient method getKeyStore.

public KeyStore getKeyStore() {
    SchemeRegistry registry = httpClient4.getConnectionManager().getSchemeRegistry();
    if (!registry.getSchemeNames().contains("https")) {
        throw new IllegalStateException("Registry does not include an 'https' entry.");
    }
    SchemeSocketFactory awareSocketFactory = httpClient4.getConnectionManager().getSchemeRegistry().getScheme("https").getSchemeSocketFactory();
    if (awareSocketFactory instanceof KeyStoreAwareSocketFactory) {
        return ((KeyStoreAwareSocketFactory) awareSocketFactory).getKeyStore();
    } else {
        throw new IllegalStateException("Cannot extract keystore from scheme socket factory of type: " + awareSocketFactory.getClass().getName());
    }
}
Also used : SchemeSocketFactory(org.apache.http.conn.scheme.SchemeSocketFactory) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) KeyStoreAwareSocketFactory(com.netflix.http4.ssl.KeyStoreAwareSocketFactory)

Aggregations

SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)91 Scheme (org.apache.http.conn.scheme.Scheme)88 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)58 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)50 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)48 BasicHttpParams (org.apache.http.params.BasicHttpParams)35 HttpParams (org.apache.http.params.HttpParams)33 ThreadSafeClientConnManager (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)30 SSLContext (javax.net.ssl.SSLContext)24 IOException (java.io.IOException)22 KeyManagementException (java.security.KeyManagementException)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18 CertificateException (java.security.cert.CertificateException)15 HttpClient (org.apache.http.client.HttpClient)12 BasicClientConnectionManager (org.apache.http.impl.conn.BasicClientConnectionManager)12 PoolingClientConnectionManager (org.apache.http.impl.conn.PoolingClientConnectionManager)12 KeyStoreException (java.security.KeyStoreException)11 UnrecoverableKeyException (java.security.UnrecoverableKeyException)10 X509Certificate (java.security.cert.X509Certificate)10 X509TrustManager (javax.net.ssl.X509TrustManager)9