org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine Java Examples

The following examples show how to use org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LoginPageTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void acceptLanguageHeader() {
    ProfileAssume.assumeCommunity();
    
    CloseableHttpClient httpClient = (CloseableHttpClient) new HttpClientBuilder().build();
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();

    loginPage.open();
    Response response = client.target(driver.getCurrentUrl()).request().acceptLanguage("de").get();
    Assert.assertTrue(response.readEntity(String.class).contains("Anmeldung bei test"));

    response = client.target(driver.getCurrentUrl()).request().acceptLanguage("en").get();
    Assert.assertTrue(response.readEntity(String.class).contains("Log in to test"));

    client.close();
}
 
Example #2
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testAddMovieMultiConnection() {

    final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
    final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    final ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    final ResteasyWebTarget target = client.target(FULL_PATH);
    final ServicesInterface proxy = target.proxy(ServicesInterface.class);

    final Response batmanResponse = proxy.addMovie(batmanMovie);
    final Response transformerResponse = proxy.addMovie(transformerMovie);

    if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
        System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus());
    }
    if (batmanResponse.getStatus() != Response.Status.CREATED.getStatusCode()) {
        System.out.println("Batman Movie creation Failed : HTTP error code : " + batmanResponse.getStatus());
    }

    batmanResponse.close();
    transformerResponse.close();
    cm.close();

}
 
Example #3
Source File: RestEasyITest.java    From java-jaxrs with Apache License 2.0 6 votes vote down vote up
/**
 * A substitution for {@link #testAsyncError()}. It test that span is reported.
 */
@Test
public void testAsyncErrorTestSpanReported() {
    // disable retry otherwise there can be 2 spans
    CloseableHttpClient build = HttpClientBuilder.create().disableAutomaticRetries().build();
    Client client = new ResteasyClientBuilder().httpEngine(new ApacheHttpClient4Engine(build)).build();
    try (Response response = client.target(url("/asyncError"))
        .request()
        .get()) {
        response.readEntity(String.class);
    } catch (Exception ex) {
        // client throws an exception if async request fails
    } finally {
          client.close();
    }
    await().until(finishedSpansSizeEquals(1));

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(1, mockSpans.size());
    assertOnErrors(mockSpans);
}
 
Example #4
Source File: SchedulerClient.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void init(ConnectionInfo connectionInfo) throws Exception {
    HttpClient client = new HttpClientBuilder().insecure(connectionInfo.isInsecure()).useSystemProperties().build();
    SchedulerRestClient restApiClient = new SchedulerRestClient(connectionInfo.getUrl(),
                                                                new ApacheHttpClient4Engine(client));

    ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
    factory.register(new WildCardTypeReader());
    factory.register(new OctetStreamReader());
    factory.register(new TaskResultReader());
    SchedulerRestClient.registerGzipEncoding(factory);

    setApiClient(restApiClient);

    this.connectionInfo = connectionInfo;
    this.initialized = true;

    renewSession();
}
 
