Search in sources :

Example 41 with HTTPClientPolicy

use of org.apache.cxf.transports.http.configuration.HTTPClientPolicy in project components by Talend.

the class AmbariClientBuilder method build.

/**
 * 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;
    // 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;
}
Also used : HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) TLSClientParameters(org.apache.cxf.configuration.jsse.TLSClientParameters) JAXRSClientFactoryBean(org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean) LoggingFeature(org.apache.cxf.feature.LoggingFeature) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy) ClientConfiguration(org.apache.cxf.jaxrs.client.ClientConfiguration)

Example 42 with HTTPClientPolicy

use of org.apache.cxf.transports.http.configuration.HTTPClientPolicy in project ddf by codice.

the class SecureCxfClientFactory method configureTimeouts.

/**
     * Configures the connection and receive timeouts. If any of the parameters are null, the timeouts
     * will be set to the system default.
     *
     * @param clientConfiguration Client configuration used for outgoing requests.
     * @param connectionTimeout   Connection timeout in milliseconds.
     * @param receiveTimeout      Receive timeout in milliseconds.
     */
protected void configureTimeouts(ClientConfiguration clientConfiguration, Integer connectionTimeout, Integer receiveTimeout) {
    HTTPConduit httpConduit = clientConfiguration.getHttpConduit();
    if (httpConduit == null) {
        LOGGER.info("HTTPConduit was null for {}. Unable to configure timeouts", this);
        return;
    }
    HTTPClientPolicy httpClientPolicy = httpConduit.getClient();
    if (httpClientPolicy == null) {
        httpClientPolicy = new HTTPClientPolicy();
    }
    if (connectionTimeout != null) {
        httpClientPolicy.setConnectionTimeout(connectionTimeout);
    } else {
        httpClientPolicy.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
    }
    if (receiveTimeout != null) {
        httpClientPolicy.setReceiveTimeout(receiveTimeout);
    } else {
        httpClientPolicy.setReceiveTimeout(DEFAULT_RECEIVE_TIMEOUT);
    }
    if (httpClientPolicy.isSetConnectionTimeout()) {
        LOGGER.debug("Connection timeout has been set.");
    } else {
        LOGGER.debug("Connection timeout has NOT been set.");
    }
    if (httpClientPolicy.isSetReceiveTimeout()) {
        LOGGER.debug("Receive timeout has been set.");
    } else {
        LOGGER.debug("Receive timeout has NOT been set.");
    }
    httpConduit.setClient(httpClientPolicy);
}
Also used : HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy)

Example 43 with HTTPClientPolicy

use of org.apache.cxf.transports.http.configuration.HTTPClientPolicy in project ddf by codice.

the class SecureCxfClientFactory method configureConduit.

