Java Code Examples for org.apache.cxf.transports.http.configuration.HTTPClientPolicy#setConnectionTimeout()

The following examples show how to use org.apache.cxf.transports.http.configuration.HTTPClientPolicy#setConnectionTimeout() . 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: RestUtil.java    From peer-os with Apache License 2.0 7 votes vote down vote up
public static WebClient createTrustedWebClient( String url )
{
    WebClient client = WebClient.create( url );

    HTTPConduit httpConduit = ( HTTPConduit ) WebClient.getConfig( client ).getConduit();

    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setConnectionTimeout( defaultConnectionTimeout );
    httpClientPolicy.setReceiveTimeout( defaultReceiveTimeout );
    httpClientPolicy.setMaxRetransmits( defaultMaxRetransmits );


    httpConduit.setClient( httpClientPolicy );

    SSLManager sslManager = new SSLManager( null, null, null, null );

    TLSClientParameters tlsClientParameters = new TLSClientParameters();
    tlsClientParameters.setDisableCNCheck( true );
    tlsClientParameters.setTrustManagers( sslManager.getClientFullTrustManagers() );
    httpConduit.setTlsClientParameters( tlsClientParameters );

    return client;
}
 
Example 2
Source File: JaxRsClientStarter.java    From paymentgateway with GNU General Public License v3.0 6 votes vote down vote up
public T start(Class<T> cls, String url, boolean trustAllCerts, String trustStore, String trustStorePassword, 
	List<?> providers, int connectTimeout, int receiveTimeout) {

	try {
		
		T resource = JAXRSClientFactory.create(url, cls, providers);
	    HTTPConduit conduit = WebClient.getConfig(resource).getHttpConduit();
	    WebClient.getConfig(resource).getInInterceptors().add(new LoggingInInterceptor());
	    WebClient.getConfig(resource).getOutInterceptors().add(new LoggingOutInterceptor());
		configureHTTPS(resource, conduit, trustAllCerts, trustStore, trustStorePassword);
		
	    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); 
	    httpClientPolicy.setConnectionTimeout(connectTimeout); 
	    httpClientPolicy.setReceiveTimeout(receiveTimeout); 
	    conduit.setClient(httpClientPolicy);
		
		return resource;
		
	} catch (Exception e) {
		LOG.error(" rest client '{}': NOT STARTED", url);
		return null;
	}
	
}
 
Example 3
Source File: WebServiceProtocol.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected <T> T doRefer(final Class<T> serviceType, final URL url) throws RpcException {
    ClientProxyFactoryBean proxyFactoryBean = new ClientProxyFactoryBean();
    proxyFactoryBean.setAddress(url.setProtocol("http").toIdentityString());
    proxyFactoryBean.setServiceClass(serviceType);
    proxyFactoryBean.setBus(bus);
    T ref = (T) proxyFactoryBean.create();
    Client proxy = ClientProxy.getClient(ref);
    HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
    HTTPClientPolicy policy = new HTTPClientPolicy();
    policy.setConnectionTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT));
    policy.setReceiveTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
    conduit.setClient(policy);
    return ref;
}
 
Example 4
Source File: OpenTracingTracingTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatNewSpanIsCreatedOnClientTimeout() {
    final WebClient client = WebClient
        .create("http://localhost:" + PORT + "/bookstore/books/long", Collections.emptyList(),
            Arrays.asList(new OpenTracingClientFeature(tracer)), null)
        .accept(MediaType.APPLICATION_JSON);

    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setConnectionTimeout(100);
    httpClientPolicy.setReceiveTimeout(100);
    WebClient.getConfig(client).getHttpConduit().setClient(httpClientPolicy);

    expectedException.expect(ProcessingException.class);
    try {
        client.get();
    } finally {
        await().atMost(Duration.ofSeconds(1L)).until(()-> REPORTER.getSpans().size() == 2);
        assertThat(REPORTER.getSpans().toString(), REPORTER.getSpans().size(), equalTo(2));
        assertThat(REPORTER.getSpans().get(0).getOperationName(), equalTo("GET " + client.getCurrentURI()));
        assertThat(REPORTER.getSpans().get(0).getTags(), hasItem(Tags.ERROR.getKey(), Boolean.TRUE));
        assertThat(REPORTER.getSpans().get(1).getOperationName(), equalTo("GET /bookstore/books/long"));
    }
}
 
