Search in sources :

Example 46 with ClientBuilder

use of javax.ws.rs.client.ClientBuilder in project meecrowave by apache.

the class ConfigurationLoader method createClient.

private Client createClient(final Routes.Route route) {
    final ClientBuilder clientBuilder = ClientBuilder.newBuilder();
    clientBuilder.executorService(route.executor);
    clientBuilder.readTimeout(route.clientConfiguration.timeouts.read, MILLISECONDS);
    clientBuilder.connectTimeout(route.clientConfiguration.timeouts.connect, MILLISECONDS);
    if (route.clientConfiguration.sslConfiguration.acceptAnyCertificate) {
        clientBuilder.hostnameVerifier((host, session) -> true);
        clientBuilder.sslContext(createUnsafeSSLContext());
    } else if (route.clientConfiguration.sslConfiguration.keystoreLocation != null) {
        if (route.clientConfiguration.sslConfiguration.verifiedHostnames != null) {
            clientBuilder.hostnameVerifier((host, session) -> route.clientConfiguration.sslConfiguration.verifiedHostnames.contains(host));
        }
        clientBuilder.sslContext(createSSLContext(route.clientConfiguration.sslConfiguration.keystoreLocation, route.clientConfiguration.sslConfiguration.keystoreType, route.clientConfiguration.sslConfiguration.keystorePassword, route.clientConfiguration.sslConfiguration.truststoreType));
    }
    return clientBuilder.build();
}
Also used : X509Certificate(java.security.cert.X509Certificate) SSLContext(javax.net.ssl.SSLContext) Routes(org.apache.meecrowave.proxy.servlet.configuration.Routes) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) JsonBuilderFactory(javax.json.JsonBuilderFactory) Client(javax.ws.rs.client.Client) TrustManager(javax.net.ssl.TrustManager) KeyStoreException(java.security.KeyStoreException) JsonbConfig(javax.json.bind.JsonbConfig) Collections.singletonList(java.util.Collections.singletonList) JsonProvider(javax.json.spi.JsonProvider) JsonValue(javax.json.JsonValue) NotificationOptions(javax.enterprise.event.NotificationOptions) ClientBuilder(javax.ws.rs.client.ClientBuilder) Collectors.toMap(java.util.stream.Collectors.toMap) Json(javax.json.Json) Collector(java.util.stream.Collector) ThreadFactory(java.util.concurrent.ThreadFactory) Path(java.nio.file.Path) Collections.emptyMap(java.util.Collections.emptyMap) JsonObject(javax.json.JsonObject) JsonbBuilder(javax.json.bind.JsonbBuilder) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) Files(java.nio.file.Files) Optional.ofNullable(java.util.Optional.ofNullable) IOException(java.io.IOException) KeyStore(java.security.KeyStore) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) FileInputStream(java.io.FileInputStream) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) UUID(java.util.UUID) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) InvocationTargetException(java.lang.reflect.InvocationTargetException) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) X509TrustManager(javax.net.ssl.X509TrustManager) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Function.identity(java.util.function.Function.identity) Optional(java.util.Optional) Jsonb(javax.json.bind.Jsonb) JsonObjectBuilder(javax.json.JsonObjectBuilder) InputStream(java.io.InputStream) ClientBuilder(javax.ws.rs.client.ClientBuilder)

Example 47 with ClientBuilder

use of javax.ws.rs.client.ClientBuilder in project Payara by payara.

the class RemoteEJBContext method getClientBuilder.

