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

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

Introduction

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

Prototype

String ANY_HOST

To view the source code for org.apache.http.auth AuthScope ANY_HOST.

Click Source Link

Document

The null value represents any host.

Usage

From source file:net.sf.jasperreports.data.http.HttpDataService.java

protected void setAuthentication(Map<String, Object> parameters, HttpClientBuilder clientBuilder) {
    String username = getUsername(parameters);
    if (username != null) {
        String password = getPassword(parameters);

        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        //FIXME proxy authentication?
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }//from   w w w .j  av  a2s . co  m
}

From source file:com.hp.saas.agm.rest.client.AliRestClient.java

@Override
public void setHttpProxyCredentials(String username, String password) {

    Credentials cred = new UsernamePasswordCredentials(username, password);
    AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
    httpClient.getCredentialsProvider().setCredentials(scope, cred);
}

From source file:org.artifactory.util.HttpClientConfigurator.java

/**
 * Configures preemptive authentication on this client. Ignores blank username input.
 *//*from   www.jav  a 2 s  .c o  m*/
public HttpClientConfigurator authentication(String username, String password, boolean allowAnyHost) {
    if (StringUtils.isNotBlank(username)) {
        if (StringUtils.isBlank(host)) {
            throw new IllegalStateException("Cannot configure authentication when host is not set.");
        }

        AuthScope authscope = allowAnyHost
                ? new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM)
                : new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
        credsProvider.setCredentials(authscope, new UsernamePasswordCredentials(username, password));

        builder.addInterceptorFirst(new PreemptiveAuthInterceptor());
    }
    return this;
}

From source file:org.opcfoundation.ua.transport.https.HttpsClient.java

/**
 * Initialize HttpsClient. //from  ww w.j ava 2  s.c  o  m
 * 
 * @param connectUrl
 * @param tcs
 */
public void initialize(String connectUrl, TransportChannelSettings tcs, EncoderContext ctx)
        throws ServiceResultException {

    this.connectUrl = connectUrl;
    this.securityPolicyUri = tcs.getDescription().getSecurityPolicyUri();
    this.transportChannelSettings = tcs;
    HttpsSettings httpsSettings = tcs.getHttpsSettings();
    HttpsSecurityPolicy[] policies = httpsSettings.getHttpsSecurityPolicies();
    if (policies != null && policies.length > 0)
        securityPolicy = policies[policies.length - 1];
    else
        securityPolicy = HttpsSecurityPolicy.TLS_1_1;
    // securityPolicy = SecurityPolicy.getSecurityPolicy( this.securityPolicyUri );
    if (securityPolicy != HttpsSecurityPolicy.TLS_1_0 && securityPolicy != HttpsSecurityPolicy.TLS_1_1
            && securityPolicy != HttpsSecurityPolicy.TLS_1_2)
        throw new ServiceResultException(StatusCodes.Bad_SecurityChecksFailed,
                "Https Client doesn't support securityPolicy " + securityPolicy);
    if (logger.isDebugEnabled()) {
        logger.debug("initialize: url={}; settings={}", tcs.getDescription().getEndpointUrl(),
                ObjectUtils.printFields(tcs));
    }

    // Setup Encoder
    EndpointConfiguration endpointConfiguration = tcs.getConfiguration();
    encoderCtx = ctx;
    encoderCtx.setMaxArrayLength(
            endpointConfiguration.getMaxArrayLength() != null ? endpointConfiguration.getMaxArrayLength() : 0);
    encoderCtx.setMaxStringLength(
            endpointConfiguration.getMaxStringLength() != null ? endpointConfiguration.getMaxStringLength()
                    : 0);
    encoderCtx.setMaxByteStringLength(endpointConfiguration.getMaxByteStringLength() != null
            ? endpointConfiguration.getMaxByteStringLength()
            : 0);
    encoderCtx.setMaxMessageSize(
            endpointConfiguration.getMaxMessageSize() != null ? endpointConfiguration.getMaxMessageSize() : 0);

    timer = TimerUtil.getTimer();
    try {
        SchemeRegistry sr = new SchemeRegistry();
        if (protocol.equals(UriUtil.SCHEME_HTTPS)) {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(httpsSettings.getKeyManagers(), httpsSettings.getTrustManagers(), null);
            X509HostnameVerifier hostnameVerifier = httpsSettings.getHostnameVerifier() != null
                    ? httpsSettings.getHostnameVerifier()
                    : SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, hostnameVerifier) {
                protected void prepareSocket(javax.net.ssl.SSLSocket socket) throws IOException {
                    socket.setEnabledCipherSuites(cipherSuites);
                };
            };

            SSLEngine sslEngine = sslcontext.createSSLEngine();
            String[] enabledCipherSuites = sslEngine.getEnabledCipherSuites();
            cipherSuites = CryptoUtil.filterCipherSuiteList(enabledCipherSuites,
                    securityPolicy.getCipherSuites());

            logger.info("Enabled protocols in SSL Engine are {}",
                    Arrays.toString(sslEngine.getEnabledProtocols()));
            logger.info("Enabled CipherSuites in SSL Engine are {}", Arrays.toString(enabledCipherSuites));
            logger.info("Client CipherSuite selection for {} is {}", securityPolicy.getPolicyUri(),
                    Arrays.toString(cipherSuites));

            Scheme https = new Scheme("https", 443, sf);
            sr.register(https);
        }

        if (protocol.equals(UriUtil.SCHEME_HTTP)) {
            Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
            sr.register(http);
        }

        if (ccm == null) {
            PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(sr);
            ccm = pccm;
            pccm.setMaxTotal(maxConnections);
            pccm.setDefaultMaxPerRoute(maxConnections);
        }
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                transportChannelSettings.getConfiguration().getOperationTimeout());
        HttpConnectionParams.setSoTimeout(httpParams, 0);
        httpclient = new DefaultHttpClient(ccm, httpParams);

        // Set username and password authentication
        if (httpsSettings.getUsername() != null && httpsSettings.getPassword() != null) {
            BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(httpsSettings.getUsername(), httpsSettings.getPassword()));
            httpclient.setCredentialsProvider(credsProvider);
        }

    } catch (NoSuchAlgorithmException e) {
        new ServiceResultException(e);
    } catch (KeyManagementException e) {
        new ServiceResultException(e);
    }

}

