Example usage for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

List of usage examples for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

Introduction

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

Prototype

public BasicCredentialsProvider() 

Source Link

Document

Default constructor.

Usage

From source file:com.microsoft.alm.plugin.context.ServerContext.java

protected static ClientConfig getClientConfig(final Type type, final AuthenticationInfo authenticationInfo,
        final boolean includeProxySettings) {
    final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo);

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    final ConnectorProvider connectorProvider = new ApacheConnectorProvider();

    final ClientConfig clientConfig = new ClientConfig().connectorProvider(connectorProvider);
    clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);

    clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
    clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    //Define a local HTTP proxy
    if (includeProxySettings) {
        final String proxyHost;
        if (System.getProperty("proxyHost") != null) {
            proxyHost = System.getProperty("proxyHost");
        } else {//from   w w w  . jav a 2  s  . co m
            proxyHost = "127.0.0.1";
        }

        final String proxyPort;
        if (System.getProperty("proxyPort") != null) {
            proxyPort = System.getProperty("proxyPort");
        } else {
            proxyPort = "8888";
        }

        final String proxyUrl = String.format("http://%s:%s", proxyHost, proxyPort);

        clientConfig.property(ClientProperties.PROXY_URI, proxyUrl);
    }

    // if this is a onPrem server and the uri starts with https, we need to setup ssl
    if (isSSLEnabledOnPrem(type, authenticationInfo.getServerUri())) {
        clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator());
    }

    return clientConfig;
}

From source file:com.seyren.core.service.checker.GraphiteTargetChecker.java

/**
 * Set auth header for graphite if username and password are provided
 */// w w w.  j a va 2s  . c om
private void setAuthHeadersIfNecessary() {
    if (!StringUtils.isEmpty(graphiteUsername) && !StringUtils.isEmpty(graphitePassword)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(graphiteHost, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(graphiteUsername, graphitePassword));
        if (client instanceof AbstractHttpClient) {
            ((AbstractHttpClient) client).setCredentialsProvider(credsProvider);
        }
    }
}

From source file:org.sonatype.nexus.examples.url.UrlRealmTest.java

@Test(expected = UnknownAccountException.class)
public void testAuthcWrongCreds() throws Exception {
    // build client
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, "cake"));
    httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    when(hc4Provider.createHttpClient(Mockito.any(RemoteStorageContext.class))).thenReturn(httpClient);

    urlRealm.getAuthenticationInfo(new UsernamePasswordToken(username, "cake"));
}

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./*from   ww w . jav a  2s  . 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:org.jboss.teiid.quickstart.PortfolioClient.java

public void resteasyHttpBackendClient() {

    System.out.println("\nResteasy Client API with HTTP client as engine");

    HttpHost targetHost = new HttpHost("localhost", 8080, "http");

    // 1. Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // 2. Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // 3. Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    // 4. Create client executor and proxy
    HttpClientBuilder builder = HttpClientBuilder.create();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope scope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD);
    credsProvider.setCredentials(scope, credentials);
    builder.setDefaultCredentialsProvider(credsProvider);
    HttpClient httpClient = builder.build();

    // 5. Create ResteasyClient with http client as engine
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, localContext);
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();

    // 6. Execute Rest call via ResteasyClient
    String authString = getBasicAuthentication();
    for (String api : apis) {
        ResteasyWebTarget target = client.target(api);
        Response response = target.request().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML)
                .header(HttpHeaders.AUTHORIZATION, authString).get();
        if (response.getStatus() == 200) {
            String value = response.readEntity(String.class);
            System.out.println(value);
            response.close();/*from w w w. j  a v a 2  s. c  o m*/
        } else {
            handleError(response);
        }
    }
}

From source file:io.github.cidisk.indexcrawler.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).setRedirectsEnabled(false)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();/*from   w ww.  j av  a  2  s. c  o  m*/

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    if (config.isIncludeHttpsPages()) {
        try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
            // By always trusting the ssl certificate
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, String authType) {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            connRegistryBuilder.register("https", sslsf);
        } catch (Exception e) {
            logger.warn("Exception thrown while trying to register https");
            logger.debug("Stacktrace", e);
        }
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent(config.getUserAgentString());

    if (config.getProxyHost() != null) {
        if (config.getProxyUsername() != null) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        clientBuilder.setProxy(proxy);
        logger.debug("Working through Proxy: {}", proxy.getHostName());
    }

    httpClient = clientBuilder.build();
    if (config.getAuthInfos() != null && !config.getAuthInfos().isEmpty()) {
        doAuthetication(config.getAuthInfos());
    }

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();
}

From source file:com.crawler.app.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).setRedirectsEnabled(false)
            //.setRelativeRedirectsAllowed(true)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();/*from   w  ww.  jav  a  2s.  c  o m*/

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    if (config.isIncludeHttpsPages()) {
        try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
            // By always trusting the ssl certificate
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                //@Override
                public boolean isTrusted(final X509Certificate[] chain, String authType) {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            connRegistryBuilder.register("https", sslsf);
        } catch (Exception e) {
            logger.warn("Exception thrown while trying to register https");
            logger.debug("Stacktrace", e);
        }
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent(config.getUserAgentString());

    if (config.getProxyHost() != null) {
        if (config.getProxyUsername() != null) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        clientBuilder.setProxy(proxy);
        logger.debug("Working through Proxy: {}", proxy.getHostName());
    }

    httpClient = clientBuilder.build();
    if (config.getAuthInfos() != null && !config.getAuthInfos().isEmpty()) {
        doAuthetication(config.getAuthInfos());
    }

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();
}

From source file:de.comlineag.snc.webcrawler.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).setRedirectsEnabled(false)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();//from w w  w.j  a v  a 2s  .  com

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    if (config.isIncludeHttpsPages()) {
        try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
            // By always trusting the ssl certificate
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, String authType) {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            connRegistryBuilder.register("https", sslsf);
        } catch (Exception e) {
            logger.debug("Exception thrown while trying to register https:", e);
        }
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent(config.getUserAgentString());
    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        clientBuilder.setProxy(proxy);
    }
    clientBuilder.addInterceptorLast(new HttpResponseInterceptor() {
        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    httpClient = clientBuilder.build();

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();
}

From source file:com.fourspaces.couchdb.Session.java

/**
 * Constructor for obtaining a Session with an HTTP-AUTH username/password
 * and (optionally) a secure connection This isn't supported by CouchDB -
 * you need a proxy in front to use this
 *
 * @param host - hostname/*  w w w.  jav  a 2 s  .c o  m*/
 * @param port - port to use
 * @param user - username
 * @param pass - password
 * @param usesAuth
 * @param secure - use an SSL connection?
 */
public Session(String host, int port, String user, String pass, boolean usesAuth, boolean secure) {
    this.host = host;
    this.port = port;
    this.user = user;
    this.pass = pass;
    this.usesAuth = usesAuth;
    this.secure = secure;

    PlainConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
    LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainsf).register("https", sslsf).build();
    this.connManager = new PoolingHttpClientConnectionManager(r);

    this.requestConfig = RequestConfig.custom().setConnectTimeout(15 * 1000).setSocketTimeout((30 * 1000))
            .setAuthenticationEnabled(usesAuth).build();

    this.httpContext = HttpClientContext.create();
    if (user != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
        this.httpContext.setCredentialsProvider(credsProvider);
    }

    this.httpClient = createHttpClient();
}