private ClientBuilder getClientBuilder() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    ClientBuilder clientBuilder = ClientBuilder.newBuilder();
    if (environment.containsKey(JAXRS_CLIENT_CONNECT_TIMEOUT)) {
        clientBuilder.connectTimeout(getLong(environment.get(JAXRS_CLIENT_CONNECT_TIMEOUT)), MICROSECONDS);
    }
    if (environment.containsKey(JAXRS_CLIENT_EXECUTOR_SERVICE)) {
        clientBuilder.executorService(getInstance(environment.get(JAXRS_CLIENT_EXECUTOR_SERVICE), ExecutorService.class));
    }
    if (environment.containsKey(JAXRS_CLIENT_HOSTNAME_VERIFIER)) {
        clientBuilder.hostnameVerifier(getInstance(environment.get(JAXRS_CLIENT_HOSTNAME_VERIFIER), HostnameVerifier.class));
    }
    if (environment.containsKey(JAXRS_CLIENT_KEY_STORE)) {
        clientBuilder.keyStore(getInstance(environment.get(JAXRS_CLIENT_KEY_STORE), KeyStore.class), getPassword(environment.containsKey("keyStorePassword") ? environment.get("keyStorePassword") : environment.get(JAXRS_CLIENT_KEY_STORE_PASSOWRD)));
    }
    if (environment.containsKey(JAXRS_CLIENT_READ_TIMEOUT)) {
        clientBuilder.readTimeout(getLong(environment.get(JAXRS_CLIENT_READ_TIMEOUT)), MICROSECONDS);
    }
    if (environment.containsKey(JAXRS_CLIENT_SCHEDULED_EXECUTOR_SERVICE)) {
        clientBuilder.scheduledExecutorService(getInstance(environment.get(JAXRS_CLIENT_SCHEDULED_EXECUTOR_SERVICE), ScheduledExecutorService.class));
    }
    if (environment.containsKey(JAXRS_CLIENT_SSL_CONTEXT)) {
        clientBuilder.sslContext(getInstance(environment.get(JAXRS_CLIENT_SSL_CONTEXT), SSLContext.class));
    }
    if (environment.containsKey(JAXRS_CLIENT_TRUST_STORE)) {
        clientBuilder.trustStore(getInstance(environment.get(JAXRS_CLIENT_TRUST_STORE), KeyStore.class));
    }
    if (environment.containsKey(JAXRS_CLIENT_CONFIG)) {
        clientBuilder.withConfig(getInstance(environment.get(JAXRS_CLIENT_CONFIG), Configuration.class));
    }
    if (environment.containsKey(JAXRS_CLIENT_REQUEST_FILTER)) {
        Object value = environment.get(JAXRS_CLIENT_REQUEST_FILTER);
        if (value instanceof Class && (ClientRequestFilter.class.isAssignableFrom((Class) value))) {
            clientBuilder.register((Class<ClientRequestFilter>) value);
        } else if (value instanceof ClientRequestFilter) {
            clientBuilder.register((ClientRequestFilter) value);
        }
    }
    if (environment.containsKey(JAXRS_CLIENT_RESPONSE_FILTER)) {
        Object value = environment.get(JAXRS_CLIENT_RESPONSE_FILTER);
        if (value instanceof Class && (ClientResponseFilter.class.isAssignableFrom((Class) value))) {
            clientBuilder.register((Class<ClientResponseFilter>) value);
        } else if (value instanceof ClientResponseFilter) {
            clientBuilder.register((ClientResponseFilter) value);
        }
    }
    String providerPrincipal = (String) environment.get(PROVIDER_PRINCIPAL);
    String providerCredentials = (String) environment.get(PROVIDER_CREDENTIALS);
    if (providerPrincipal != null && providerCredentials != null) {
        String authType = (String) environment.get(PROVIDER_AUTH_TYPE);
        if (null == authType || BASIC_AUTH.equals(authType)) {
            clientBuilder.register(HttpAuthenticationFeature.basic(providerPrincipal, providerCredentials));
        } else if (DIGEST_AUTH.equals(authType)) {
            clientBuilder.register(HttpAuthenticationFeature.digest(providerPrincipal, providerCredentials));
        }
    }
    return clientBuilder;
}
Also used : ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Configuration(javax.ws.rs.core.Configuration) ClientResponseFilter(javax.ws.rs.client.ClientResponseFilter) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) ClientBuilder(javax.ws.rs.client.ClientBuilder) HostnameVerifier(javax.net.ssl.HostnameVerifier)

