Example usage for org.apache.http.impl.client DefaultHttpClient setCredentialsProvider

List of usage examples for org.apache.http.impl.client DefaultHttpClient setCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient setCredentialsProvider.

Prototype

public synchronized void setCredentialsProvider(final CredentialsProvider credsProvider) 

Source Link

Usage

From source file:fr.paris.lutece.plugins.mylutece.modules.oauth.authentication.OAuthAuthentication.java

/**
 * Builds a new {@link HttpClient}/*www  .  j a  va 2 s .  c  o m*/
 * @return new HttpClient
 */
private HttpClient getHttpClient() {
    DefaultHttpClient client = new DefaultHttpClient();

    String strUserName = AppPropertiesService.getProperty(PROPERTY_PROXY_USERNAME);
    String strPassword = AppPropertiesService.getProperty(PROPERTY_PROXY_PASSWORD);
    String strDomainName = AppPropertiesService.getProperty(PROPERTY_DOMAIN_NAME);

    if (StringUtils.isNotBlank(strUserName) && StringUtils.isNotBlank(strPassword)) {
        // at least Userpasswordcredz
        Credentials creds;

        if (StringUtils.isBlank(strDomainName)) {
            creds = new UsernamePasswordCredentials(strUserName, strPassword);
        } else {
            creds = new NTCredentials(strUserName, strPassword, "", strDomainName);
        }

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, creds);
        client.setCredentialsProvider(credsProvider);

        HttpHost proxy = new HttpHost(AppPropertiesService.getProperty(PROPERTY_PROXY_HOST),
                AppPropertiesService.getPropertyInt(PROPERTY_PROXY_PORT, 8080));
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    return client;
}

From source file:net.java.sip.communicator.service.httputil.HttpUtils.java

/**
 * Returns the preconfigured http client,
 * using CertificateVerificationService, timeouts, user-agent,
 * hostname verifier, proxy settings are used from global java settings,
 * if protected site is hit asks for credentials
 * using util.swing.AuthenticationWindow.
 * @param usernamePropertyName the property to use to retrieve/store
 * username value if protected site is hit, for username
 * ConfigurationService service is used.
 * @param passwordPropertyName the property to use to retrieve/store
 * password value if protected site is hit, for password
 * CredentialsStorageService service is used.
 * @param credentialsProvider if not null provider will bre reused
 * in the new client/*from  w  w  w .  j ava2  s . c o m*/
 * @param address the address we will be connecting to
 */
public static DefaultHttpClient getHttpClient(String usernamePropertyName, String passwordPropertyName,
        final String address, CredentialsProvider credentialsProvider) throws IOException {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(ClientPNames.MAX_REDIRECTS, MAX_REDIRECTS);

    DefaultHttpClient httpClient = new DefaultHttpClient(params);

    HttpProtocolParams.setUserAgent(httpClient.getParams(),
            System.getProperty("sip-communicator.application.name") + "/"
                    + System.getProperty("sip-communicator.version"));

    SSLContext sslCtx;
    try {
        sslCtx = HttpUtilActivator.getCertificateVerificationService()
                .getSSLContext(HttpUtilActivator.getCertificateVerificationService().getTrustManager(address));
    } catch (GeneralSecurityException e) {
        throw new IOException(e.getMessage());
    }

    // note to any reviewer concerned about ALLOW_ALL_HOSTNAME_VERIFIER:
    // the SSL context obtained from the certificate service takes care of
    // certificate validation
    try {
        Scheme sch = new Scheme("https", 443, new SSLSocketFactoryEx(sslCtx));
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (Throwable t) {
        logger.error("Error creating ssl socket factory", t);
    }

    // set proxy from default jre settings
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    if (credentialsProvider == null)
        credentialsProvider = new HTTPCredentialsProvider(usernamePropertyName, passwordPropertyName);
    httpClient.setCredentialsProvider(credentialsProvider);

    // enable retry connecting with default retry handler
    // when connecting has prompted for authentication
    // connection can be disconnected nefore user answers and
    // we need to retry connection, using the credentials provided
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    return httpClient;
}

From source file:org.eclipse.skalli.core.destination.DestinationComponent.java

private void setCredentials(DefaultHttpClient client, URL url) {
    if (configService == null) {
        return;//from   w w  w.  java 2  s.c om
    }

    DestinationsConfig config = configService.readConfiguration(DestinationsConfig.class);
    if (config == null) {
        return;
    }

    for (DestinationConfig destination : config.getDestinations()) {
        Pattern regex = Pattern.compile(destination.getPattern());
        Matcher matcher = regex.matcher(url.toExternalForm());
        if (matcher.matches()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("matched URL {0} with destination ''{1}''", url.toExternalForm(),
                        destination.getId()));
            }

            if (StringUtils.isNotBlank(destination.getUser())
                    && StringUtils.isNotBlank(destination.getPattern())) {
                String authenticationMethod = destination.getAuthenticationMethod();
                if ("basic".equalsIgnoreCase(authenticationMethod)) { //$NON-NLS-1$
                    CredentialsProvider credsProvider = new BasicCredentialsProvider();
                    credsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(destination.getUser(), destination.getPassword()));
                    client.setCredentialsProvider(credsProvider);
                } else if (StringUtils.isNotBlank(authenticationMethod)) {
                    LOG.warn(MessageFormat.format("Authentication method ''{1}'' is not supported",
                            authenticationMethod));
                }
            }
            break;
        }
    }
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

