Example usage for org.apache.http.auth AuthScope AuthScope

List of usage examples for org.apache.http.auth AuthScope AuthScope

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope AuthScope.

Prototype

public AuthScope(final String host, final int port) 

Source Link

Document

Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.

Usage

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();//w w w  . ja va  2  s . co m
        } else {
            handleError(response);
        }
    }
}

From source file:org.sonar.ide.intellij.wsclient.WSClientFactory.java

/**
 * Workaround for http://jira.codehaus.org/browse/SONAR-1586
 *///from  ww w .ja v  a 2  s.co  m
private void configureProxy(DefaultHttpClient httpClient, Host server) {
    try {
        Proxy proxyData = getIntelliJProxyFor(server);
        if (proxyData != null) {
            InetSocketAddress address = (InetSocketAddress) proxyData.address();
            HttpConfigurable proxySettings = HttpConfigurable.getInstance();
            LOG.debug("Proxy for [" + address.getHostName() + "] - [" + address + "]");
            HttpHost proxy = new HttpHost(address.getHostName(), address.getPort());
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            if (proxySettings.PROXY_AUTHENTICATION) {
                httpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(address.getHostName(), address.getPort()),
                        new UsernamePasswordCredentials(proxySettings.PROXY_LOGIN,
                                proxySettings.getPlainProxyPassword()));
            }
        } else {
            LOG.debug("No proxy for [" + server.getHost() + "]");
        }
    } catch (Exception e) {
        LOG.error("Unable to configure proxy for sonar-ws-client", e);
    }
}

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 w w .j a  va2  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  w  w . j a v a  2  s. c  om

    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();
}