Search in sources :

Example 26 with DefaultClientConfig

use of com.sun.jersey.api.client.config.DefaultClientConfig in project coprhd-controller by CoprHD.

the class ApiTestBase method createHttpsClient.

protected BalancedWebResource createHttpsClient(final String username, final String password, List<String> hosts, boolean addAuthFilters) throws NoSuchAlgorithmException {
    String verb = System.getenv("API_TEST_VERBOSE");
    boolean verbose = false;
    if (verb != null && verb.equalsIgnoreCase("true")) {
        verbose = true;
    }
    // Disable server certificate validation as we are using
    // self-signed certificate
    disableCertificateValidation();
    BalancedWebResource lbw = new BalancedWebResource();
    for (String h : hosts) {
        final ClientConfig config = new DefaultClientConfig();
        final Client c = Client.create(config);
        if (verbose) {
            c.addFilter(new LoggingFilter());
        }
        if (addAuthFilters) {
            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);
                    // this only used to inspect cookies after the fact.
                    if (null == _lastUsedAuthTokenCookie) {
                        System.out.println("Cookie was null");
                        List<NewCookie> allCookies = response.getCookies();
                        System.out.println("Cookie list size:" + allCookies.size());
                        for (NewCookie ck : allCookies) {
                            System.out.print("Cookie name " + ck.getName());
                            if (ck.getName().equals(AUTH_TOKEN_HEADER)) {
                                _lastUsedAuthTokenCookie = ck.getValue();
                                break;
                            }
                        }
                    }
                    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 {
            c.setFollowRedirects(true);
        }
        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) LoggingFilter(com.sun.jersey.api.client.filter.LoggingFilter) ArrayList(java.util.ArrayList) WebResource(com.sun.jersey.api.client.WebResource) HTTPBasicAuthFilter(com.sun.jersey.api.client.filter.HTTPBasicAuthFilter) ClientFilter(com.sun.jersey.api.client.filter.ClientFilter) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) 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) NewCookie(javax.ws.rs.core.NewCookie)

Example 27 with DefaultClientConfig

use of com.sun.jersey.api.client.config.DefaultClientConfig 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 28 with DefaultClientConfig

use of com.sun.jersey.api.client.config.DefaultClientConfig 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 29 with DefaultClientConfig

use of com.sun.jersey.api.client.config.DefaultClientConfig in project coprhd-controller by CoprHD.

the class HP3PARApiFactory method configureClient.

public ClientConfig configureClient() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (java.security.GeneralSecurityException ex) {
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
    ClientConfig config = new DefaultClientConfig();
    try {
        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }, ctx));
    } catch (Exception e) {
    }
    config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    return config;
}
Also used : DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) SSLSession(javax.net.ssl.SSLSession) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) HP3PARException(com.emc.storageos.hp3par.impl.HP3PARException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) X509TrustManager(javax.net.ssl.X509TrustManager) ClientConfig(com.sun.jersey.api.client.config.ClientConfig) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) HTTPSProperties(com.sun.jersey.client.urlconnection.HTTPSProperties)

Example 30 with DefaultClientConfig

use of com.sun.jersey.api.client.config.DefaultClientConfig in project coprhd-controller by CoprHD.

the class NotificationManagerImpl method notifyApprovalService.

private void notifyApprovalService(String approvalUrl, Order order, ApprovalRequest approval) {
    try {
        ApprovalRestRep approvalRestRep = map(approval);
        ClientConfig config = new DefaultClientConfig();
        config.getClasses().add(JacksonJaxbJsonProvider.class);
        Client client = Client.create(config);
        WebResource.Builder webResource = client.resource(UriBuilder.fromUri(approvalUrl).build()).type(MediaType.APPLICATION_JSON);
        ClientResponse response = webResource.post(ClientResponse.class, approvalRestRep);
        if (isError(response)) {
            log.error(String.format("Approval POST failed: %s, %s %s", approvalUrl, response.getStatus(), response.getEntity(String.class)));
        } else {
            log.debug(String.format("Approval POST succeeded: %s, %s %s", approvalUrl, response.getStatus(), response.getEntity(String.class)));
        }
    } catch (ClientHandlerException e) {
        log.error(String.format("Approval POST failed: %s, %s, %s", approvalUrl, e.getCause(), e.getMessage()));
    }
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) ClientHandlerException(com.sun.jersey.api.client.ClientHandlerException) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) ApprovalRestRep(com.emc.vipr.model.catalog.ApprovalRestRep) WebResource(com.sun.jersey.api.client.WebResource) ClientConfig(com.sun.jersey.api.client.config.ClientConfig) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) Client(com.sun.jersey.api.client.Client) CoordinatorClient(com.emc.storageos.coordinator.client.service.CoordinatorClient)

Aggregations

DefaultClientConfig (com.sun.jersey.api.client.config.DefaultClientConfig)65 ClientConfig (com.sun.jersey.api.client.config.ClientConfig)55 Client (com.sun.jersey.api.client.Client)42 WebResource (com.sun.jersey.api.client.WebResource)21 HTTPBasicAuthFilter (com.sun.jersey.api.client.filter.HTTPBasicAuthFilter)15 ClientResponse (com.sun.jersey.api.client.ClientResponse)14 HTTPSProperties (com.sun.jersey.client.urlconnection.HTTPSProperties)9 HostnameVerifier (javax.net.ssl.HostnameVerifier)7 SSLSession (javax.net.ssl.SSLSession)7 TrustManager (javax.net.ssl.TrustManager)7 ClientHandlerException (com.sun.jersey.api.client.ClientHandlerException)6 URLConnectionClientHandler (com.sun.jersey.client.urlconnection.URLConnectionClientHandler)6 IOException (java.io.IOException)6 VisibleForTesting (com.google.common.annotations.VisibleForTesting)5 ClientFilter (com.sun.jersey.api.client.filter.ClientFilter)5 LoggingFilter (com.sun.jersey.api.client.filter.LoggingFilter)5 SecureRandom (java.security.SecureRandom)5 SSLContext (javax.net.ssl.SSLContext)5 URISyntaxException (java.net.URISyntaxException)4 ArrayList (java.util.ArrayList)4