From source file:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java

public static BasicHttpContext setCredentials(DefaultHttpClient client, HttpHost httpHost, String username,
        String password, boolean preAuth) {
    // set Username and Password
    if (!StringUtil.isEmpty(username, true)) {
        if (password == null)
            password = "";
        CredentialsProvider cp = client.getCredentialsProvider();
        cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        BasicHttpContext httpContext = new BasicHttpContext();
        if (preAuth) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(httpHost, new BasicScheme());
            httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }//w  ww . j  a va 2s .c o  m
        return httpContext;
    }
    return null;
}

From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java

public static BasicHttpContext setCredentials(HttpClientBuilder builder, HttpHost httpHost, String username,
        String password, boolean preAuth) {
    // set Username and Password
    if (!StringUtil.isEmpty(username, true)) {
        if (password == null)
            password = "";
        CredentialsProvider cp = new BasicCredentialsProvider();
        builder.setDefaultCredentialsProvider(cp);

        cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        BasicHttpContext httpContext = new BasicHttpContext();
        if (preAuth) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(httpHost, new BasicScheme());
            httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }/*from w  ww.j  a v a 2 s  . co m*/
        return httpContext;
    }
    return null;
}

From source file:com.untangle.app.web_filter.WebFilterDecisionEngine.java

/**
 * Get dia key//from   w  ww .  j  a  v a 2 s .  c o  m
 * 
 * @return The dia key
 */
public String getDiaKey() {
    if (WebFilterDecisionEngine.diaKey != null)
        return WebFilterDecisionEngine.diaKey;

    /* otherwise synchronize and fetch a new one */

    if (logger.isDebugEnabled()) {
        logger.debug("start-getDiaKey");
    }
    synchronized (this) {
        long t = System.currentTimeMillis();

        if ((null == diaKey) || ((t - DIA_TIMEOUT) > lastDiaUpdate)) {
            if ((t - DIA_TRY_LIMIT) < lastDiaTry) {
                logger.warn("DIA_TRY_LIMIT has not expired, not getting key");
                return diaKey;
            }

            lastDiaTry = t;

            int timeout = 60 * 1000;
            RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setSocketTimeout(timeout).setConnectionRequestTimeout(timeout).build();
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
                    .build();
            CloseableHttpResponse response = null;
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials("untangle", "wu+glev6"));
            HttpClientContext context = HttpClientContext.create();
            context.setCredentialsProvider(credsProvider);

            try {
                String url = "https://dl.zvelo.com/oem/dia.key";
                logger.debug("Fetch URL: \"" + url + "\"");
                HttpGet get = new HttpGet(url);
                response = httpClient.execute(get, context);
                logger.debug("Fetched URL: \"" + url + "\"");

                if (response != null && response.getStatusLine().getStatusCode() == 200) {
                    String s = EntityUtils.toString(response.getEntity(), "UTF-8");
                    s = s.trim();
                    logger.debug("DIA key response: " + s);

                    if (s.toUpperCase().startsWith("ERROR")) {
                        logger.warn("Could not get a dia key: " + s.substring(0, 10));
                    } else {
                        diaKey = s;
                        lastDiaUpdate = System.currentTimeMillis();
                    }
                } else {
                    logger.warn("Failed to get dia key: " + response);
                }
            } catch (Exception exn) {
                logger.warn("Could not get dia key", exn);
            } finally {
                try {
                    if (response != null)
                        response.close();
                } catch (Exception e) {
                    logger.warn("close", e);
                }
                try {
                    httpClient.close();
                } catch (Exception e) {
                    logger.warn("close", e);
                }
            }

        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("end-getDiaKey");
    }

    return diaKey;
}

