Search in sources :

Example 6 with ClientFilter

use of com.sun.jersey.api.client.filter.ClientFilter in project coprhd-controller by CoprHD.

the class AuthSvcTests method createCookieHttpsClient.

protected Client createCookieHttpsClient(final String username, final String password) throws NoSuchAlgorithmException {
    // Disable server certificate validation as we are using
    // self-signed certificate
    disableCertificateValidation();
    final ClientConfig config = new DefaultClientConfig();
    final Client c = Client.create(config);
    c.addFilter(new LoggingFilter());
    c.setFollowRedirects(false);
    c.addFilter(new HTTPBasicAuthFilter(username, password));
    c.addFilter(new ClientFilter() {

        private ArrayList<Object> cookies;

        private ArrayList<Object> getCookiesToSet() {
            if (cookies != null && !cookies.isEmpty()) {
                ArrayList<Object> cookiesToSet = new ArrayList<Object>();
                StringBuilder cookieToAdd = new StringBuilder();
                for (Object cookieRaw : cookies) {
                    NewCookie cookie = (NewCookie) cookieRaw;
                    cookieToAdd.append(cookie.getName());
                    cookieToAdd.append("=");
                    cookieToAdd.append(cookie.getValue());
                    cookieToAdd.append("; ");
                }
                cookiesToSet.add(cookieToAdd);
                return cookiesToSet;
            }
            return null;
        }

        @Override
        public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
            ArrayList<Object> cookiesToSet = getCookiesToSet();
            if (cookiesToSet != null) {
                request.getHeaders().put("Cookie", cookiesToSet);
            }
            ClientResponse response = getNext().handle(request);
            if (response.getCookies() != null) {
                if (cookies == null) {
                    cookies = new ArrayList<Object>();
                }
                // simple addAll just for illustration (should probably check for duplicates and expired cookies)
                cookies.addAll(response.getCookies());
            }
            if (response.getStatus() == 302) {
                WebResource wb = c.resource(response.getLocation());
                cookiesToSet = getCookiesToSet();
                if (cookiesToSet != null) {
                    response = wb.header("Cookie", cookiesToSet).get(ClientResponse.class);
                } else {
                    response = wb.get(ClientResponse.class);
                }
            }
            return response;
        }
    });
    return c;
}
Also used : DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) LoggingFilter(com.sun.jersey.api.client.filter.LoggingFilter) ArrayList(java.util.ArrayList) HTTPBasicAuthFilter(com.sun.jersey.api.client.filter.HTTPBasicAuthFilter) ClientFilter(com.sun.jersey.api.client.filter.ClientFilter) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) ClientConfig(com.sun.jersey.api.client.config.ClientConfig) NewCookie(javax.ws.rs.core.NewCookie)

Example 7 with ClientFilter

use of com.sun.jersey.api.client.filter.ClientFilter in project coprhd-controller by CoprHD.

the class AuthSvcTests method createHttpsClient.

/**
 * Conveninence method to create a Client, and add authentication info
 * if desired. If addAuthFilter is set to true, credentials will be added
 * to a Basic Auth filter, and 302 will be followed manually, adding the auth token
 * on the final redirect to the service location. If addAuthFilter is set to
 * false, a regular 302 follow up will be done, no headers or basic auth will be
 * added.
 *
 * @throws NoSuchAlgorithmException
 */
