Search in sources :

Example 1 with ClientBuilder

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

the class RestClient method constructInvocationBuilder.

private Invocation.Builder constructInvocationBuilder(String descriptionToken) {
    if (StringUtils.isNullOrEmpty(this.uri)) {
        throw new IllegalArgumentException("Null or empty target URI. Please specify a valid one");
    }
    URL url;
    try {
        url = new URL(this.uri);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Please specify a valid URI. You have provided '" + this.uri + "'");
    }
    // remember these client id keys in order to work around a Jersey memory leak
    List<String> clientIdKeys = new ArrayList<String>();
    clientIdKeys.add("host_base_path=" + url.getProtocol() + "://" + url.getHost() + ":" + url.getPort());
    // create the client builder
    ClientBuilder clientBuilder = ClientBuilder.newBuilder();
    if (this.uri.startsWith("https")) {
        // configure Trust-all SSL context
        SSLContext sslContext = SslUtils.getSSLContext(clientConfigurator.getCertificateFileName(), clientConfigurator.getCertificateFilePassword(), supportedProtocols[0]);
        clientBuilder = clientBuilder.sslContext(sslContext).hostnameVerifier(new SslUtils.DefaultHostnameVerifier());
        clientIdKeys.add("cert_file=" + clientConfigurator.getCertificateFileName());
    }
    // (e.g. features or individual entity providers, filters or interceptors)
    for (Object provider : clientConfigurator.getProviders()) {
        clientBuilder.register(provider);
        clientIdKeys.add(provider.getClass().getName());
    }
    for (Class<?> providerClass : clientConfigurator.getProviderClasses()) {
        clientBuilder.register(providerClass);
        clientIdKeys.add(providerClass.getName());
    }
    // attach any configuration properties
    Map<String, Object> properties = clientConfigurator.getProperties();
    for (Entry<String, Object> propertyEntry : properties.entrySet()) {
        clientBuilder.property(propertyEntry.getKey(), propertyEntry.getValue());
        clientIdKeys.add(propertyEntry.getKey() + "=" + propertyEntry.getValue());
    }
    // basic authorization
    if (username != null) {
        clientIdKeys.add("user=" + username);
        clientIdKeys.add("password=" + password);
        clientBuilder.register(HttpAuthenticationFeature.basic(username, password));
    }
    // now create the client
    client = getClient(clientIdKeys, clientBuilder);
    if (debugLevel != RESTDebugLevel.NONE) {
        RequestFilter requestFilter = new RequestFilter();
        requestFilter.setDebugLevel(debugLevel);
        client.register(requestFilter);
    }
    WebTarget webTarget = client.target(this.uri);
    // navigate to internal resource
    for (String token : resourcePath) {
        webTarget = webTarget.path(token);
    }
    // add request parameters
    for (Entry<String, List<String>> requestParamEntry : requestParameters.entrySet()) {
        for (String requestParamValue : requestParamEntry.getValue()) {
            webTarget = webTarget.queryParam(requestParamEntry.getKey(), requestParamValue);
        }
    }
    log.info("We will " + descriptionToken + " " + webTarget.getUri());
    Invocation.Builder invocationBuilder = webTarget.request();
    // set response media type
    if (!StringUtils.isNullOrEmpty(responseMediaType)) {
        invocationBuilder = invocationBuilder.accept(RestMediaType.toMediaType(responseMediaType, responseMediaCharset));
    }
    // add request headers
    for (Entry<String, Object> requestHeaderEntry : requestHeaders.entrySet()) {
        invocationBuilder.header(requestHeaderEntry.getKey(), requestHeaderEntry.getValue());
    }
    // add request cookies
    for (Cookie cookie : cookies) {
        invocationBuilder.cookie(cookie);
    }
    return invocationBuilder;
}
Also used : Cookie(javax.ws.rs.core.Cookie) MalformedURLException(java.net.MalformedURLException) Invocation(javax.ws.rs.client.Invocation) ArrayList(java.util.ArrayList) SSLContext(javax.net.ssl.SSLContext) URL(java.net.URL) ArrayList(java.util.ArrayList) List(java.util.List) WebTarget(javax.ws.rs.client.WebTarget) ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) ClientBuilder(javax.ws.rs.client.ClientBuilder)

Example 2 with ClientBuilder

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

the class BonitaAuthFilter method filter.

@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    if (requestContext.getCookies().get("JSESSIONID") == null) {
        String username = bonitaApiConfig.getUsername();
        String password = bonitaApiConfig.getPassword();
        String bonitaApiToken = null;
        if (ObjectHelper.isEmpty(username)) {
            throw new IllegalArgumentException("Username provided is null or empty.");
        }
        if (ObjectHelper.isEmpty(password)) {
            throw new IllegalArgumentException("Password provided is null or empty.");
        }
        ClientBuilder clientBuilder = ClientBuilder.newBuilder();
        Client client = clientBuilder.build();
        WebTarget webTarget = client.target(bonitaApiConfig.getBaseBonitaURI()).path("loginservice");
        MultivaluedMap<String, String> form = new MultivaluedHashMap<String, String>();
        form.add("username", username);
        form.add("password", password);
        form.add("redirect", "false");
        Response response = webTarget.request().accept(MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
        Map<String, NewCookie> cr = response.getCookies();
        ArrayList<Object> cookies = new ArrayList<>();
        for (NewCookie cookie : cr.values()) {
            if ("X-Bonita-API-Token".equals(cookie.getName())) {
                bonitaApiToken = cookie.getValue();
                requestContext.getHeaders().add("X-Bonita-API-Token", bonitaApiToken);
            }
            cookies.add(cookie.toCookie());
        }
        requestContext.getHeaders().put("Cookie", cookies);
    }
}
Also used : ArrayList(java.util.ArrayList) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Response(javax.ws.rs.core.Response) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) ClientBuilder(javax.ws.rs.client.ClientBuilder) NewCookie(javax.ws.rs.core.NewCookie)