From source file:com.bordercloud.sparql.Endpoint.java

private HashMap<String, HashMap> sendQueryPOSTwithAuth(String urlStr, String parameter, String query,
        String login, String password) throws EndpointException {

    int statusCode = 0;
    try {//w  ww  .j a  v a 2 s.co  m
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(login, password));
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();
        try {
            HttpPost httpPost = new HttpPost(urlStr);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair(parameter, query));
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            CloseableHttpResponse response2 = httpclient.execute(httpPost);

            try {
                //System.out.println(response2.getStatusLine());
                statusCode = response2.getStatusLine().getStatusCode();
                if (statusCode < 200 || statusCode >= 300) {
                    throw new EndpointException(this, response2.getStatusLine().toString());
                }
                HttpEntity entity2 = response2.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                ////System.out.println(EntityUtils.toString(entity2));

                _response = EntityUtils.toString(entity2);
                //EntityUtils.consume(entity2);
            } finally {
                response2.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }

    return getResult();
}

From source file:org.apache.manifoldcf.agents.output.solr.HttpPoster.java

/** Initialize the standard http poster.
*///  w  ww  .j a v  a2s.c  o m
public HttpPoster(String protocol, String server, int port, String webapp, String core, int connectionTimeout,
        int socketTimeout, String updatePath, String removePath, String statusPath, String realm, String userID,
        String password, String allowAttributeName, String denyAttributeName, String idAttributeName,
        String modifiedDateAttributeName, String createdDateAttributeName, String indexedDateAttributeName,
        String fileNameAttributeName, String mimeTypeAttributeName, String contentAttributeName,
        IKeystoreManager keystoreManager, Long maxDocumentLength, String commitWithin,
        boolean useExtractUpdateHandler) throws ManifoldCFException {
    // These are the paths to the handlers in Solr that deal with the actions we need to do
    this.postUpdateAction = updatePath;
    this.postRemoveAction = removePath;
    this.postStatusAction = statusPath;

    this.commitWithin = commitWithin;

    this.allowAttributeName = allowAttributeName;
    this.denyAttributeName = denyAttributeName;
    this.idAttributeName = idAttributeName;
    this.modifiedDateAttributeName = modifiedDateAttributeName;
    this.createdDateAttributeName = createdDateAttributeName;
    this.indexedDateAttributeName = indexedDateAttributeName;
    this.fileNameAttributeName = fileNameAttributeName;
    this.mimeTypeAttributeName = mimeTypeAttributeName;
    this.contentAttributeName = contentAttributeName;
    this.useExtractUpdateHandler = useExtractUpdateHandler;

    this.maxDocumentLength = maxDocumentLength;

    String location = "";
    if (webapp != null)
        location = "/" + webapp;
    if (core != null) {
        if (webapp == null)
            throw new ManifoldCFException("Webapp must be specified if core is specified.");
        location += "/" + core;
    }

    // Initialize standard solr-j.
    // First, we need an HttpClient where basic auth is properly set up.
    connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(1);

    SSLConnectionSocketFactory myFactory;
    if (keystoreManager != null) {
        myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {
        // Use the "trust everything" one
        myFactory = new SSLConnectionSocketFactory(KeystoreManagerFactory.getTrustingSecureSocketFactory(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
            .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setRedirectStrategy(new DefaultRedirectStrategy()).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout)).setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build());

    if (userID != null && userID.length() > 0 && password != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        Credentials credentials = new UsernamePasswordCredentials(userID, password);
        if (realm != null)
            credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, realm),
                    credentials);
        else
            credentialsProvider.setCredentials(AuthScope.ANY, credentials);

        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    HttpClient localClient = clientBuilder.build();

    String httpSolrServerUrl = protocol + "://" + server + ":" + port + location;
    solrServer = new ModifiedHttpSolrServer(httpSolrServerUrl, localClient, new XMLResponseParser());
}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

public static DefaultHttpClient getLoginHttpClient(String userName, String password) {
    try {//from w  w  w  .  j a va 2 s  .  co m

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, 300000);
        HttpConnectionParams.setSocketBufferSize(params, 10485760);
        HttpConnectionParams.setSoTimeout(params, 300000);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(userName, password));
        return httpClient;
    } catch (Exception e) {
        e.printStackTrace();
        return new DefaultHttpClient();
    }
}