Example 5
Source File: ClientPolicyCalculatorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompatibleClientPolicies() {
    ClientPolicyCalculator calc = new ClientPolicyCalculator();
    HTTPClientPolicy p1 = new HTTPClientPolicy();
    assertTrue("Policy is not compatible with itself.", calc.compatible(p1, p1));
    HTTPClientPolicy p2 = new HTTPClientPolicy();
    assertTrue("Policies are not compatible.", calc.compatible(p1, p2));
    p1.setBrowserType("browser");
    assertTrue("Policies are not compatible.", calc.compatible(p1, p2));
    p1.setBrowserType(null);
    p1.setConnectionTimeout(10000);
    assertTrue("Policies are not compatible.", calc.compatible(p1, p2));
    p1.setAllowChunking(false);
    p2.setAllowChunking(true);
    assertFalse("Policies are compatible.", calc.compatible(p1, p2));
    p2.setAllowChunking(false);
    assertTrue("Policies are compatible.", calc.compatible(p1, p2));
}
 
Example 6
Source File: JaxRsClientStarter.java    From paymentgateway with GNU General Public License v3.0 6 votes vote down vote up
public T start(Class<T> cls, String url, boolean trustAllCerts, String trustStore, String trustStorePassword, 
	List<?> providers, int connectTimeout, int receiveTimeout) {

	try {
		
		T resource = JAXRSClientFactory.create(url, cls, providers);
	    HTTPConduit conduit = WebClient.getConfig(resource).getHttpConduit();
	    WebClient.getConfig(resource).getInInterceptors().add(new LoggingInInterceptor());
	    WebClient.getConfig(resource).getOutInterceptors().add(new LoggingOutInterceptor());
		configureHTTPS(resource, conduit, trustAllCerts, trustStore, trustStorePassword);
		
	    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); 
	    httpClientPolicy.setConnectionTimeout(connectTimeout); 
	    httpClientPolicy.setReceiveTimeout(receiveTimeout); 
	    conduit.setClient(httpClientPolicy);
		
		return resource;
		
	} catch (Exception e) {
		LOG.error(" rest client '{}': NOT STARTED", url);
		return null;
	}
	
}
 
Example 7
Source File: BraveTracingTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatNewSpanIsCreatedOnClientTimeout() {
    final WebClient client = WebClient
        .create("http://localhost:" + PORT + "/bookstore/books/long", Collections.emptyList(),
            Arrays.asList(new BraveClientFeature(brave)), null)
        .accept(MediaType.APPLICATION_JSON);

    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setConnectionTimeout(100);
    httpClientPolicy.setReceiveTimeout(100);
    WebClient.getConfig(client).getHttpConduit().setClient(httpClientPolicy);

    expectedException.expect(ProcessingException.class);
    try {
        client.get();
    } finally {
        await().atMost(Duration.ofSeconds(1L)).until(()-> TestSpanReporter.getAllSpans().size() == 2);
        assertThat(TestSpanReporter.getAllSpans().size(), equalTo(2));
        assertThat(TestSpanReporter.getAllSpans().get(0).name(), equalTo("get " + client.getCurrentURI()));
        assertThat(TestSpanReporter.getAllSpans().get(0).tags(), hasKey("error"));
        assertThat(TestSpanReporter.getAllSpans().get(1).name(), equalTo("get /bookstore/books/long"));
    }
}
 
Example 8
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testPatchBookTimeout() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/patch";
    WebClient wc = WebClient.create(address);
    wc.type("application/xml");
    ClientConfiguration clientConfig = WebClient.getConfig(wc);
    clientConfig.getRequestContext().put("use.async.http.conduit", true);
    HTTPClientPolicy clientPolicy = clientConfig.getHttpConduit().getClient();
    clientPolicy.setReceiveTimeout(500);
    clientPolicy.setConnectionTimeout(500);
    try {
        Book book = wc.invoke("PATCH", new Book("Timeout", 123L), Book.class);
        fail("should throw an exception due to timeout, instead got " + book);
    } catch (javax.ws.rs.ProcessingException e) {
        //expected!!!
    }
}
 