Example 48 with ClientBuilder

use of javax.ws.rs.client.ClientBuilder in project athenz by yahoo.

the class MSDClient method initClient.

/**
 * Initialize the client for class constructors
 *
 * @param url        MSD Server url
 * @param sslContext SSLContext for service authentication
 */
private void initClient(String url, SSLContext sslContext) {
    String msdUrl;
    if (url == null || "".equals(url)) {
        LOGGER.error("No MSD URL is specified. Trying to look in environment.");
        msdUrl = System.getProperty(MSD_CLIENT_PROP_MSD_URL);
        if (msdUrl == null || "".equals(msdUrl)) {
            throw new IllegalArgumentException("MSD URL must be specified");
        }
    } else {
        msdUrl = url;
    }
    /* determine our read and connect timeouts */
    int readTimeout = Integer.parseInt(System.getProperty(MSD_CLIENT_PROP_READ_TIMEOUT, "30000"));
    int connectTimeout = Integer.parseInt(System.getProperty(MSD_CLIENT_PROP_CONNECT_TIMEOUT, "30000"));
    ClientBuilder builder = getClientBuilder();
    builder = builder.sslContext(sslContext);
    final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ClientConfig clientConfig = new ClientConfig(jacksonJsonProvider);
    clientConfig.connectorProvider(new ApacheConnectorProvider());
    // JerseyClientBuilder::withConfig() replaces the existing config with the new client
    // config. Hence the client config should be added to the builder before the timeouts.
    // Otherwise the timeout settings would be overridden.
    Client rsClient = builder.withConfig(clientConfig).connectTimeout(connectTimeout, TimeUnit.MILLISECONDS).readTimeout(readTimeout, TimeUnit.MILLISECONDS).build();
    client = new MSDRDLGeneratedClient(msdUrl, rsClient);
}
Also used : JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) ApacheConnectorProvider(org.glassfish.jersey.apache.connector.ApacheConnectorProvider) JacksonJaxbJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider) ClientConfig(org.glassfish.jersey.client.ClientConfig) Client(javax.ws.rs.client.Client) ClientBuilder(javax.ws.rs.client.ClientBuilder)

Example 49 with ClientBuilder

use of javax.ws.rs.client.ClientBuilder in project ats-framework by Axway.

the class RestClient method constructApacheConnectorInvocationBuilder.

private void constructApacheConnectorInvocationBuilder(String descriptionToken, boolean suppressHttpComplianceValidation) {
    // create the client config object
    ClientConfig clientConfig = createClientConfig(suppressHttpComplianceValidation);
    // check if user had specified custom connection manager and custom connection factory
    boolean hasConnectionManager = this.clientConfigurator.getConnectionManager() != null;
    boolean hasConnectionFactory = this.clientConfigurator.getConnectionFactory() != null;
    // handle HTTPS requests
    Registry registry = null;
    if (isHttps()) {
        // configure Trust-all SSL context
        if (!hasConnectionManager) {
        }
        registry = constructRegistry();
    }
    HttpClientConnectionManager connectionManager = null;
    HttpConnectionFactory connectionFactory = null;
    if (hasConnectionManager) {
        connectionManager = this.clientConfigurator.getConnectionManager();
        if (hasConnectionFactory) {
            connectionFactory = this.clientConfigurator.getConnectionFactory();
        } else {
            throw new RuntimeException("Connection manager was specified, but connection factory was not. " + "Provide both if you want to use custom connection manager");
        }
    } else {
        if (hasConnectionFactory) {
            connectionFactory = this.clientConfigurator.getConnectionFactory();
        } else {
            connectionFactory = new ManagedHttpClientConnectionFactory();
        }
        if (registry != null) {
            if (usePooling) {
                connectionManager = new PoolingHttpClientConnectionManager(registry, connectionFactory);
            } else {
                connectionManager = new BasicHttpClientConnectionManager(registry, connectionFactory);
            }
        } else {
            if (usePooling) {
                connectionManager = new PoolingHttpClientConnectionManager(connectionFactory);
            } else {
                connectionManager = new BasicHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build(), connectionFactory);
            }
        }
    }
    if (connectionManager != null && connectionManager instanceof PoolingHttpClientConnectionManager) {
        // 10 sec
        ((PoolingHttpClientConnectionManager) connectionManager).setValidateAfterInactivity(10 * 1000);
    }
    try {
        Class<?> apacheClientProperties = Class.forName(RestClient.APACHE_CLIENT_PROPERTIES_CLASSNAME);
        clientConfig.property((String) apacheClientProperties.getDeclaredField("CONNECTION_MANAGER").get(null), connectionManager);
    } catch (Exception e) {
        throw new RuntimeException("Could not set validity timeinterval for '" + connectionManager.getClass().getName() + "'", e);
    }
    // create the client builder
    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig);
    // now create the client
    createClient(clientBuilder);
    createInvocationBuilder(descriptionToken);
}
Also used : HttpConnectionFactory(org.apache.http.conn.HttpConnectionFactory) ManagedHttpClientConnectionFactory(org.apache.http.impl.conn.ManagedHttpClientConnectionFactory) Registry(org.apache.http.config.Registry) ClientConfig(org.glassfish.jersey.client.ClientConfig) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) RestException(com.axway.ats.action.exceptions.RestException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) ClientBuilder(javax.ws.rs.client.ClientBuilder)