Example #5
Source File: RMNodeClient.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void init(ConnectionInfo connectionInfo) throws Exception {
    HttpClient client = new HttpClientBuilder().insecure(connectionInfo.isInsecure()).useSystemProperties().build();

    RMRestClient restApiClient = new RMRestClient(connectionInfo.getUrl(), new ApacheHttpClient4Engine(client));

    this.rm = restApiClient.getRm();

    this.connectionInfo = connectionInfo;

    try {
        String sid = rm.rmConnect(connectionInfo.getLogin(), connectionInfo.getPassword());
        setSession(sid);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: AbstractScimClient.java    From SCIM-Client with Apache License 2.0 5 votes vote down vote up
AbstractScimClient(String domain, Class<T> serviceClass) {
    /*
     Configures a proxy to interact with the service using the new JAX-RS 2.0 Client API, see section
     "Resteasy Proxy Framework" of RESTEasy JAX-RS user guide
     */
    if (System.getProperty("httpclient.multithreaded") == null) {
        client = new ResteasyClientBuilder().build();
    } else {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //Change defaults if supplied
        getIntegerProperty("httpclient.multithreaded.maxtotal").ifPresent(cm::setMaxTotal);
        getIntegerProperty("httpclient.multithreaded.maxperroute").ifPresent(cm::setDefaultMaxPerRoute);
        getIntegerProperty("httpclient.multithreaded.validateafterinactivity").ifPresent(cm::setValidateAfterInactivity);

        logger.debug("Using multithreaded support with maxTotalConnections={} and maxPerRoutConnections={}", cm.getMaxTotal(), cm.getDefaultMaxPerRoute());
        logger.warn("Ensure your oxTrust 'rptConnectionPoolUseConnectionPooling' property is set to true");

        CloseableHttpClient httpClient = HttpClients.custom()
	.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
        		.setConnectionManager(cm).build();
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);

        client = new ResteasyClientBuilder().httpEngine(engine).build();
    }
    ResteasyWebTarget target = client.target(domain);

    scimService = target.proxy(serviceClass);
    target.register(ListResponseProvider.class);
    target.register(AuthorizationInjectionFilter.class);
    target.register(ScimResourceProvider.class);

    ClientMap.update(client, null);
}
 
Example #7
Source File: AbstractKerberosTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void initHttpClient(boolean useSpnego) {
    if (client != null) {
        cleanupApacheHttpClient();
    }
    
    DefaultHttpClient httpClient = (DefaultHttpClient) new HttpClientBuilder()
            .disableCookieCache(false)
            .build();

    httpClient.getAuthSchemes().register(AuthSchemes.SPNEGO, spnegoSchemeFactory);

    if (useSpnego) {
        Credentials fake = new Credentials() {

            @Override
            public String getPassword() {
                return null;
            }

            @Override
            public Principal getUserPrincipal() {
                return null;
            }

        };

        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(null, -1, null),
                fake);
    }
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    client = new ResteasyClientBuilder().httpEngine(engine).build();
}
 
Example #8
Source File: ClientFactory.java    From oxAuth with MIT License 5 votes vote down vote up
public ApacheHttpClient4Engine createEngine(int maxTotal, int defaultMaxPerRoute, String cookieSpec, boolean followRedirects) {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    CloseableHttpClient httpClient = HttpClients.custom()
			.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(cookieSpec).build())
    		.setConnectionManager(cm).build();
    cm.setMaxTotal(maxTotal);
    cm.setDefaultMaxPerRoute(defaultMaxPerRoute);
       final ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
       engine.setFollowRedirects(followRedirects);
       return engine;
}
 
Example #9
Source File: ResteasyGitLabClientBuilder.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
protected ClientHttpEngine initDefaultEngine() {
    ApacheHttpClient4Engine httpEngine = (ApacheHttpClient4Engine) super.initDefaultEngine();
    if (proxyCredentials != null) {
        ((DefaultHttpClient) httpEngine.getHttpClient()).setCredentialsProvider(proxyCredentials);
    }
    return httpEngine;
}
 
Example #10
Source File: RestFactory.java    From KubernetesAPIJavaClient with Apache License 2.0 5 votes vote down vote up
public KubernetesAPI createAPI(URI uri, String userName, String password) {

        // Configure HttpClient to authenticate preemptively
        // by prepopulating the authentication data cache.
        // http://docs.jboss.org/resteasy/docs/3.0.9.Final/userguide/html/RESTEasy_Client_Framework.html#transport_layer
        // http://hc.apache.org/httpcomponents-client-4.2.x/tutorial/html/authentication.html#d5e1032

        HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

        DefaultHttpClient httpclient = new DefaultHttpClient();

        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        // 4. Create client executor and proxy
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, localcontext);
        ResteasyClient client = new ResteasyClientBuilder().connectionPoolSize(connectionPoolSize).httpEngine(engine)
                .build();

        client.register(JacksonJaxbJsonProvider.class).register(JacksonConfig.class);
        ProxyBuilder<KubernetesAPI> proxyBuilder = client.target(uri).proxyBuilder(KubernetesAPI.class);
        if (classLoader != null) {
            proxyBuilder = proxyBuilder.classloader(classLoader);
        }
        return proxyBuilder.build();
    }
 