Example 9
Source File: JaxRsClientStarter.java    From paymentgateway with GNU General Public License v3.0 6 votes vote down vote up
public T start(Class<T> cls, String url, boolean trustAllCerts, String trustStore, String trustStorePassword, 
	List<?> providers, int connectTimeout, int receiveTimeout) {

	try {
		
		T resource = JAXRSClientFactory.create(url, cls, providers);
	    HTTPConduit conduit = WebClient.getConfig(resource).getHttpConduit();
	    WebClient.getConfig(resource).getInInterceptors().add(new LoggingInInterceptor());
	    WebClient.getConfig(resource).getOutInterceptors().add(new LoggingOutInterceptor());
		configureHTTPS(resource, conduit, trustAllCerts, trustStore, trustStorePassword);
		
	    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); 
	    httpClientPolicy.setConnectionTimeout(connectTimeout); 
	    httpClientPolicy.setReceiveTimeout(receiveTimeout); 
	    conduit.setClient(httpClientPolicy);
		
		return resource;
		
	} catch (Exception e) {
		LOG.error(" rest client '{}': NOT STARTED", url);
		return null;
	}
	
}
 
Example 10
Source File: JaxRsClientStarter.java    From paymentgateway with GNU General Public License v3.0 6 votes vote down vote up
public T start(Class<T> cls, String url, boolean trustAllCerts, String trustStore, String trustStorePassword, 
	List<?> providers, int connectTimeout, int receiveTimeout) {

	try {
		
		T resource = JAXRSClientFactory.create(url, cls, providers);
	    HTTPConduit conduit = WebClient.getConfig(resource).getHttpConduit();
	    WebClient.getConfig(resource).getInInterceptors().add(new LoggingInInterceptor());
	    WebClient.getConfig(resource).getOutInterceptors().add(new LoggingOutInterceptor());
		configureHTTPS(resource, conduit, trustAllCerts, trustStore, trustStorePassword);
		
	    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); 
	    httpClientPolicy.setConnectionTimeout(connectTimeout); 
	    httpClientPolicy.setReceiveTimeout(receiveTimeout); 
	    conduit.setClient(httpClientPolicy);
		
		return resource;
		
	} catch (Exception e) {
		LOG.error(" rest client '{}': NOT STARTED", url);
		return null;
	}
	
}
 
Example 11
Source File: AsyncHTTPConduit.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void propagateJaxwsSpecTimeoutSettings(Message message, HTTPClientPolicy csPolicy) {
    int receiveTimeout = determineReceiveTimeout(message, csPolicy);
    if (csPolicy.getReceiveTimeout() == 60000) {
        csPolicy.setReceiveTimeout(receiveTimeout);
    }
    int connectionTimeout = determineConnectionTimeout(message, csPolicy);
    if (csPolicy.getConnectionTimeout() == 30000) {
        csPolicy.setConnectionTimeout(connectionTimeout);
    }
}
 
Example 12
Source File: AmbariClientBuilder.java    From components with Apache License 2.0 5 votes vote down vote up
/**
 * Build a client proxy, for a specific proxy type.
 * 
 * @param proxyType proxy type class
 * @return client proxy stub
 */
protected <T> T build(Class<T> proxyType) {
    String address = generateAddress();
    T rootResource;
    // Synchronized on the class to correlate with the scope of clientStaticResources
    // We want to ensure that the shared bean isn't set concurrently in multiple callers
    synchronized (AmbariClientBuilder.class) {
        JAXRSClientFactoryBean bean = cleanFactory(clientStaticResources.getUnchecked(proxyType));
        bean.setAddress(address);
        if (username != null) {
            bean.setUsername(username);
            bean.setPassword(password);
        }

        if (enableLogging) {
            bean.setFeatures(Arrays.<AbstractFeature> asList(new LoggingFeature()));
        }
        rootResource = bean.create(proxyType);
    }

    boolean isTlsEnabled = address.startsWith("https://");
    ClientConfiguration config = WebClient.getConfig(rootResource);
    HTTPConduit conduit = (HTTPConduit) config.getConduit();
    if (isTlsEnabled) {
        TLSClientParameters tlsParams = new TLSClientParameters();
        if (!validateCerts) {
            tlsParams.setTrustManagers(new TrustManager[] { new AcceptAllTrustManager() });
        } else if (trustManagers != null) {
            tlsParams.setTrustManagers(trustManagers);
        }
        tlsParams.setDisableCNCheck(!validateCn);
        conduit.setTlsClientParameters(tlsParams);
    }

    HTTPClientPolicy policy = conduit.getClient();
    policy.setConnectionTimeout(connectionTimeoutUnits.toMillis(connectionTimeout));
    policy.setReceiveTimeout(receiveTimeoutUnits.toMillis(receiveTimeout));
    return rootResource;
}
 
