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:io.github.thred.climatetray.ClimateTrayProxySettings.java

public CloseableHttpClient createHttpClient(String... additionalProxyExcludes) {
    if (proxyType == ProxyType.NONE) {
        return HttpClients.createDefault();
    }/*from   w  w w  .  j a  va  2s .  c o  m*/

    if (proxyType == ProxyType.SYSTEM_DEFAULT) {
        return HttpClients.createSystem();
    }

    HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
    HttpClientBuilder builder = HttpClientBuilder.create().setProxy(proxy);

    if (isProxyAuthorizationNeeded()) {
        Credentials credentials = new UsernamePasswordCredentials(getProxyUser(), getProxyPassword());
        AuthScope authScope = new AuthScope(getProxyHost(), getProxyPort());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        credsProvider.setCredentials(authScope, credentials);

        builder.setDefaultCredentialsProvider(credsProvider);
    }

    String excludes = proxyExcludes;

    if (Utils.isBlank(excludes)) {
        excludes = "";
    }

    for (String additionalProxyExclude : additionalProxyExcludes) {
        if (excludes.length() > 0) {
            excludes += ", ";
        }

        excludes += additionalProxyExclude;
    }

    if (!Utils.isBlank(excludes)) {
        WildcardPattern pattern = new WildcardPattern(excludes.split("\\s*,\\s*"));
        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy) {
            @Override
            public HttpRoute determineRoute(HttpHost host, HttpRequest request, HttpContext context)
                    throws HttpException {
                InetAddress address = host.getAddress();

                if (address == null) {
                    try {
                        address = InetAddress.getByName(host.getHostName());
                    } catch (UnknownHostException e) {
                        ClimateTray.LOG.info("Failed to determine address of host \"%s\"", host.getHostName());
                    }
                }

                if (address != null) {
                    String hostAddress = address.getHostAddress();

                    if (pattern.matches(hostAddress)) {
                        return new HttpRoute(host);
                    }
                }

                String hostName = host.getHostName();

                if (pattern.matches(hostName)) {
                    return new HttpRoute(host);
                }

                return super.determineRoute(host, request, context);
            }
        };

        builder.setRoutePlanner(routePlanner);
    }

    return builder.build();
}

From source file:org.datagator.api.client.backend.DataGatorService.java

public DataGatorService(UsernamePasswordCredentials auth) {
    this();//from w w  w  .j  ava  2  s  . co m
    log.info(String.format("Initializing service with authorization: %s", auth.getUserName()));
    // attach credentials to context
    HttpHost host = new HttpHost(environ.DATAGATOR_API_HOST, environ.DATAGATOR_API_PORT,
            environ.DATAGATOR_API_SCHEME);
    AuthScope scope = new AuthScope(host.getHostName(), host.getPort());
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(scope, auth);
    this.context.setCredentialsProvider(provider);
    // enable preemptive (pro-active) basic authentication
    AuthCache cache = new BasicAuthCache();
    cache.put(host, new BasicScheme());
    this.context.setAuthCache(cache);
}

From source file:net.siegmar.japtproxy.fetcher.HttpClientConfigurer.java

protected void configureProxy(final HttpClientBuilder httpClientBuilder, final String proxy)
        throws InitializationException {
    final URL proxyUrl;
    try {/*from  w w  w  .java 2 s  .  co m*/
        proxyUrl = new URL(proxy);
    } catch (final MalformedURLException e) {
        throw new InitializationException("Invalid proxy url", e);
    }

    final String proxyHost = proxyUrl.getHost();
    final int proxyPort = proxyUrl.getPort() != -1 ? proxyUrl.getPort() : proxyUrl.getDefaultPort();

    LOG.info("Set proxy server to '{}:{}'", proxyHost, proxyPort);
    httpClientBuilder.setRoutePlanner(new DefaultProxyRoutePlanner(new HttpHost(proxyHost, proxyPort)));

    final String userInfo = proxyUrl.getUserInfo();
    if (userInfo != null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), buildCredentials(userInfo));

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }
}

From source file:com.moviejukebox.tools.YamjHttpClientBuilder.java

