Example usage for org.apache.http.client CredentialsProvider getCredentials

List of usage examples for org.apache.http.client CredentialsProvider getCredentials

Introduction

In this page you can find the example usage for org.apache.http.client CredentialsProvider getCredentials.

Prototype

Credentials getCredentials(AuthScope authscope);

Source Link

Document

Get the Credentials credentials for the given authentication scope.

Usage

From source file:com.example.pierre.applicompanies.library_http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from   www  . j  a va  2  s .c o m*/
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams);
    Utils.asserts(cm != null,
            "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null");

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    //remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:de.escidoc.core.common.util.service.ConnectionUtility.java

/**
 * Set Authentication to a given {@link DefaultHttpClient} instance.
 * //from  w w  w  . ja  v  a 2s.  co  m
 * @param url
 *            URL of resource.
 * @param username
 *            User name for authentication
 * @param password
 *            Password for authentication.
 * @throws WebserverSystemException
 *             Thrown if connection failed.
 */
public void setAuthentication(final DefaultHttpClient client, final URL url, final String username,
        final String password) {
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final AuthScope authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
    final Credentials creds = new UsernamePasswordCredentials(username, password);
    credsProvider.setCredentials(authScope, creds);
    client.setCredentialsProvider(credsProvider);
    // don't wait for auth request
    final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            final AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            final CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            final HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            // If not auth scheme has been initialized yet
            if (authState.getAuthScheme() == null) {
                final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                // Obtain credentials matching the target host
                final Credentials creds = credsProvider.getCredentials(authScope);
                // If found, generate BasicScheme preemptively
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    };
    client.addRequestInterceptor(preemptiveAuth, 0);
}

From source file:com.lfrj.diancan.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from  www  .  j  a va 2 s  . c  om*/
 * 
 * @param schemeRegistry
 *            SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    // remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.xinlan.otma.net.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from  w  w  w. j  a v a  2  s  .  co  m
 * 
 * @param schemeRegistry
 *            SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    // remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            } // end for
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                } // end for
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:cn.com.loopj.android.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*  ww w  .  j a  v  a2s  . com*/
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams);
    Utils.asserts(cm != null,
            "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null");

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    //remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from   w  ww  . jav  a2s.c  o  m
 *
 * @param schemeRegistry
 *            SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams);
    Utils.asserts(cm != null,
            "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null");

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    // remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:de.escidoc.core.common.business.fedora.FedoraUtility.java

/**
 * Returns a HttpClient object configured with credentials to access Fedora URLs.
 * /*w  ww.j  ava  2 s .  c o  m*/
 * @return A HttpClient object configured with credentials to access Fedora URLs.
 * @throws de.escidoc.core.common.exceptions.system.WebserverSystemException
 */
DefaultHttpClient getHttpClient() throws WebserverSystemException {
    try {
        if (this.httpClient == null) {
            final HttpParams params = new BasicHttpParams();
            ConnManagerParams.setMaxTotalConnections(params, HTTP_MAX_TOTAL_CONNECTIONS);

            final ConnPerRoute connPerRoute = new ConnPerRouteBean(HTTP_MAX_CONNECTIONS_PER_HOST);
            ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

            final Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
            final SchemeRegistry sr = new SchemeRegistry();
            sr.register(http);
            final ClientConnectionManager cm = new ThreadSafeClientConnManager(params, sr);

            this.httpClient = new DefaultHttpClient(cm, params);
            final URL url = new URL(this.fedoraUrl);
            final CredentialsProvider credsProvider = new BasicCredentialsProvider();

            final AuthScope authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            final Credentials creds = new UsernamePasswordCredentials(this.fedoraUser, this.fedoraPassword);
            credsProvider.setCredentials(authScope, creds);

            httpClient.setCredentialsProvider(credsProvider);
        }

        // don't wait for auth request
        final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

            @Override
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {

                final AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                final CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                final HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                // If not auth scheme has been initialized yet
                if (authState.getAuthScheme() == null) {
                    final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    // Obtain credentials matching the target host
                    final Credentials creds = credsProvider.getCredentials(authScope);
                    // If found, generate BasicScheme preemptively
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }

        };

        httpClient.addRequestInterceptor(preemptiveAuth, 0);

        // try only BASIC auth; skip to test NTLM and DIGEST

        return this.httpClient;
    } catch (final MalformedURLException e) {
        throw new WebserverSystemException("Fedora URL from configuration malformed.", e);
    }
}