Example 50 with ClientBuilder

use of javax.ws.rs.client.ClientBuilder in project ats-framework by Axway.

the class RestClient method constructHttpUrlConnectionInvocationBuilder.

private void constructHttpUrlConnectionInvocationBuilder(String descriptionToken, boolean suppressHttpComplianceValidation) {
    // create the client config object
    ClientConfig clientConfig = createClientConfig(suppressHttpComplianceValidation);
    // create the client builder
    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig);
    // handle HTTPS requests
    if (isHttps()) {
        // configure Trust-all SSL context
        checkSupportedProtocols();
        SSLContext sslContext = SslUtils.getSSLContext(clientConfigurator.getCertificateFileName(), clientConfigurator.getCertificateFilePassword(), supportedProtocols[0]);
        clientBuilder = clientBuilder.sslContext(sslContext).hostnameVerifier(new SslUtils.DefaultHostnameVerifier());
    }
    // now create the client
    createClient(clientBuilder);
    createInvocationBuilder(descriptionToken);
}
Also used : SSLContext(javax.net.ssl.SSLContext) ClientConfig(org.glassfish.jersey.client.ClientConfig) ClientBuilder(javax.ws.rs.client.ClientBuilder)

Aggregations

ClientBuilder (javax.ws.rs.client.ClientBuilder)57 Client (javax.ws.rs.client.Client)41 Response (javax.ws.rs.core.Response)26 Test (org.junit.Test)26 RunAsClient (org.jboss.arquillian.container.test.api.RunAsClient)24 AuthenticationContext (org.wildfly.security.auth.client.AuthenticationContext)24 URL (java.net.URL)20 SSLContext (javax.net.ssl.SSLContext)16 ClientConfig (org.glassfish.jersey.client.ClientConfig)15 AuthenticationConfiguration (org.wildfly.security.auth.client.AuthenticationConfiguration)13 ModelControllerClient (org.jboss.as.controller.client.ModelControllerClient)11 InvalidAuthenticationConfigurationException (org.wildfly.security.auth.client.InvalidAuthenticationConfigurationException)11 WebTarget (javax.ws.rs.client.WebTarget)10 IOException (java.io.IOException)9 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)9 KeyStore (java.security.KeyStore)7 HttpClient (org.apache.http.client.HttpClient)7 AuthenticationContextConfigurationClient (org.wildfly.security.auth.client.AuthenticationContextConfigurationClient)6 MalformedURLException (java.net.MalformedURLException)5 HostnameVerifier (javax.net.ssl.HostnameVerifier)5