Search in sources :

Example 6 with PlainConnectionSocketFactory

use of org.apache.http.conn.socket.PlainConnectionSocketFactory in project chassis by Kixeye.

the class HttpTransportTest method testHttpServiceWithJsonWithHTTPSAndHTTP.

@Test
public void testHttpServiceWithJsonWithHTTPSAndHTTP() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");
    properties.put("https.enabled", "true");
    properties.put("https.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("https.hostname", "localhost");
    properties.put("https.selfSigned", "true");
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);
    try {
        context.refresh();
        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);
        SSLContextBuilder builder = SSLContexts.custom();
        builder.loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLContext sslContext = builder.build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

            @Override
            public void verify(String host, SSLSocket ssl) throws IOException {
            }

            @Override
            public void verify(String host, X509Certificate cert) throws SSLException {
            }

            @Override
            public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
            }

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build());
        RestTemplate httpClient = new RestTemplate(requestFactory);
        httpClient.setErrorHandler(new ResponseErrorHandler() {

            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {
            }
        });
        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));
        TestObject response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        response = httpClient.postForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject("more stuff"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        response = httpClient.getForObject(new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        ResponseEntity<ServiceError> error = httpClient.postForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);
        error = httpClient.getForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);
        error = httpClient.getForEntity(new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
        response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        response = httpClient.postForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("stuff"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);
        response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        response = httpClient.getForObject(new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"), TestObject.class);
        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);
        error = httpClient.postForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);
        error = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);
        error = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"), ServiceError.class);
        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) HashMap(java.util.HashMap) ResponseErrorHandler(org.springframework.web.client.ResponseErrorHandler) SSLSocket(javax.net.ssl.SSLSocket) CertificateException(java.security.cert.CertificateException) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLException(javax.net.ssl.SSLException) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) StandardEnvironment(org.springframework.core.env.StandardEnvironment) ServiceError(com.kixeye.chassis.transport.dto.ServiceError) SSLSession(javax.net.ssl.SSLSession) YamlJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.YamlJacksonMessageSerDe) XmlMessageSerDe(com.kixeye.chassis.transport.serde.converter.XmlMessageSerDe) JsonJacksonMessageSerDe(com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe) ProtobufMessageSerDe(com.kixeye.chassis.transport.serde.converter.ProtobufMessageSerDe) MessageSerDe(com.kixeye.chassis.transport.serde.MessageSerDe) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) MapPropertySource(org.springframework.core.env.MapPropertySource) SerDeHttpMessageConverter(com.kixeye.chassis.transport.http.SerDeHttpMessageConverter) RestTemplate(org.springframework.web.client.RestTemplate) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) Test(org.junit.Test)

Example 7 with PlainConnectionSocketFactory

use of org.apache.http.conn.socket.PlainConnectionSocketFactory in project athenz by yahoo.

the class HttpDriver method createConnectionPooling.

protected PoolingHttpClientConnectionManager createConnectionPooling(SSLContext sslContext) {
    if (sslContext == null) {
        return null;
    }
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", new SSLConnectionSocketFactory(sslContext)).register("http", new PlainConnectionSocketFactory()).build();
    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
    // route is host + port.  Since we have only one, set the max and the route the same
    poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPoolPerRoute);
    poolingHttpClientConnectionManager.setMaxTotal(maxPoolTotal);
    return poolingHttpClientConnectionManager;
}
Also used : PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 8 with PlainConnectionSocketFactory

use of org.apache.http.conn.socket.PlainConnectionSocketFactory in project yacy_grid_mcp by yacy.

the class ClientConnection method getConnctionManager.

public static PoolingHttpClientConnectionManager getConnctionManager() {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
    try {
        SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), new TrustAllHostNameVerifier());
        socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()).register("https", trustSelfSignedSocketFactory).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        Data.logger.warn("", e);
    }
    PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ? new PoolingHttpClientConnectionManager(socketFactoryRegistry) : new PoolingHttpClientConnectionManager();
    // twitter specific options
    cm.setMaxTotal(2000);
    cm.setDefaultMaxPerRoute(200);
    return cm;
}
Also used : PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) KeyManagementException(java.security.KeyManagementException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 9 with PlainConnectionSocketFactory

use of org.apache.http.conn.socket.PlainConnectionSocketFactory in project yacy_grid_loader by yacy.

the class ApacheHttpClient method getConnctionManager.

/**
 * get a connection manager
 * @param trustAllCerts allow opportunistic encryption if needed
 * @return
 */
private static HttpClientConnectionManager getConnctionManager() {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
    try {
        SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), new TrustAllHostNameVerifier());
        socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()).register("https", trustSelfSignedSocketFactory).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        Data.logger.warn("", e);
    }
    PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ? new PoolingHttpClientConnectionManager(socketFactoryRegistry) : new PoolingHttpClientConnectionManager();
    // twitter specific options
    cm.setMaxTotal(2000);
    cm.setDefaultMaxPerRoute(200);
    return cm;
}
Also used : PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) KeyManagementException(java.security.KeyManagementException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 10 with PlainConnectionSocketFactory

use of org.apache.http.conn.socket.PlainConnectionSocketFactory in project oxAuth by GluuFederation.

the class ClientUtil method createHttpClient.

/**
 * Creates a special SSLContext using a custom TLS version and a set of ciphers enabled to process SSL connections.
 * @param tlsVersion TLS version, for example TLSv1.2
 * @param ciphers Set of ciphers used to create connections.
 */
public static CloseableHttpClient createHttpClient(String tlsVersion, String[] ciphers) {
    try {
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext, new String[] { tlsVersion }, ciphers, NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectionFactory).register("http", new PlainConnectionSocketFactory()).build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        return HttpClients.custom().setSSLContext(sslContext).setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()).setConnectionManager(cm).build();
    } catch (Exception e) {
        log.error("Error creating HttpClient with a custom TLS version and custom ciphers", e);
        return null;
    }
}
Also used : ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLContext(javax.net.ssl.SSLContext) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Aggregations

ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)10 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)10 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)10 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)9 SSLContext (javax.net.ssl.SSLContext)5 IOException (java.io.IOException)4 TrustSelfSignedStrategy (org.apache.http.conn.ssl.TrustSelfSignedStrategy)4 KeyManagementException (java.security.KeyManagementException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 CertificateException (java.security.cert.CertificateException)2 X509Certificate (java.security.cert.X509Certificate)2 HostnameVerifier (javax.net.ssl.HostnameVerifier)2 SSLContextBuilder (org.apache.http.conn.ssl.SSLContextBuilder)2 SSLContextBuilder (org.apache.http.ssl.SSLContextBuilder)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ServiceError (com.kixeye.chassis.transport.dto.ServiceError)1 SerDeHttpMessageConverter (com.kixeye.chassis.transport.http.SerDeHttpMessageConverter)1 MessageSerDe (com.kixeye.chassis.transport.serde.MessageSerDe)1 JsonJacksonMessageSerDe (com.kixeye.chassis.transport.serde.converter.JsonJacksonMessageSerDe)1