Example usage for org.apache.http.client.protocol ClientContext AUTH_CACHE

List of usage examples for org.apache.http.client.protocol ClientContext AUTH_CACHE

Introduction

In this page you can find the example usage for org.apache.http.client.protocol ClientContext AUTH_CACHE.

Prototype

String AUTH_CACHE

To view the source code for org.apache.http.client.protocol ClientContext AUTH_CACHE.

Click Source Link

Document

Attribute name of a org.apache.http.client.AuthCache object that represents the auth scheme cache.

Usage

From source file:org.artificer.test.AbstractIntegrationTest.java

protected ClientRequest clientRequest(String endpoint) {
    DefaultHttpClient client = new DefaultHttpClient();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD);
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost targetHost = new HttpHost(HOST, PORT);
    authCache.put(targetHost, basicAuth);
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext);

    ClientRequest clientRequest = new ClientRequest(BASE_URL + endpoint, executor);
    return clientRequest;
}

From source file:org.eclipse.mylyn.commons.repositories.http.core.CommonHttpClient.java

private void prepareRequest(HttpRequestBase request, IOperationMonitor monitor) {
    UserCredentials httpCredentials = location.getCredentials(httpAuthenticationType);
    if (httpCredentials != null) {
        HttpUtil.configureAuthentication(getHttpClient(), location, httpCredentials);

        if (isPreemptiveAuthenticationEnabled()) {
            // create or pre-populate auth cache 
            HttpHost host = HttpUtil.createHost(request);
            Object authCache = getContext().getAttribute(ClientContext.AUTH_CACHE);
            if (authCache == null) {
                authCache = new BasicAuthCache();
                getContext().setAttribute(ClientContext.AUTH_CACHE, authCache);
            }//w  w  w  .j ava  2 s.c  om
            if (authCache instanceof BasicAuthCache) {
                if (((BasicAuthCache) authCache).get(host) == null) {
                    ((BasicAuthCache) authCache).put(host, new BasicScheme());
                }
            }
        }
    }
    HttpUtil.configureProxy(getHttpClient(), location);

    CertificateCredentials socketCredentials = location.getCredentials(AuthenticationType.CERTIFICATE);
    if (socketCredentials != null) {
        SslSupport support = new SslSupport(new TrustManager[] { new TrustAllTrustManager() },
                socketCredentials.getKeyStoreFileName(), socketCredentials.getPassword(),
                socketCredentials.getKeyStoreType());
        request.getParams().setParameter(SslSupport.class.getName(), support);
    } else {
        // remove the token that associates certificate credentials with the connection
        getContext().removeAttribute(ClientContext.USER_TOKEN);
    }

    getContext().setAttribute(HttpUtil.CONTEXT_KEY_MONITOR_THREAD, getMonitorThread());
}

From source file:org.zenoss.app.consumer.metric.impl.MetricServicePoster.java

/**
 * Login to the ZAuth service using the zenoss credentials.  Grab the tenant id from the http response and cache
 * the results for future requests./*www  .jav  a2 s .  c  o  m*/
 * @return tenant id
 * @throws IOException
 */
String getTenantId() throws IOException {
    if (tenantId == null) {
        log.debug("Requesting tenant id");
        // get the hostname and port from ProxyConfiguration
        ProxyConfiguration proxyConfig = configuration.getProxyConfiguration();
        String hostname = proxyConfig.getHostname();
        int port = proxyConfig.getPort();

        //configure request
        HttpContext context = new BasicHttpContext();
        HttpHost host = new HttpHost(hostname, port, "http");
        HttpPost post = new HttpPost(AUTHENTICATE_URL);
        post.addHeader(ACCEPT, APPLICATION_JSON.toString());

        //configure authentication
        String username = configuration.getZenossCredentials().getUsername();
        String password = configuration.getZenossCredentials().getPassword();
        if (!Strings.nullToEmpty(username).isEmpty()) {
            //configure credentials
            CredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                    new UsernamePasswordCredentials(username, password));
            context.setAttribute(ClientContext.CREDS_PROVIDER, provider);

            //setup auth cache
            AuthCache cache = new BasicAuthCache();
            BasicScheme scheme = new BasicScheme();
            cache.put(host, scheme);
            context.setAttribute(ClientContext.AUTH_CACHE, cache);
        }

        //handle response and collect tenantId
        HttpResponse response = null;
        try {
            response = httpClient.execute(host, post, context);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            log.debug("Tenant id request complete with status: {}", statusCode);
            if (statusCode >= 200 && statusCode <= 299) {
                Header id = response.getFirstHeader(ZenossTenant.ID_HTTP_HEADER);
                if (id == null) {
                    log.warn("Failed to get zauth tenant id after login");
                    throw new RuntimeException("Failed to get zauth tenant id after successful login");
                }
                tenantId = id.getValue();
                log.info("Got tenant id: {}", tenantId);
            } else {
                log.warn("Unsuccessful response from server: {}", response.getStatusLine());
                throw new IOException("Login for tenantId failed");
            }
        } catch (NullPointerException ex) {
            log.warn("npe retrieving tenantId: {}", ex);
        } finally {
            try {
                if (response != null) {
                    response.getEntity().getContent().close();
                }
            } catch (NullPointerException | IOException ex) {
                log.warn("Failed to close request: {}", ex);
            }
        }
    }
    return tenantId;
}