Example 13
Source File: CECXFClient.java    From uavstack with Apache License 2.0 5 votes vote down vote up
private void configHttpConduit(Object port) {

        // 设置客户端的配置信息,超时等.
        Client proxy = ClientProxy.getClient(port);
        HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
        HTTPClientPolicy policy = new HTTPClientPolicy();

        // 连接服务器超时时间
        policy.setConnectionTimeout(this.connectTimeout);
        // 等待服务器响应超时时间
        policy.setReceiveTimeout(this.receiveTimeout);

        conduit.setClient(policy);
    }
 
Example 14
Source File: WebServiceProtocol.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
  protected <T> T doRefer(final Class<T> serviceType, final URL url) throws RpcException {
  	ClientProxyFactoryBean proxyFactoryBean = new ClientProxyFactoryBean();
  	proxyFactoryBean.setAddress(url.setProtocol("http").toIdentityString());
  	proxyFactoryBean.setServiceClass(serviceType);
  	proxyFactoryBean.setBus(bus);
  	T ref = (T) proxyFactoryBean.create();
  	Client proxy = ClientProxy.getClient(ref);  
HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
HTTPClientPolicy policy = new HTTPClientPolicy();
policy.setConnectionTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT));
policy.setReceiveTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
conduit.setClient(policy);
      return ref;
  }
 
Example 15
Source File: WebServiceProtocol.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
  protected <T> T doRefer(final Class<T> serviceType, final URL url) throws RpcException {
  	ClientProxyFactoryBean proxyFactoryBean = new ClientProxyFactoryBean();
  	proxyFactoryBean.setAddress(url.setProtocol("http").toIdentityString());
  	proxyFactoryBean.setServiceClass(serviceType);
  	proxyFactoryBean.setBus(bus);
  	T ref = (T) proxyFactoryBean.create();
  	Client proxy = ClientProxy.getClient(ref);  
HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
HTTPClientPolicy policy = new HTTPClientPolicy();
policy.setConnectionTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT));
policy.setReceiveTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT));
conduit.setClient(policy);
      return ref;
  }
 
Example 16
Source File: AbstractWebServiceTest.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
public static WebClient getClient(String url) {
	WebClient c = WebClient.create(url, List.of(new AppointmentMessageBodyReader()))
			.accept("application/json").type("application/json");
	HTTPClientPolicy p = WebClient.getConfig(c).getHttpConduit().getClient();
	p.setConnectionTimeout(TIMEOUT);
	p.setReceiveTimeout(TIMEOUT);
	return c;
}
 
Example 17
Source File: ClientPolicyCalculatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testIntersectClientPolicies() {
    ThreadLocalRandom random = ThreadLocalRandom.current();
    ClientPolicyCalculator calc = new ClientPolicyCalculator();
    HTTPClientPolicy p1 = new HTTPClientPolicy();
    HTTPClientPolicy p2 = new HTTPClientPolicy();
    HTTPClientPolicy p = null;

    p1.setBrowserType("browser");
    p = calc.intersect(p1, p2);
    assertEquals("browser", p.getBrowserType());
    p1.setBrowserType(null);

    long connectionRequestTimeout = random.nextLong(0, 10000);
    p1.setConnectionRequestTimeout(connectionRequestTimeout);
    p = calc.intersect(p1, p2);
    assertEquals(connectionRequestTimeout, p.getConnectionRequestTimeout());

    long receiveTimeout = random.nextLong(0, 10000);
    p1.setReceiveTimeout(receiveTimeout);
    p = calc.intersect(p1, p2);
    assertEquals(receiveTimeout, p.getReceiveTimeout());

    long connectionTimeout = random.nextLong(0, 10000);
    p1.setConnectionTimeout(connectionTimeout);
    p = calc.intersect(p1, p2);
    assertEquals(connectionTimeout, p.getConnectionTimeout());

    p1.setAllowChunking(false);
    p2.setAllowChunking(false);
    p = calc.intersect(p1, p2);
    assertFalse(p.isAllowChunking());
}
 
Example 18
Source File: SoapClient.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Configures the timeout (in seconds)
 */
protected void configureTimeout(int timeout) {
	if (timeout <= 0)
		return;

	HTTPClientPolicy policy = new HTTPClientPolicy();
	policy.setConnectionTimeout(timeout * 1000);
	policy.setReceiveTimeout(timeout * 1000);

	org.apache.cxf.endpoint.Client cl = ClientProxy.getClient(client);
	HTTPConduit httpConduit = (HTTPConduit) cl.getConduit();
	httpConduit.setClient(policy);
}
 