From source file:org.apache.http.client.protocol.RequestAuthCache.java

private void doPreemptiveAuth(final HttpHost host, final AuthScheme authScheme, final AuthState authState,
        final CredentialsProvider credsProvider) {
    final String schemeName = authScheme.getSchemeName();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
    }/*w  w w .  j a  v a  2 s  .c o  m*/

    final AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName);
    final Credentials creds = credsProvider.getCredentials(authScope);

    if (creds != null) {
        if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) {
            authState.setState(AuthProtocolState.CHALLENGED);
        } else {
            authState.setState(AuthProtocolState.SUCCESS);
        }
        authState.update(authScheme, creds);
    } else {
        this.log.debug("No credentials for preemptive authentication");
    }
}

From source file:org.apache.http.impl.client.AuthenticationStrategyAdaptor.java

public Queue<AuthOption> select(final Map<String, Header> challenges, final HttpHost authhost,
        final HttpResponse response, final HttpContext context) throws MalformedChallengeException {
    Args.notNull(challenges, "Map of auth challenges");
    Args.notNull(authhost, "Host");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");

    final Queue<AuthOption> options = new LinkedList<AuthOption>();
    final CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);
    if (credsProvider == null) {
        this.log.debug("Credentials provider not set in the context");
        return options;
    }/*  ww  w  . j  ava  2s.c o m*/

    final AuthScheme authScheme;
    try {
        authScheme = this.handler.selectScheme(challenges, response, context);
    } catch (final AuthenticationException ex) {
        if (this.log.isWarnEnabled()) {
            this.log.warn(ex.getMessage(), ex);
        }
        return options;
    }
    final String id = authScheme.getSchemeName();
    final Header challenge = challenges.get(id.toLowerCase(Locale.US));
    authScheme.processChallenge(challenge);

    final AuthScope authScope = new AuthScope(authhost.getHostName(), authhost.getPort(), authScheme.getRealm(),
            authScheme.getSchemeName());

    final Credentials credentials = credsProvider.getCredentials(authScope);
    if (credentials != null) {
        options.add(new AuthOption(authScheme, credentials));
    }
    return options;
}

From source file:org.apache.http.impl.client.AuthenticationStrategyImpl.java

public Queue<AuthOption> select(final Map<String, Header> challenges, final HttpHost authhost,
        final HttpResponse response, final HttpContext context) throws MalformedChallengeException {
    Args.notNull(challenges, "Map of auth challenges");
    Args.notNull(authhost, "Host");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");
    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    final Queue<AuthOption> options = new LinkedList<AuthOption>();
    final Lookup<AuthSchemeProvider> registry = clientContext.getAuthSchemeRegistry();
    if (registry == null) {
        this.log.debug("Auth scheme registry not set in the context");
        return options;
    }//from  w  w  w .  j  ava2  s.  co m
    final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
    if (credsProvider == null) {
        this.log.debug("Credentials provider not set in the context");
        return options;
    }
    final RequestConfig config = clientContext.getRequestConfig();
    Collection<String> authPrefs = getPreferredAuthSchemes(config);
    if (authPrefs == null) {
        authPrefs = DEFAULT_SCHEME_PRIORITY;
    }
    if (this.log.isDebugEnabled()) {
        this.log.debug("Authentication schemes in the order of preference: " + authPrefs);
    }

    for (final String id : authPrefs) {
        final Header challenge = challenges.get(id.toLowerCase(Locale.US));
        if (challenge != null) {
            final AuthSchemeProvider authSchemeProvider = registry.lookup(id);
            if (authSchemeProvider == null) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication scheme " + id + " not supported");
                    // Try again
                }
                continue;
            }
            final AuthScheme authScheme = authSchemeProvider.create(context);
            authScheme.processChallenge(challenge);

            final AuthScope authScope = new AuthScope(authhost.getHostName(), authhost.getPort(),
                    authScheme.getRealm(), authScheme.getSchemeName());

            final Credentials credentials = credsProvider.getCredentials(authScope);
            if (credentials != null) {
                options.add(new AuthOption(authScheme, credentials));
            }
        } else {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Challenge for " + id + " authentication scheme not available");
                // Try again
            }
        }
    }
    return options;
}