@SuppressWarnings("resource")
private static YamjHttpClient buildHttpClient() {
    LOG.trace("Create new YAMJ http client");

    // create proxy
    HttpHost proxy = null;//ww  w.  j  a v  a 2s  .  c om
    CredentialsProvider credentialsProvider = null;

    if (StringUtils.isNotBlank(PROXY_HOST) && PROXY_PORT > 0) {
        proxy = new HttpHost(PROXY_HOST, PROXY_PORT);

        if (StringUtils.isNotBlank(PROXY_USERNAME) && StringUtils.isNotBlank(PROXY_PASSWORD)) {
            credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT),
                    new UsernamePasswordCredentials(PROXY_USERNAME, PROXY_PASSWORD));
        }
    }

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(TIMEOUT_SOCKET).build());
    connManager.setMaxTotal(20);
    connManager.setDefaultMaxPerRoute(2);

    CacheConfig cacheConfig = CacheConfig.custom().setMaxCacheEntries(1000).setMaxObjectSize(8192).build();

    HttpClientBuilder builder = CachingHttpClientBuilder.create().setCacheConfig(cacheConfig)
            .setConnectionManager(connManager).setProxy(proxy)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_READ)
                    .setConnectTimeout(TIMEOUT_CONNECT).setSocketTimeout(TIMEOUT_SOCKET)
                    .setCookieSpec(CookieSpecs.IGNORE_COOKIES).setProxy(proxy).build());

    // show status
    showStatus();

    // build the client
    YamjHttpClient wrapper = new YamjHttpClient(builder.build(), connManager);
    wrapper.setUserAgentSelector(new WebBrowserUserAgentSelector());
    wrapper.addGroupLimit(".*", 1); // default limit, can be overwritten

    // First we have to read/create the rules
    String maxDownloadSlots = PropertiesUtil.getProperty("mjb.MaxDownloadSlots");
    if (StringUtils.isNotBlank(maxDownloadSlots)) {
        LOG.debug("Using download limits: {}", maxDownloadSlots);

        Pattern pattern = Pattern.compile(",?\\s*([^=]+)=(\\d+)");
        Matcher matcher = pattern.matcher(maxDownloadSlots);
        while (matcher.find()) {
            String group = matcher.group(1);
            try {
                final Integer maxResults = Integer.valueOf(matcher.group(2));
                wrapper.addGroupLimit(group, maxResults);
                LOG.trace("Added download slot '{}' with max results {}", group, maxResults);
            } catch (NumberFormatException error) {
                LOG.debug("Rule '{}' is no valid regexp, ignored", group);
            }
        }
    }

    return wrapper;
}

From source file:org.yamj.core.tools.web.PoolingHttpClientBuilder.java

@SuppressWarnings("resource")
public PoolingHttpClient build() {
    // create proxy
    HttpHost proxy = null;//from ww w  .  j  a v a2 s  .  c  om
    CredentialsProvider credentialsProvider = null;

    if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) {
        proxy = new HttpHost(proxyHost, proxyPort);

        if (StringUtils.isNotBlank(proxyUsername) && StringUtils.isNotBlank(proxyPassword)) {
            if (systemProperties) {
                credentialsProvider = new SystemDefaultCredentialsProvider();
            } else {
                credentialsProvider = new BasicCredentialsProvider();
            }
            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new UsernamePasswordCredentials(proxyUsername, proxyPassword));
        }
    }

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
    connManager.setMaxTotal(connectionsMaxTotal);
    connManager.setDefaultMaxPerRoute(connectionsMaxPerRoute);

    HttpClientBuilder builder = HttpClientBuilder.create().setConnectionManager(connManager).setProxy(proxy)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectionTimeout)
                    .setSocketTimeout(socketTimeout).setProxy(proxy).build());

    // use system properties
    if (systemProperties) {
        builder.useSystemProperties();
    }

    // build the client
    PoolingHttpClient wrapper = new PoolingHttpClient(builder.build(), connManager);
    wrapper.addGroupLimit(".*", 1); // default limit, can be overwritten

    if (StringUtils.isNotBlank(maxDownloadSlots)) {
        LOG.debug("Using download limits: {}", maxDownloadSlots);

        Pattern pattern = Pattern.compile(",?\\s*([^=]+)=(\\d+)");
        Matcher matcher = pattern.matcher(maxDownloadSlots);
        while (matcher.find()) {
            String group = matcher.group(1);
            try {
                final Integer maxResults = Integer.valueOf(matcher.group(2));
                wrapper.addGroupLimit(group, maxResults);
                LOG.trace("Added download slot '{}' with max results {}", group, maxResults);
            } catch (NumberFormatException error) {
                LOG.debug("Rule '{}' is no valid regexp, ignored", group);
            }
        }
    }

    return wrapper;
}