Example 19
Source File: WebClientBuilder.java    From peer-os with Apache License 2.0 4 votes vote down vote up
public static WebClient buildPeerWebClient( final PeerInfo peerInfo, final String path, final Object provider,
                                            long connectTimeoutMs, long readTimeoutMs, int maxAttempts )
{
    String effectiveUrl = String.format( PEER_URL_TEMPLATE, peerInfo.getIp(), peerInfo.getPublicSecurePort(),
            path.startsWith( "/" ) ? path : "/" + path );
    WebClient client;
    if ( provider == null )
    {
        client = WebClient.create( effectiveUrl );
    }
    else
    {
        client = WebClient.create( effectiveUrl, Collections.singletonList( provider ) );
    }
    client.type( MediaType.APPLICATION_JSON );
    client.accept( MediaType.APPLICATION_JSON );

    HTTPConduit httpConduit = ( HTTPConduit ) WebClient.getConfig( client ).getConduit();

    HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
    httpClientPolicy.setConnectionTimeout( connectTimeoutMs );
    httpClientPolicy.setReceiveTimeout( readTimeoutMs );
    httpClientPolicy.setMaxRetransmits( maxAttempts );

    httpConduit.setClient( httpClientPolicy );

    KeyStoreTool keyStoreManager = new KeyStoreTool();
    KeyStoreData keyStoreData = new KeyStoreData();
    keyStoreData.setupKeyStorePx2();
    keyStoreData.setAlias( SecuritySettings.KEYSTORE_PX2_ROOT_ALIAS );
    KeyStore keyStore = keyStoreManager.load( keyStoreData );

    LOG.debug( String.format( "Getting key with alias: %s for url: %s", SecuritySettings.KEYSTORE_PX2_ROOT_ALIAS,
            effectiveUrl ) );

    KeyStoreData trustStoreData = new KeyStoreData();
    trustStoreData.setupTrustStorePx2();
    KeyStore trustStore = keyStoreManager.load( trustStoreData );

    SSLManager sslManager = new SSLManager( keyStore, keyStoreData, trustStore, trustStoreData );

    TLSClientParameters tlsClientParameters = new TLSClientParameters();
    tlsClientParameters.setDisableCNCheck( true );
    tlsClientParameters.setTrustManagers( sslManager.getClientTrustManagers() );
    tlsClientParameters.setKeyManagers( sslManager.getClientKeyManagers() );
    tlsClientParameters.setCertAlias( SecuritySettings.KEYSTORE_PX2_ROOT_ALIAS );
    httpConduit.setTlsClientParameters( tlsClientParameters );
    return client;
}
 
Example 20
Source File: HttpClient.java    From peer-os with Apache License 2.0 4 votes vote down vote up
public static WebClient createTrustedWebClientWithAuth( String url, KeyStore keyStore, char[] keyStorePassword,
                                                        byte[] serverFingerprint ) throws BazaarManagerException
{
    try
    {
        WebClient client = WebClient.create( url );

        // A client certificate is not provided in SSL context if async connection is used.
        // See details: #311 - Registration failure due to inability to find fingerprint.
        Map<String, Object> requestContext = WebClient.getConfig( client ).getRequestContext();
        requestContext.put( "use.async.http.conduit", Boolean.FALSE );

        HTTPConduit httpConduit = ( HTTPConduit ) WebClient.getConfig( client ).getConduit();

        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();

        httpClientPolicy.setConnectionTimeout( SECONDS_30 );

        httpClientPolicy.setReceiveTimeout( SECONDS_60 );

        httpClientPolicy.setMaxRetransmits( DEFAULT_MAX_RETRANSMITS );

        httpConduit.setClient( httpClientPolicy );

        KeyManagerFactory keyManagerFactory =
                KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );

        keyManagerFactory.init( keyStore, keyStorePassword );

        TLSClientParameters tlsClientParameters = new TLSClientParameters();

        tlsClientParameters.setDisableCNCheck( true );

        tlsClientParameters
                .setTrustManagers( new TrustManager[] { new FingerprintTrustManager( serverFingerprint ) } );

        tlsClientParameters.setKeyManagers( keyManagerFactory.getKeyManagers() );

        httpConduit.setTlsClientParameters( tlsClientParameters );

        return client;
    }
    catch ( Exception e )
    {
        throw new BazaarManagerException( e );
    }
}