public static void setHttpClientProxy(DefaultHttpClient client, String url, String proxyUser,
        String proxyPassword) {//  www  .ja va  2  s.  com
    String proxyHost = null;
    int proxyPort = 8080;
    try {
        System.setProperty("java.net.useSystemProxies", "true");
        URI uri = new URI(url);
        List<Proxy> proxies = ProxySelector.getDefault().select(uri);
        if (proxies != null && client != null) {
            for (Proxy proxy : proxies) {
                if (proxy.address() != null && proxy.address() instanceof InetSocketAddress) {
                    InetSocketAddress address = (InetSocketAddress) proxy.address();
                    proxyHost = address.getHostName();
                    HttpHost host = new HttpHost(address.getHostName(), address.getPort());
                    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
                    break;
                }
            }
        }
    } catch (Exception ex) {
        Debug.log(ex);
    }

    if (proxyHost == null && System.getProperty("http.proxyHost") != null
            && !"".equals(System.getProperty("http.proxyHost"))) {
        proxyHost = System.getProperty("http.proxyHost");
        try {
            proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
        } catch (Exception ex) {
            //ignore
        }
        HttpHost host = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
    }

    if (proxyUser != null) {
        BasicCredentialsProvider bcp = new BasicCredentialsProvider();
        bcp.setCredentials(new AuthScope(proxyHost, proxyPort),
                new UsernamePasswordCredentials(proxyUser, proxyPassword));
        client.setCredentialsProvider(bcp);
    }
}

From source file:net.yacy.cora.federate.solr.instance.RemoteInstance.java

/**
 * @param solraccount eventual user name used to authenticate on the target Solr
 * @param solraccount eventual password used to authenticate on the target Solr
 * @param trustSelfSignedCertificates when true, https connections to an host providing a self-signed certificate are accepted
* @param maxBytesPerReponse//w  w w . ja  v a  2  s.  co m
*            maximum acceptable decompressed size in bytes for a response from
*            the remote Solr server. Negative value or Long.MAX_VALUE means no
*            limit.
 * @return a new apache HttpClient instance usable as a custom http client by SolrJ
 */
private static HttpClient buildCustomHttpClient(final int timeout, final MultiProtocolURL u,
        final String solraccount, final String solrpw, final String host,
        final boolean trustSelfSignedCertificates, final long maxBytesPerResponse) {

    /* Important note : use of deprecated Apache classes is required because SolrJ still use them internally (see HttpClientUtil). 
     * Upgrade only when Solr implementation will become compatible */

    org.apache.http.impl.client.DefaultHttpClient result = new org.apache.http.impl.client.DefaultHttpClient(
            CONNECTION_MANAGER) {
        @Override
        protected HttpContext createHttpContext() {
            HttpContext context = super.createHttpContext();
            AuthCache authCache = new org.apache.http.impl.client.BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            HttpHost targetHost = new HttpHost(u.getHost(), u.getPort(), u.getProtocol());
            authCache.put(targetHost, basicAuth);
            context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
            if (trustSelfSignedCertificates && SCHEME_REGISTRY != null) {
                context.setAttribute(ClientContext.SCHEME_REGISTRY, SCHEME_REGISTRY);
            }
            this.setHttpRequestRetryHandler(
                    new org.apache.http.impl.client.DefaultHttpRequestRetryHandler(0, false)); // no retries needed; we expect connections to fail; therefore we should not retry
            return context;
        }
    };
    org.apache.http.params.HttpParams params = result.getParams();
    /* Set the maximum time to establish a connection to the remote server */
    org.apache.http.params.HttpConnectionParams.setConnectionTimeout(params, timeout);
    /* Set the maximum time between data packets reception one a connection has been established */
    org.apache.http.params.HttpConnectionParams.setSoTimeout(params, timeout);
    /* Set the maximum time to get a connection from the shared connections pool */
    HttpClientParams.setConnectionManagerTimeout(params, timeout);
    result.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context) throws IOException {
            if (!request.containsHeader(HeaderFramework.ACCEPT_ENCODING))
                request.addHeader(HeaderFramework.ACCEPT_ENCODING, HeaderFramework.CONTENT_ENCODING_GZIP);
            if (!request.containsHeader(HTTP.CONN_DIRECTIVE))
                request.addHeader(HTTP.CONN_DIRECTIVE, "close"); // prevent CLOSE_WAIT
        }

    });
    result.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(final HttpResponse response, final HttpContext context) throws IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (HeaderElement codec : codecs) {
                        if (codec.getName().equalsIgnoreCase(HeaderFramework.CONTENT_ENCODING_GZIP)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    if (solraccount != null && !solraccount.isEmpty()) {
        org.apache.http.impl.client.BasicCredentialsProvider credsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(solraccount, solrpw));
        result.setCredentialsProvider(credsProvider);
    }

    if (maxBytesPerResponse >= 0 && maxBytesPerResponse < Long.MAX_VALUE) {
        /*
         * Add in last position the eventual interceptor limiting the response size, so
         * that this is the decompressed amount of bytes that is considered
         */
        result.addResponseInterceptor(new StrictSizeLimitResponseInterceptor(maxBytesPerResponse),
                result.getResponseInterceptorCount());
    }

    return result;
}