protected Client createHttpsClient(final String username, final String password, boolean addAuthFilters) throws NoSuchAlgorithmException {
    // Disable server certificate validation as we are using
    // self-signed certificate
    disableCertificateValidation();
    final ClientConfig config = new DefaultClientConfig();
    final Client c = Client.create(config);
    c.addFilter(new LoggingFilter());
    if (addAuthFilters) {
        // do a "modified 302" below with copying the header
        c.setFollowRedirects(false);
        c.addFilter(new HTTPBasicAuthFilter(username, password));
        c.addFilter(new ClientFilter() {

            @Override
            public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
                if (_savedTokens.containsKey(username)) {
                    ArrayList<Object> token = new ArrayList<Object>();
                    token.add(_savedTokens.get(username));
                    request.getHeaders().put(AUTH_TOKEN_HEADER, token);
                }
                ClientResponse response = getNext().handle(request);
                if (response.getHeaders() != null && response.getHeaders().get(AUTH_TOKEN_HEADER) != null) {
                    _savedTokens.put(username, response.getHeaders().getFirst(AUTH_TOKEN_HEADER));
                }
                if (response.getHeaders() != null && response.getHeaders().get(AUTH_PROXY_TOKEN_HEADER) != null) {
                    _savedProxyTokens.put(username, response.getHeaders().getFirst(AUTH_PROXY_TOKEN_HEADER));
                }
                if (response.getStatus() == 302) {
                    WebResource wb = c.resource(response.getLocation());
                    response = wb.header(AUTH_TOKEN_HEADER, _savedTokens.get(username)).get(ClientResponse.class);
                }
                return response;
            }
        });
    } else {
        // no auth filter, and do a regular 302 follow up, don't copy any auth token.
        c.setFollowRedirects(true);
    }
    return c;
}
Also used : DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) LoggingFilter(com.sun.jersey.api.client.filter.LoggingFilter) ArrayList(java.util.ArrayList) HTTPBasicAuthFilter(com.sun.jersey.api.client.filter.HTTPBasicAuthFilter) ClientFilter(com.sun.jersey.api.client.filter.ClientFilter) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) ClientConfig(com.sun.jersey.api.client.config.ClientConfig)

Example 8 with ClientFilter

use of com.sun.jersey.api.client.filter.ClientFilter in project coprhd-controller by CoprHD.

the class BaseServiceClient method ensureInitialization.

private void ensureInitialization() {
    if (!initialized) {
        synchronized (this) {
            if (!initialized) {
                if ((serviceURI == null) || (coordinatorClient == null && keyGen == null)) {
                    throw SecurityException.fatals.failedToInitializeClientRequestHelper(serviceURI == null ? "serviceURI was null" : serviceURI.toString(), (coordinatorClient == null && keyGen == null) ? "both coordinatorClient and keyGenerator were null" : "coordinatorClient or kenGenerator was provided");
                } else {
                    if (keyGen == null) {
                        clientRequestHelper = new ClientRequestHelper(coordinatorClient, this.clientReadTimeout, this.clientConnectTimeout);
                    } else {
                        clientRequestHelper = new ClientRequestHelper(keyGen, this.clientReadTimeout, this.clientConnectTimeout);
                    }
                    clientRequestHelper.setDefaultSignatureType(defaultSignatureType);
                    // create and save a client for re-use, since it's an expensive object
                    // and concurrent request creation is thread-safe
                    client = clientRequestHelper.createClient();
                    if (filters.isEmpty()) {
                        client.addFilter(new ServiceClientRetryFilter(clientMaxRetries, clientRetryInterval));
                    } else {
                        for (ClientFilter filter : filters) {
                            client.addFilter(filter);
                        }
                    }
                    initialized = true;
                }
            }
        }
    }
}
Also used : ClientFilter(com.sun.jersey.api.client.filter.ClientFilter)

Example 9 with ClientFilter

use of com.sun.jersey.api.client.filter.ClientFilter in project coprhd-controller by CoprHD.

the class RESTClientUtil method authenticate.

private void authenticate(final Client c, final int authenticateCallCount) throws NoSuchAlgorithmException {
    final String methodName = "authenticate(): ";
    log.debug(methodName + "Called");
    disableCertificateValidation();
    c.setFollowRedirects(false);
    if (log.isTraceEnabled()) {
        c.addFilter(new LoggingFilter());
    }
    c.addFilter(new HTTPBasicAuthFilter(this._username, this._password));
    c.addFilter(new ClientFilter() {

        private Object authToken;

        // private int callCount = authenticateCallCount;
        @Override
        public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
            if (authToken != null) {
                request.getHeaders().put(AUTH_TOKEN_HEADER, Collections.singletonList(authToken));
            }
            ClientResponse response = getNext().handle(request);
            if (response.getHeaders() != null && response.getHeaders().containsKey(AUTH_TOKEN_HEADER)) {
                authToken = (response.getHeaders().getFirst(AUTH_TOKEN_HEADER));
            }
            if (response.getStatus() == 302) {
                WebResource wb = c.resource(response.getLocation());
                response = wb.header(AUTH_TOKEN_HEADER, authToken).get(ClientResponse.class);
            }
            return response;
        }
    });
}
Also used : ClientHandlerException(com.sun.jersey.api.client.ClientHandlerException) ClientResponse(com.sun.jersey.api.client.ClientResponse) LoggingFilter(com.sun.jersey.api.client.filter.LoggingFilter) ClientFilter(com.sun.jersey.api.client.filter.ClientFilter) WebResource(com.sun.jersey.api.client.WebResource) HTTPBasicAuthFilter(com.sun.jersey.api.client.filter.HTTPBasicAuthFilter) ClientRequest(com.sun.jersey.api.client.ClientRequest)

