Search in sources :

Example 1 with HttpClientConnectionManager

use of org.apache.http.conn.HttpClientConnectionManager in project jersey by jersey.

the class HelloWorldTest method _testConnectionPoolSharing.

public void _testConnectionPoolSharing(final boolean sharingEnabled) throws Exception {
    final HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    final ClientConfig cc = new ClientConfig();
    cc.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
    cc.property(ApacheClientProperties.CONNECTION_MANAGER_SHARED, sharingEnabled);
    cc.connectorProvider(new ApacheConnectorProvider());
    final Client clientOne = ClientBuilder.newClient(cc);
    WebTarget target = clientOne.target(getBaseUri()).path(ROOT_PATH);
    target.request().get();
    clientOne.close();
    final boolean exceptionExpected = !sharingEnabled;
    final Client clientTwo = ClientBuilder.newClient(cc);
    target = clientTwo.target(getBaseUri()).path(ROOT_PATH);
    try {
        target.request().get();
        if (exceptionExpected) {
            Assert.fail("Exception expected");
        }
    } catch (Exception e) {
        if (!exceptionExpected) {
            Assert.fail("Exception not expected");
        }
    } finally {
        clientTwo.close();
    }
    if (sharingEnabled) {
        connectionManager.shutdown();
    }
}
Also used : WebTarget(javax.ws.rs.client.WebTarget) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) ClientConfig(org.glassfish.jersey.client.ClientConfig) Client(javax.ws.rs.client.Client) ConnectionPoolTimeoutException(org.apache.http.conn.ConnectionPoolTimeoutException) IOException(java.io.IOException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) HttpException(org.apache.http.HttpException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 2 with HttpClientConnectionManager

use of org.apache.http.conn.HttpClientConnectionManager in project camel by apache.

the class HttpComponent method createEndpoint.

@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    Map<String, Object> httpClientParameters = new HashMap<String, Object>(parameters);
    final Map<String, Object> httpClientOptions = new HashMap<>();
    final HttpClientBuilder clientBuilder = createHttpClientBuilder(uri, parameters, httpClientOptions);
    HttpBinding httpBinding = resolveAndRemoveReferenceParameter(parameters, "httpBinding", HttpBinding.class);
    HttpContext httpContext = resolveAndRemoveReferenceParameter(parameters, "httpContext", HttpContext.class);
    SSLContextParameters sslContextParameters = resolveAndRemoveReferenceParameter(parameters, "sslContextParameters", SSLContextParameters.class);
    if (sslContextParameters == null) {
        sslContextParameters = getSslContextParameters();
    }
    String httpMethodRestrict = getAndRemoveParameter(parameters, "httpMethodRestrict", String.class);
    HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters, "headerFilterStrategy", HeaderFilterStrategy.class);
    UrlRewrite urlRewrite = resolveAndRemoveReferenceParameter(parameters, "urlRewrite", UrlRewrite.class);
    boolean secure = HttpHelper.isSecureConnection(uri) || sslContextParameters != null;
    // need to set scheme on address uri depending on if its secure or not
    String addressUri = (secure ? "https://" : "http://") + remaining;
    addressUri = UnsafeUriCharactersEncoder.encodeHttpURI(addressUri);
    URI uriHttpUriAddress = new URI(addressUri);
    // validate http uri that end-user did not duplicate the http part that can be a common error
    int pos = uri.indexOf("//");
    if (pos != -1) {
        String part = uri.substring(pos + 2);
        if (part.startsWith("http:") || part.startsWith("https:")) {
            throw new ResolveEndpointFailedException(uri, "The uri part is not configured correctly. You have duplicated the http(s) protocol.");
        }
    }
    // create the configurer to use for this endpoint
    HttpClientConfigurer configurer = createHttpClientConfigurer(parameters, secure);
    URI endpointUri = URISupport.createRemainingURI(uriHttpUriAddress, httpClientParameters);
    // the endpoint uri should use the component name as scheme, so we need to re-create it once more
    String scheme = ObjectHelper.before(uri, "://");
    endpointUri = URISupport.createRemainingURI(new URI(scheme, endpointUri.getUserInfo(), endpointUri.getHost(), endpointUri.getPort(), endpointUri.getPath(), endpointUri.getQuery(), endpointUri.getFragment()), httpClientParameters);
    // create the endpoint and set the http uri to be null
    String endpointUriString = endpointUri.toString();
    LOG.debug("Creating endpoint uri {}", endpointUriString);
    final HttpClientConnectionManager localConnectionManager = createConnectionManager(parameters, sslContextParameters);
    HttpEndpoint endpoint = new HttpEndpoint(endpointUriString, this, clientBuilder, localConnectionManager, configurer);
    // configure the endpoint with the common configuration from the component
    if (getHttpConfiguration() != null) {
        Map<String, Object> properties = new HashMap<>();
        IntrospectionSupport.getProperties(getHttpConfiguration(), properties, null);
        setProperties(endpoint, properties);
    }
    if (urlRewrite != null) {
        // let CamelContext deal with the lifecycle of the url rewrite
        // this ensures its being shutdown when Camel shutdown etc.
        getCamelContext().addService(urlRewrite);
        endpoint.setUrlRewrite(urlRewrite);
    }
    // configure the endpoint
    setProperties(endpoint, parameters);
    // determine the portnumber (special case: default portnumber)
    //int port = getPort(uriHttpUriAddress);
    // we can not change the port of an URI, we must create a new one with an explicit port value
    URI httpUri = URISupport.createRemainingURI(new URI(uriHttpUriAddress.getScheme(), uriHttpUriAddress.getUserInfo(), uriHttpUriAddress.getHost(), uriHttpUriAddress.getPort(), uriHttpUriAddress.getPath(), uriHttpUriAddress.getQuery(), uriHttpUriAddress.getFragment()), parameters);
    endpoint.setHttpUri(httpUri);
    if (headerFilterStrategy != null) {
        endpoint.setHeaderFilterStrategy(headerFilterStrategy);
    } else {
        setEndpointHeaderFilterStrategy(endpoint);
    }
    endpoint.setBinding(getHttpBinding());
    if (httpBinding != null) {
        endpoint.setBinding(httpBinding);
    }
    if (httpMethodRestrict != null) {
        endpoint.setHttpMethodRestrict(httpMethodRestrict);
    }
    endpoint.setHttpContext(getHttpContext());
    if (httpContext != null) {
        endpoint.setHttpContext(httpContext);
    }
    if (endpoint.getCookieStore() == null) {
        endpoint.setCookieStore(getCookieStore());
    }
    endpoint.setHttpClientOptions(httpClientOptions);
    return endpoint;
}
Also used : HashMap(java.util.HashMap) HttpContext(org.apache.http.protocol.HttpContext) UrlRewrite(org.apache.camel.http.common.UrlRewrite) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) HttpRestHeaderFilterStrategy(org.apache.camel.http.common.HttpRestHeaderFilterStrategy) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) Endpoint(org.apache.camel.Endpoint) SSLContextParameters(org.apache.camel.util.jsse.SSLContextParameters) ResolveEndpointFailedException(org.apache.camel.ResolveEndpointFailedException) HttpBinding(org.apache.camel.http.common.HttpBinding) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager)