From source file:org.fcrepo.client.utils.HttpHelper.java

private static HttpClient buildClient(final String fedoraUsername, final String fedoraPassword,
        final String repositoryURL) {
    final PoolingClientConnectionManager connMann = new PoolingClientConnectionManager();
    connMann.setMaxTotal(MAX_VALUE);/*from   w  ww. j a va  2 s.c o  m*/
    connMann.setDefaultMaxPerRoute(MAX_VALUE);

    final DefaultHttpClient httpClient = new DefaultHttpClient(connMann);
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy());
    httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(0, false));

    // If the Fedora instance requires authentication, set it up here
    if (!isBlank(fedoraUsername) && !isBlank(fedoraPassword)) {
        LOGGER.debug("Adding BASIC credentials to client for repo requests.");

        final URI fedoraUri = URI.create(repositoryURL);
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(fedoraUri.getHost(), fedoraUri.getPort()),
                new UsernamePasswordCredentials(fedoraUsername, fedoraPassword));

        httpClient.setCredentialsProvider(credsProvider);
    }
    return httpClient;
}

From source file:org.fcrepo.indexer.IndexerGroup.java

@VisibleForTesting
protected DefaultHttpClient httpClient(final String repositoryURL) {
    // try to find existing client
    if (clients.size() > 0) {
        for (final Iterator<String> it = clients.keySet().iterator(); it.hasNext();) {
            final String base = it.next();
            if (repositoryURL.startsWith(base)) {
                return clients.get(base);
            }/*w  w w . ja  va 2s  .c o m*/
        }
    }

    if (defaultClient != null) {
        return defaultClient;
    }

    // if no existing client matched, create a new one
    final String baseURL;
    if (repositoryURL.indexOf(REST_PREFIX) > 0) {
        baseURL = repositoryURL.substring(0, repositoryURL.indexOf(REST_PREFIX) + REST_PREFIX.length());
    } else if (repositoryURL.indexOf("/", FCREPO_PREFIX.length()) > 0) {
        baseURL = repositoryURL.substring(0, repositoryURL.indexOf("/", FCREPO_PREFIX.length()) + 1);
    } else {
        baseURL = repositoryURL;
    }

    final PoolingClientConnectionManager connMann = new PoolingClientConnectionManager();
    connMann.setMaxTotal(MAX_VALUE);
    connMann.setDefaultMaxPerRoute(MAX_VALUE);

    final DefaultHttpClient httpClient = new DefaultHttpClient(connMann);
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy());
    httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(0, false));

    // If the Fedora instance requires authentication, set it up here
    if (!isBlank(fedoraUsername) && !isBlank(fedoraPassword)) {
        LOGGER.debug("Adding BASIC credentials to client for repo requests.");

        final URI fedoraUri = URI.create(baseURL);
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(fedoraUri.getHost(), fedoraUri.getPort()),
                new UsernamePasswordCredentials(fedoraUsername, fedoraPassword));

        httpClient.setCredentialsProvider(credsProvider);
    }
    clients.put(baseURL, httpClient);
    return httpClient;
}