From source file:biocode.fims.ezid.EzidService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EzidService,
 * and so subsequent calls using this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 *
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 *
 * @throws EzidException if authentication fails for any reason
 *//*from  ww w  . ja  v  a 2  s  .com*/
public void login(String username, String password) throws EzidException {
    String msg;
    try {
        URI serviceUri = new URI(LOGIN_SERVICE);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme());
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        //System.out.println("authCache: " + authCache.toString());

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(LOGIN_SERVICE);
        body = httpClient.execute(httpget, handler, localcontext);
        String message = new String(body);
        msg = parseIdentifierResponse(message);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        /*
                org.apache.http.client.CookieStore cookieStore = httpClient.getCookieStore();
        System.out.println("\n\nCookies : ");
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Cookie: " + cookies.get(i));
        } */

    } catch (URISyntaxException e) {
        //System.out.println("URI SyntaxError Exception in LOGIN");
        throw new EzidException("Bad syntax for uri: " + LOGIN_SERVICE, e);
    } catch (ClientProtocolException e) {
        //System.out.println("ClientProtocol Exception in LOGIN");
        throw new EzidException(e);
    } catch (IOException e) {
        //System.out.println("IO Exception in LOGIN");
        throw new EzidException(e);
    }
    //System.out.println("Seems to be a successful LOGIN, msg= " + msg.toString());
}

From source file:org.energy_home.jemma.utils.rest.RestClient.java

public void setCredential(String hostname, int port, String username, String password) {
    HttpHost httpHost = new HttpHost(hostname, port);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port),
            new UsernamePasswordCredentials(username, password));
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);//  www  . ja v  a 2 s .c  o m
    // Add AuthCache to the execution context
    httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:ezid.EZIDService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EZIDService,
 * and so subsequent calls using this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 *
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 *
 * @throws EZIDException if authentication fails for any reason
 *///from   w w w . java2 s .co m
public void login(String username, String password) throws EZIDException {
    this.username = username;
    this.password = password;
    String msg;
    try {
        URI serviceUri = new URI(LOGIN_SERVICE);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme());
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        //System.out.println("authCache: " + authCache.toString());

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(LOGIN_SERVICE);
        body = httpclient.execute(httpget, handler, localcontext);
        String message = new String(body);
        msg = parseIdentifierResponse(message);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        /*
                org.apache.http.client.CookieStore cookieStore = httpclient.getCookieStore();
        System.out.println("\n\nCookies : ");
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Cookie: " + cookies.get(i));
        } */

    } catch (URISyntaxException e) {
        //System.out.println("URI SyntaxError Exception in LOGIN");
        throw new EZIDException("Bad syntax for uri: " + LOGIN_SERVICE, e);
    } catch (ClientProtocolException e) {
        //System.out.println("ClientProtocol Exception in LOGIN");
        throw new EZIDException(e);
    } catch (IOException e) {
        //System.out.println("IO Exception in LOGIN");
        throw new EZIDException(e);
    }
    //System.out.println("Seems to be a successful LOGIN, msg= " + msg.toString());
}

From source file:com.socrata.ApiBase.java

/**
 * Sets up http authentication (BASIC) for default requests
 *///w  w  w  .ja va  2s.c  om
private void setupBasicAuthentication() {
    Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
    CredentialsProvider credProvider = new BasicCredentialsProvider();

    credProvider.setCredentials(AuthScope.ANY, defaultcreds);

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();

    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.AUTH_CACHE, basicAuth);

    httpClient.setCredentialsProvider(credProvider);
}

From source file:org.trancecode.xproc.step.HttpRequestStepProcessor.java

private HttpClient prepareHttpClient(final XProcHttpRequest xProcRequest, final BasicHttpContext localContext) {
    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    final ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(schemeRegistry);
    final DefaultHttpClient httpClient = new DefaultHttpClient(connManager);
    final ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    if (xProcRequest.getCredentials() != null) {
        final List<String> authPref = Lists.newArrayList(AuthPolicy.BASIC, AuthPolicy.DIGEST);
        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPref);
        httpClient.setCredentialsProvider(xProcRequest.getCredentials());
        final AuthCache authCache = new BasicAuthCache();
        final BasicScheme basicAuth = new BasicScheme();
        authCache.put(xProcRequest.getHttpHost(), basicAuth);
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }/*from  ww w  .  j av a 2 s .com*/
    return httpClient;
}

From source file:com.sun.jersey.client.apache4.ApacheHttpClient4Handler.java

public ClientResponse handle(final ClientRequest cr) throws ClientHandlerException {

    final HttpUriRequest request = getUriHttpRequest(cr);

    writeOutBoundHeaders(cr.getHeaders(), request);

    try {//from  w  w w. j  a  va 2  s  . co m
        HttpResponse response;

        if (preemptiveBasicAuth) {
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            BasicHttpContext localContext = new BasicHttpContext();
            localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

            response = getHttpClient().execute(getHost(request), request, localContext);
        } else {
            response = getHttpClient().execute(getHost(request), request);
        }

        ClientResponse r = new ClientResponse(response.getStatusLine().getStatusCode(),
                getInBoundHeaders(response), new HttpClientResponseInputStream(response),
                getMessageBodyWorkers());
        if (!r.hasEntity()) {
            r.bufferEntity();
            r.close();
        }

        return r;
    } catch (Exception e) {
        throw new ClientHandlerException(e);
    }

}