Example 3 with HttpClientConnectionManager

use of org.apache.http.conn.HttpClientConnectionManager in project camel by apache.

the class HttpEndpointURLTest method testConnectionManagerFromHttpUri.

@Test
public void testConnectionManagerFromHttpUri() throws Exception {
    HttpEndpoint http1 = context.getEndpoint("http4://www.google.com?maxTotalConnections=40&connectionsPerRoute=5", HttpEndpoint.class);
    HttpClientConnectionManager connectionManager = http1.getClientConnectionManager();
    assertTrue("Get a wrong type of connection manager", connectionManager instanceof PoolingHttpClientConnectionManager);
    @SuppressWarnings("resource") PoolingHttpClientConnectionManager poolManager = (PoolingHttpClientConnectionManager) connectionManager;
    assertEquals("Get a wrong setting of maxTotalConnections", 40, poolManager.getMaxTotal());
    assertEquals("Get a wrong setting of connectionsPerRoute", 5, poolManager.getDefaultMaxPerRoute());
}
Also used : PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) Test(org.junit.Test)

Example 4 with HttpClientConnectionManager

use of org.apache.http.conn.HttpClientConnectionManager in project cuba by cuba-platform.

the class IdpAuthLifecycleManager method pingIdpSessionServer.

protected IdpSessionStatus pingIdpSessionServer(String idpSessionId) {
    log.debug("Ping IDP session {}", idpSessionId);
    String idpBaseURL = idpConfig.getIdpBaseURL();
    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }
    String idpSessionPingUrl = idpBaseURL + "service/ping";
    HttpPost httpPost = new HttpPost(idpSessionPingUrl);
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("idpSessionId", idpSessionId), new BasicNameValuePair("trustedServicePassword", idpConfig.getIdpTrustedServicePassword())), StandardCharsets.UTF_8);
    httpPost.setEntity(formEntity);
    HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
    HttpClient client = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
    try {
        HttpResponse httpResponse = client.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.GONE.value()) {
            log.debug("IDP session expired {}", idpSessionId);
            return IdpSessionStatus.EXPIRED;
        }
        if (statusCode != HttpStatus.OK.value()) {
            log.warn("IDP respond status {} on session ping", statusCode);
        }
    } catch (IOException e) {
        log.warn("Unable to ping IDP {} session {}", idpSessionPingUrl, idpSessionId, e);
    } finally {
        connectionManager.shutdown();
    }
    return IdpSessionStatus.ALIVE;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager)

Example 5 with HttpClientConnectionManager

use of org.apache.http.conn.HttpClientConnectionManager in project cuba by cuba-platform.

the class RestApiDataProvider method provide.

@Override
public InputStream provide() {
    String url = restApiUrl + query;
    HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
    HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = httpClient.execute(httpGet);
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) {
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                inputStream = httpEntity.getContent();
            } else {
                throw new RuntimeException("Unable to retrieve data using REST API from " + url + "\nHttpEntity is null");
            }
        } else {
            throw new RuntimeException("Unable to retrieve data using REST API from " + url + "\n" + response.getStatusLine());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        connectionManager.shutdown();
    }
    return inputStream;
}
Also used : HttpEntity(org.apache.http.HttpEntity) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager)

Aggregations

HttpClientConnectionManager (org.apache.http.conn.HttpClientConnectionManager)34 BasicHttpClientConnectionManager (org.apache.http.impl.conn.BasicHttpClientConnectionManager)22 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)18 IOException (java.io.IOException)16 HttpResponse (org.apache.http.HttpResponse)14 HttpClient (org.apache.http.client.HttpClient)11 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)10 SSLContext (javax.net.ssl.SSLContext)8 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)8 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)8 CertificateException (java.security.cert.CertificateException)7 RequestConfig (org.apache.http.client.config.RequestConfig)7 HttpGet (org.apache.http.client.methods.HttpGet)6 HttpPost (org.apache.http.client.methods.HttpPost)6 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)5 KeyManagementException (java.security.KeyManagementException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)4 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)4 NoopHostnameVerifier (org.apache.http.conn.ssl.NoopHostnameVerifier)4