private void configureConduit(ClientConfiguration clientConfig) {
    HTTPConduit httpConduit = clientConfig.getHttpConduit();
    if (httpConduit == null) {
        LOGGER.info("HTTPConduit was null for {}. Unable to configure security.", this);
        return;
    }
    if (allowRedirects) {
        HTTPClientPolicy clientPolicy = httpConduit.getClient();
        if (clientPolicy != null) {
            clientPolicy.setAutoRedirect(true);
            Bus bus = clientConfig.getBus();
            if (bus != null) {
                bus.getProperties().put("http.redirect.relative.uri", true);
            }
        }
    }
    TLSClientParameters tlsParams = httpConduit.getTlsClientParameters();
    if (tlsParams == null) {
        tlsParams = new TLSClientParameters();
    }
    tlsParams.setDisableCNCheck(disableCnCheck);
    tlsParams.setUseHttpsURLConnectionDefaultHostnameVerifier(true);
    tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(true);
    String cipherSuites = System.getProperty("https.cipherSuites");
    if (cipherSuites != null) {
        tlsParams.setCipherSuites(Arrays.asList(cipherSuites.split(",")));
    }
    KeyStore keyStore = null;
    KeyStore trustStore = null;
    try {
        keyStore = SecurityConstants.newKeystore();
        trustStore = SecurityConstants.newTruststore();
    } catch (KeyStoreException e) {
        LOGGER.debug("Unable to create keystore instance of type {}", System.getProperty(SecurityConstants.KEYSTORE_TYPE), e);
    }
    Path keyStoreFile = Paths.get(SecurityConstants.getKeystorePath());
    Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath());
    String ddfHome = System.getProperty("ddf.home");
    if (ddfHome != null) {
        Path ddfHomePath = Paths.get(ddfHome);
        if (!keyStoreFile.isAbsolute()) {
            keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString());
        }
        if (!trustStoreFile.isAbsolute()) {
            trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString());
        }
    }
    String keyStorePassword = SecurityConstants.getKeystorePassword();
    String trustStorePassword = SecurityConstants.getTruststorePassword();
    if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) {
        LOGGER.debug("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile, trustStoreFile);
        return;
    }
    try (InputStream kfis = Files.newInputStream(keyStoreFile)) {
        if (keyStore != null) {
            keyStore.load(kfis, keyStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system key file.", e);
    }
    try (InputStream tfis = Files.newInputStream(trustStoreFile)) {
        if (trustStore != null) {
            trustStore.load(tfis, trustStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system trust file.", e);
    }
    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
        tlsParams.setKeyManagers(keyManagerFactory.getKeyManagers());
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.debug("Unable to initialize KeyManagerFactory.", e);
    }
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        tlsParams.setTrustManagers(trustManagerFactory.getTrustManagers());
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.debug("Unable to initialize TrustManagerFactory.", e);
    }
    tlsParams.setCertAlias(SystemBaseUrl.getHost());
    httpConduit.setTlsClientParameters(tlsParams);
}
Also used : Path(java.nio.file.Path) Bus(org.apache.cxf.Bus) TLSClientParameters(org.apache.cxf.configuration.jsse.TLSClientParameters) InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) UnrecoverableKeyException(java.security.UnrecoverableKeyException) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy)

Example 44 with HTTPClientPolicy

use of org.apache.cxf.transports.http.configuration.HTTPClientPolicy in project uavstack by uavorg.

the class WSService method test.

@GET
@Path("test")
public String test() {
    TestService_Service s = new TestService_Service();
    TestService ts = s.getTestServicePort();
    // 设置客户端的配置信息,超时等.
    Client proxy = ClientProxy.getClient(ts);
    HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
    HTTPClientPolicy policy = new HTTPClientPolicy();
    // 连接服务器超时时间
    policy.setConnectionTimeout(30000);
    // 等待服务器响应超时时间
    policy.setReceiveTimeout(30000);
    conduit.setClient(policy);
    ts.echo();
    return "web service perfect";
}
Also used : HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) TestService_Service(com.creditease.monitorframework.fat.client.TestService_Service) TestService(com.creditease.monitorframework.fat.client.TestService) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy) Client(org.apache.cxf.endpoint.Client) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 45 with HTTPClientPolicy

use of org.apache.cxf.transports.http.configuration.HTTPClientPolicy in project uavstack by uavorg.

the class ChainService method circleTest.