Example #11
Source File: DataSpaceClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public void init(String restServerUrl, ISchedulerClient client) {
    this.httpEngine = new ApacheHttpClient4Engine(new HttpClientBuilder().disableContentCompression()
                                                                         .insecure(client.getConnectionInfo()
                                                                                         .isInsecure())
                                                                         .useSystemProperties()
                                                                         .build());
    this.providerFactory = ResteasyProviderFactory.getInstance();
    SchedulerRestClient.registerGzipEncoding(providerFactory);
    this.restDataspaceUrl = restDataspaceUrl(restServerUrl);
    this.sessionId = client.getSession();
    if (log.isDebugEnabled()) {
        log.debug("Error : trying to retrieve session from disconnected client.");
    }
    this.schedulerClient = client;
}
 
Example #12
Source File: ApplicationContextImpl.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public SchedulerRestClient getRestClient() {
    CommonHttpClientBuilder httpClientBuilder = new HttpClientBuilder().useSystemProperties();
    if (canInsecureAccess()) {
        httpClientBuilder.insecure(true);
    }
    return new SchedulerRestClient(restServerUrl, new ApacheHttpClient4Engine(httpClientBuilder.build()));
}
 
Example #13
Source File: RestClientFactoryImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Client create(final RestClientConfiguration configuration) {
  checkNotNull(configuration);

  try (TcclBlock tccl = TcclBlock.begin(ResteasyClientBuilder.class)) {
    HttpContext httpContext = new BasicHttpContext();
    if (configuration.getUseTrustStore()) {
        httpContext.setAttribute(SSLContextSelector.USE_TRUST_STORE, true);
    }
    HttpClient client;
    if (configuration.getHttpClient() != null) {
      client = checkNotNull(configuration.getHttpClient().get());
    }
    else {
      client = httpClient.get();
    }
    ClientHttpEngine httpEngine = new ApacheHttpClient4Engine(client, httpContext);

    ResteasyClientBuilder builder = new ResteasyClientBuilder().httpEngine(httpEngine);

    if (configuration.getCustomizer() != null) {
      configuration.getCustomizer().apply(builder);
    }

    return builder.build();
  }
}
 
Example #14
Source File: RestProtocol.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
        if (connectionMonitor == null) {
            connectionMonitor = new ConnectionMonitor();
        }

        // TODO more configs to add

        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        // 20 is the default maxTotal of current PoolingClientConnectionManager
        connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
        connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

        connectionMonitor.addConnectionManager(connectionManager);

//        BasicHttpContext localContext = new BasicHttpContext();

        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                // TODO constant
                return 30 * 1000;
            }
        });

        HttpParams params = httpClient.getParams();
        // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
        HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoKeepalive(params, true);

        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

        ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
        clients.add(client);

        client.register(RpcContextFilter.class);
        for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
            if (!StringUtils.isEmpty(clazz)) {
                try {
                    client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
                } catch (ClassNotFoundException e) {
                    throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
                }
            }
        }

        // TODO protocol
        ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
        return target.proxy(serviceType);
    }
 
Example #15
Source File: RestProtocol.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
@Override
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
    if (connectionMonitor == null) {
        connectionMonitor = new ConnectionMonitor();
    }

    // TODO more configs to add
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    // 20 is the default maxTotal of current PoolingClientConnectionManager 20是当前池化clientconnectionmanager的默认最大值
    connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
    connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

    connectionMonitor.addConnectionManager(connectionManager);
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT))
            .setSocketTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT))
            .build();

    SocketConfig socketConfig = SocketConfig.custom()
            .setSoKeepAlive(true)
            .setTcpNoDelay(true)
            .build();

    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                    while (it.hasNext()) {
                        HeaderElement he = it.nextElement();
                        String param = he.getName();
                        String value = he.getValue();
                        if (value != null && param.equalsIgnoreCase("timeout")) {
                            return Long.parseLong(value) * 1000;
                        }
                    }
                    // TODO constant
                    return 30 * 1000;
                }
            })
            .setDefaultRequestConfig(requestConfig)
            .setDefaultSocketConfig(socketConfig)
            .build();

    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    clients.add(client);

    client.register(RpcContextFilter.class);
    for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
        if (!StringUtils.isEmpty(clazz)) {
            try {
                client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
            } catch (ClassNotFoundException e) {
                throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
            }
        }
    }

    // TODO protocol
    ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
    return target.proxy(serviceType);
}
 