Example 10 with ClientFilter

use of com.sun.jersey.api.client.filter.ClientFilter in project coprhd-controller by CoprHD.

the class ApiTestBase method createHttpClient.

/**
 * create the httpclient, returns a BalancedWebResource that can be used the same
 * way a WebResource is.
 */
protected BalancedWebResource createHttpClient(final String username, final String attribute, final String groups, List<String> hostNames) {
    BalancedWebResource lbw = new BalancedWebResource();
    for (String h : hostNames) {
        final ClientConfig config = new DefaultClientConfig();
        final Client c = Client.create(config);
        c.addFilter(new ClientFilter() {

            @Override
            public ClientResponse handle(ClientRequest request) throws ClientHandlerException {
                ArrayList<Object> headerValue = new ArrayList<Object>();
                String userAndAttribute = username;
                if (!attribute.isEmpty()) {
                    userAndAttribute += "," + attribute;
                }
                headerValue.add(userAndAttribute + ";" + groups);
                request.getHeaders().put(NoAuthHeaderUserFilter.USER_INFO_HEADER_TAG, headerValue);
                return getNext().handle(request);
            }
        });
        lbw.addWebResource(c.resource(h));
    }
    return lbw;
}
Also used : ClientHandlerException(com.sun.jersey.api.client.ClientHandlerException) ClientResponse(com.sun.jersey.api.client.ClientResponse) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) ArrayList(java.util.ArrayList) ClientFilter(com.sun.jersey.api.client.filter.ClientFilter) ClientConfig(com.sun.jersey.api.client.config.ClientConfig) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) Client(com.sun.jersey.api.client.Client) ClientRequest(com.sun.jersey.api.client.ClientRequest)

Aggregations

ClientFilter (com.sun.jersey.api.client.filter.ClientFilter)10 HTTPBasicAuthFilter (com.sun.jersey.api.client.filter.HTTPBasicAuthFilter)6 ClientConfig (com.sun.jersey.api.client.config.ClientConfig)5 DefaultClientConfig (com.sun.jersey.api.client.config.DefaultClientConfig)5 LoggingFilter (com.sun.jersey.api.client.filter.LoggingFilter)5 ArrayList (java.util.ArrayList)5 ClientHandlerException (com.sun.jersey.api.client.ClientHandlerException)4 ClientRequest (com.sun.jersey.api.client.ClientRequest)4 ClientResponse (com.sun.jersey.api.client.ClientResponse)4 Client (com.sun.jersey.api.client.Client)3 WebResource (com.sun.jersey.api.client.WebResource)3 NewCookie (javax.ws.rs.core.NewCookie)3 EurekaEndpoint (com.netflix.discovery.shared.resolver.EurekaEndpoint)1 TransportClientFactory (com.netflix.discovery.shared.transport.TransportClientFactory)1 Jersey1TransportClientFactories (com.netflix.discovery.shared.transport.jersey.Jersey1TransportClientFactories)1 RemoteConnectionConfiguration (com.netflix.exhibitor.core.RemoteConnectionConfiguration)1 HTTPDigestAuthFilter (com.sun.jersey.api.client.filter.HTTPDigestAuthFilter)1 ApacheHttpClient4 (com.sun.jersey.client.apache4.ApacheHttpClient4)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1