From source file:org.openehealth.ipf.commons.ihe.fhir.SslAwareApacheRestfulClientFactory.java

protected synchronized HttpClient getNativeHttpClient() {
    if (httpClient == null) {

        // @formatter:off
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(getConnectTimeout())
                .setSocketTimeout(getSocketTimeout()).setConnectionRequestTimeout(getConnectionRequestTimeout())
                .setProxy(proxy).setStaleConnectionCheckEnabled(true).build();

        HttpClientBuilder builder = HttpClients.custom().useSystemProperties()
                .setDefaultRequestConfig(defaultRequestConfig).setMaxConnTotal(getPoolMaxTotal())
                .setMaxConnPerRoute(getPoolMaxPerRoute()).setConnectionTimeToLive(5, TimeUnit.SECONDS)
                .disableCookieManagement();

        if (securityInformation != null) {
            securityInformation.configureHttpClientBuilder(builder);
        }//from  w ww . j  a v a2  s  .co m

        // Need to authenticate against proxy
        if (proxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }

        httpClient = builder.build();
    }

    return httpClient;
}

From source file:com.intel.cosbench.api.httpauth.HttpAuth.java

@Override
public AuthContext login() {
    super.login();

    //        HttpHost host = new HttpHost();
    //        HttpHost targetHost = new HttpHost(host, port, protocol);

    URI uri;/*from  w  w w. j a  v  a2 s.c  o  m*/

    try {
        uri = new URI(auth_url);
    } catch (URISyntaxException use) {
        throw new AuthException(use);
    }

    HttpGet method = new HttpGet(auth_url);
    method.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);

    client.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(this.username, this.password));

    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(AuthPNames.TARGET_AUTH_PREF,
            Arrays.asList(new String[] { AuthPolicy.BASIC, AuthPolicy.DIGEST }));

    HttpResponse response = null;

    try {
        dumpClientSettings();
        response = client.execute(method, localContext);

        dumpClientSettings();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return createContext();
        }
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthException(response.getStatusLine().getReasonPhrase());
        }
    } catch (SocketTimeoutException ste) {
        throw new AuthTimeoutException(ste);
    } catch (ConnectTimeoutException cte) {
        throw new AuthTimeoutException(cte);
    } catch (InterruptedIOException ie) {
        throw new AuthInterruptedException(ie);
    } catch (Exception e) {
        throw new AuthException(e);
    } finally {
        if (response != null)
            try {
                dumpResponse(response);
                EntityUtils.consume(response.getEntity());
            } catch (Exception ignore) {
                ignore.printStackTrace();
            }

        if (method != null)
            method.abort();
    }

    return createContext();
}

From source file:com.marklogic.client.functionaltest.ConnectedRESTQA.java

public static String getBootStrapHostFromML() {
    InputStream jstream = null;//from ww w .  jav  a2 s.  c o m
    try {
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpGet getrequest = new HttpGet("http://localhost:8002/manage/v2/properties?format=json");
        HttpResponse resp = client.execute(getrequest);
        jstream = resp.getEntity().getContent();
        JsonNode jnode = new ObjectMapper().readTree(jstream);
        String propName = "bootstrap-host";
        if (!jnode.isNull()) {

            if (jnode.has(propName)) {
                System.out.println("Bootstrap Host: "
                        + jnode.withArray(propName).get(0).get("bootstrap-host-name").asText());
                return jnode.withArray(propName).get(0).get("bootstrap-host-name").asText();
            } else {
                System.out.println("Missing " + propName
                        + " field from properties end point so sending java conanical host name\n"
                        + jnode.toString());
                return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
            }
        } else {
            System.out.println("Rest endpoint returns empty stream");
            return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
        }

    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();

        return "localhost";
    } finally {
        jstream = null;
    }
}

From source file:org.fcrepo.kernel.impl.identifiers.HttpPidMinter.java

/**
 * Setup authentication in httpclient./*  w w  w . ja  va 2  s  . c  om*/
**/
protected HttpClient buildClient() {
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties()
            .setConnectionManager(new PoolingHttpClientConnectionManager());
    if (!isBlank(username) && !isBlank(password)) {
        final URI uri = URI.create(url);
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(username, password));
        builder = builder.setDefaultCredentialsProvider(credsProvider);
    }
    return builder.build();
}