Example 3 with ClientBuilder

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

the class BonitaAPIUtil method getInstance.

public static BonitaAPIUtil getInstance(BonitaAPIConfig bonitaAPIConfig) {
    if (instance == null) {
        instance = new BonitaAPIUtil();
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.register(MultiPartFeature.class);
        clientConfig.register(JacksonJsonProvider.class);
        Logger logger = Logger.getLogger("org.bonitasoft.camel.bonita.api.util.BonitaAPIUtil");
        Feature feature = new LoggingFeature(logger, Level.INFO, null, null);
        clientConfig.register(feature);
        ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig);
        Client client = clientBuilder.build();
        client.register(new JsonClientFilter());
        client.register(new BonitaAuthFilter(bonitaAPIConfig));
        instance.setWebTarget(client.target(bonitaAPIConfig.getBaseBonitaURI()));
    }
    return instance;
}
Also used : LoggingFeature(org.glassfish.jersey.logging.LoggingFeature) JsonClientFilter(org.apache.camel.component.bonita.api.filter.JsonClientFilter) ClientConfig(org.glassfish.jersey.client.ClientConfig) Logger(java.util.logging.Logger) Client(javax.ws.rs.client.Client) BonitaAuthFilter(org.apache.camel.component.bonita.api.filter.BonitaAuthFilter) Feature(javax.ws.rs.core.Feature) MultiPartFeature(org.glassfish.jersey.media.multipart.MultiPartFeature) LoggingFeature(org.glassfish.jersey.logging.LoggingFeature) ClientBuilder(javax.ws.rs.client.ClientBuilder)

Example 4 with ClientBuilder

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

the class WebUtils method createClientHelper.

/**
 * A helper method for creating clients. The client will be created using
 * the given configuration and security context. Additionally, the client
 * will be automatically configured for JSON serialization/deserialization.
 *
 * @param config client configuration
 * @param ctx    security context, which may be null for non-secure client
 *               creation
 * @return a Client instance
 */
private static Client createClientHelper(final ClientConfig config, final SSLContext ctx) {
    ClientBuilder clientBuilder = ClientBuilder.newBuilder();
    if (config != null) {
        clientBuilder = clientBuilder.withConfig(config);
    }
    if (ctx != null) {
        // custom hostname verifier that checks subject alternative names against the hostname of the URI
        final HostnameVerifier hostnameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(final String hostname, final SSLSession ssls) {
                try {
                    for (final Certificate peerCertificate : ssls.getPeerCertificates()) {
                        if (peerCertificate instanceof X509Certificate) {
                            final X509Certificate x509Cert = (X509Certificate) peerCertificate;
                            final List<String> subjectAltNames = CertificateUtils.getSubjectAlternativeNames(x509Cert);
                            if (subjectAltNames.contains(hostname.toLowerCase())) {
                                return true;
                            }
                        }
                    }
                } catch (final SSLPeerUnverifiedException | CertificateParsingException ex) {
                    logger.warn("Hostname Verification encountered exception verifying hostname due to: " + ex, ex);
                }
                return false;
            }
        };
        clientBuilder = clientBuilder.sslContext(ctx).hostnameVerifier(hostnameVerifier);
    }
    clientBuilder = clientBuilder.register(ObjectMapperResolver.class).register(JacksonJaxbJsonProvider.class);
    return clientBuilder.build();
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SSLSession(javax.net.ssl.SSLSession) JacksonJaxbJsonProvider(org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider) X509Certificate(java.security.cert.X509Certificate) ClientBuilder(javax.ws.rs.client.ClientBuilder) HostnameVerifier(javax.net.ssl.HostnameVerifier) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 5 with ClientBuilder

use of javax.ws.rs.client.ClientBuilder in project nifi-registry by apache.

the class IntegrationTestBase method createClientFromConfig.

private static Client createClientFromConfig(NiFiRegistryClientConfig registryClientConfig) {
    final ClientConfig clientConfig = new ClientConfig();
    clientConfig.register(jacksonJaxbJsonProvider());
    final ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig);
    final SSLContext sslContext = registryClientConfig.getSslContext();
    if (sslContext != null) {
        clientBuilder.sslContext(sslContext);
    }
    final HostnameVerifier hostnameVerifier = registryClientConfig.getHostnameVerifier();
    if (hostnameVerifier != null) {
        clientBuilder.hostnameVerifier(hostnameVerifier);
    }
    return clientBuilder.build();
}
Also used : SSLContext(javax.net.ssl.SSLContext) NiFiRegistryClientConfig(org.apache.nifi.registry.client.NiFiRegistryClientConfig) ClientConfig(org.glassfish.jersey.client.ClientConfig) ClientBuilder(javax.ws.rs.client.ClientBuilder) HostnameVerifier(javax.net.ssl.HostnameVerifier)

Aggregations

ClientBuilder (javax.ws.rs.client.ClientBuilder)54 Client (javax.ws.rs.client.Client)38 Test (org.junit.Test)26 Response (javax.ws.rs.core.Response)24 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 IOException (java.io.IOException)7 WebTarget (javax.ws.rs.client.WebTarget)7 HttpClient (org.apache.http.client.HttpClient)7 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)6 AuthenticationContextConfigurationClient (org.wildfly.security.auth.client.AuthenticationContextConfigurationClient)6 MalformedURLException (java.net.MalformedURLException)5 KeyStore (java.security.KeyStore)5 HostnameVerifier (javax.net.ssl.HostnameVerifier)5