@GET
@Path("circle_test")
public String circleTest(@QueryParam("time") int time) throws SQLException {
    if (time == 10) {
        return "";
    }
    // 首先进行redis读写操作
    System.out.println("Jedis OPS======================================================");
    Jedis jedis = new Jedis("localhost", 6379);
    jedis.set("foo", "bar");
    jedis.get("foo");
    jedis.close();
    // 进行服务之间交互
    CloseableHttpClient client = HttpClients.createDefault();
    HttpUriRequest http = new HttpGet("http://localhost:8080/com.creditease.uav.monitorframework.buildFat/rs/http/httpclienttest");
    try {
        HttpResponse resp1 = client.execute(http);
        System.out.println(resp1.getStatusLine());
        client.close();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // ws调用begin
    TestService_Service s = new TestService_Service();
    TestService ts = s.getTestServicePort();
    // 设置客户端的配置信息,超时等.
    Client proxy = ClientProxy.getClient(ts);
    HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
    HTTPClientPolicy policy = new HTTPClientPolicy();
    // 连接服务器超时时间
    policy.setConnectionTimeout(30000);
    // 等待服务器响应超时时间
    policy.setReceiveTimeout(30000);
    conduit.setClient(policy);
    ts.echo();
    // ws调用end
    // mysql调用
    Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/testdb", "root", "root");
    System.out.println("Statement -------------------->");
    Statement st = c.createStatement();
    st.execute("insert into mytest values (1,'zz',23)");
    st.close();
    System.out.println("PreparedStatement -------------------->");
    PreparedStatement ps = c.prepareStatement("insert into mytest values (?,?,?)");
    ps.setInt(1, 1);
    ps.setString(2, "zz");
    ps.setInt(3, 23);
    ps.execute();
    ps.close();
    ps = c.prepareStatement("select name from mytest where id=?");
    ps.setInt(1, 1);
    ps.executeQuery();
    ps.close();
    ps = c.prepareStatement("update mytest set age=24 where id=?");
    ps.setInt(1, 1);
    ps.executeUpdate();
    ps.close();
    ps = c.prepareStatement("delete from mytest where id=?");
    ps.setInt(1, 1);
    ps.executeUpdate();
    ps.close();
    c.close();
    // mongo
    MongoClient mongoClient = new MongoClient();
    mongoClient.listDatabaseNames().first();
    MongoDatabase db = mongoClient.getDatabase("apphubDataStore");
    db.listCollectionNames().first();
    MongoCollection<Document> collection = db.getCollection("test");
    collection.listIndexes().first();
    Document doc = new Document("name", "Amarcord Pizzeria").append("contact", new Document("phone", "264-555-0193").append("email", "amarcord.pizzeria@example.net").append("location", Arrays.asList(-73.88502, 40.749556))).append("stars", 2).append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));
    collection.insertOne(doc);
    collection.find().first();
    mongoClient.close();
    // 进行服务之间交互
    CloseableHttpClient client2 = HttpClients.createDefault();
    time++;
    HttpUriRequest http2 = new HttpGet("http://localhost:8080/com.creditease.uav.monitorframework.buildFat/rs/chain/circle_test" + "?time=" + time);
    try {
        HttpResponse resp1 = client2.execute(http2);
        System.out.println(resp1.getStatusLine());
        client2.close();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // dubbo调用begin
    WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);
    IMyDubboService mds = (IMyDubboService) wac.getBean("myDubboServiceC");
    mds.sayHello("zz");
    return "circle test perfect";
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) TestService_Service(com.creditease.monitorframework.fat.client.TestService_Service) TestService(com.creditease.monitorframework.fat.client.TestService) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) HttpGet(org.apache.http.client.methods.HttpGet) Connection(java.sql.Connection) HttpResponse(org.apache.http.HttpResponse) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) Document(org.bson.Document) ClientProtocolException(org.apache.http.client.ClientProtocolException) WebApplicationContext(org.springframework.web.context.WebApplicationContext) HTTPConduit(org.apache.cxf.transport.http.HTTPConduit) Jedis(redis.clients.jedis.Jedis) MongoClient(com.mongodb.MongoClient) IMyDubboService(com.creditease.monitorframework.fat.dubbo.IMyDubboService) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Client(org.apache.cxf.endpoint.Client) MongoClient(com.mongodb.MongoClient) MongoDatabase(com.mongodb.client.MongoDatabase) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Aggregations

HTTPClientPolicy (org.apache.cxf.transports.http.configuration.HTTPClientPolicy)78 HTTPConduit (org.apache.cxf.transport.http.HTTPConduit)53 Client (org.apache.cxf.endpoint.Client)31 Test (org.junit.Test)27 URL (java.net.URL)12 Bus (org.apache.cxf.Bus)10 IOException (java.io.IOException)8 AuthorizationPolicy (org.apache.cxf.configuration.security.AuthorizationPolicy)8 WebClient (org.apache.cxf.jaxrs.client.WebClient)7 ClientPolicyCalculator (org.apache.cxf.transport.http.policy.impl.ClientPolicyCalculator)7 QName (javax.xml.namespace.QName)6 ProxyAuthorizationPolicy (org.apache.cxf.configuration.security.ProxyAuthorizationPolicy)6 ClientConfiguration (org.apache.cxf.jaxrs.client.ClientConfiguration)6 TLSClientParameters (org.apache.cxf.configuration.jsse.TLSClientParameters)5 Greeter (org.apache.hello_world.Greeter)5 SOAPService (org.apache.hello_world.services.SOAPService)5 Map (java.util.Map)4 BindingProvider (javax.xml.ws.BindingProvider)4 Endpoint (org.apache.cxf.endpoint.Endpoint)4 HashMap (java.util.HashMap)3