Example #16
Source File: ClientFactory.java    From oxAuth with MIT License 4 votes vote down vote up
public ApacheHttpClient4Engine createEngine() {
    return createEngine(false);
}
 
Example #17
Source File: ClientFactory.java    From oxAuth with MIT License 4 votes vote down vote up
public ApacheHttpClient4Engine createEngine(boolean followRedirects) {
    return createEngine(200, 20, CookieSpecs.STANDARD, followRedirects);
}
 
Example #18
Source File: BaseTest.java    From oxAuth with MIT License 4 votes vote down vote up
public static ClientHttpEngine clientEngine(boolean trustAll) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    if (trustAll) {
        return new ApacheHttpClient4Engine(createAcceptSelfSignedCertificateClient());
    }
    return new ApacheHttpClient4Engine(createClient());
}
 
Example #19
Source File: HttpService.java    From oxd with Apache License 2.0 4 votes vote down vote up
public ClientHttpEngine getClientEngine() {
    return new ApacheHttpClient4Engine(getHttpClient());
}
 
Example #20
Source File: RestProtocol.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
        if (connectionMonitor == null) {
            connectionMonitor = new ConnectionMonitor();
        }

        // TODO more configs to add

        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        // 20 is the default maxTotal of current PoolingClientConnectionManager
        connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
        connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

        connectionMonitor.addConnectionManager(connectionManager);

//        BasicHttpContext localContext = new BasicHttpContext();

        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                // TODO constant
                return 30 * 1000;
            }
        });

        HttpParams params = httpClient.getParams();
        // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
        HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoKeepalive(params, true);

        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

        ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
        clients.add(client);

        client.register(RpcContextFilter.class);
        for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
            if (!StringUtils.isEmpty(clazz)) {
                try {
                    client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
                } catch (ClassNotFoundException e) {
                    throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
                }
            }
        }

        // TODO protocol
        ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
        return target.proxy(serviceType);
    }
 
Example #21
Source File: RestProtocol.java    From dubbox-hystrix with Apache License 2.0 4 votes vote down vote up
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
        if (connectionMonitor == null) {
            connectionMonitor = new ConnectionMonitor();
        }

        // TODO more configs to add

        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        // 20 is the default maxTotal of current PoolingClientConnectionManager
        connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
        connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

        connectionMonitor.addConnectionManager(connectionManager);

//        BasicHttpContext localContext = new BasicHttpContext();

        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                // TODO constant
                return 30 * 1000;
            }
        });

        HttpParams params = httpClient.getParams();
        // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
        HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoKeepalive(params, true);

        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

        ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
        clients.add(client);

        client.register(RpcContextFilter.class);
        for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
            if (!StringUtils.isEmpty(clazz)) {
                try {
                    client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
                } catch (ClassNotFoundException e) {
                    throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
                }
            }
        }

        // TODO protocol
        ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
        return target.proxy(serviceType);
    }
 
Example #22
Source File: RestProtocol.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected <T> T doRefer(Class<T> serviceType, URL url) throws RpcException {
        if (connectionMonitor == null) {
            connectionMonitor = new ConnectionMonitor();
        }

        // TODO more configs to add

        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
        // 20 is the default maxTotal of current PoolingClientConnectionManager
        connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20));
        connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20));

        connectionMonitor.addConnectionManager(connectionManager);

//        BasicHttpContext localContext = new BasicHttpContext();

        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

        httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        return Long.parseLong(value) * 1000;
                    }
                }
                // TODO constant
                return 30 * 1000;
            }
        });

        HttpParams params = httpClient.getParams();
        // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now
        HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoKeepalive(params, true);

        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/);

        ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
        clients.add(client);

        client.register(RpcContextFilter.class);
        for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
            if (!StringUtils.isEmpty(clazz)) {
                try {
                    client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim()));
                } catch (ClassNotFoundException e) {
                    throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e);
                }
            }
        }

        // TODO protocol
        ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url));
        return target.proxy(serviceType);
    }