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

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

Introduction

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

Prototype

AuthScope ANY

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

Click Source Link

Document

Default scope matching any host, port, realm and authentication scheme.

Usage

From source file:com.asakusafw.yaess.jobqueue.client.HttpJobClient.java

/**
 * Creates a new instance.//from  w  ww  .  jav a2s . co m
 * @param baseUri the target base URL
 * @param user user name
 * @param password password
 * @throws IllegalArgumentException if some parameters were {@code null}
 */
public HttpJobClient(String baseUri, String user, String password) {
    if (baseUri == null) {
        throw new IllegalArgumentException("baseUri must not be null"); //$NON-NLS-1$
    }
    if (user == null) {
        throw new IllegalArgumentException("user must not be null"); //$NON-NLS-1$
    }
    if (password == null) {
        throw new IllegalArgumentException("password must not be null"); //$NON-NLS-1$
    }
    this.baseUri = normalize(baseUri);
    this.user = user;
    DefaultHttpClient client = createClient();
    client.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(user, password));
    this.http = client;
}

From source file:org.apache.cloudstack.cloudian.client.CloudianClient.java

private void checkAuthFailure(final HttpResponse response) {
    if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        final Credentials credentials = httpContext.getCredentialsProvider().getCredentials(AuthScope.ANY);
        LOG.error(// ww w.j  a  v  a  2 s  .  c  om
                "Cloudian admin API authentication failed, please check Cloudian configuration. Admin auth principal="
                        + credentials.getUserPrincipal() + ", password=" + credentials.getPassword()
                        + ", API url=" + adminApiUrl);
        throw new ServerApiException(ApiErrorCode.UNAUTHORIZED,
                "Cloudian backend API call unauthorized, please ask your administrator to fix integration issues.");
    }
}

From source file:org.apache.metron.elasticsearch.client.ElasticsearchClientFactory.java

private static CredentialsProvider getCredentialsProvider(ElasticsearchClientConfig esClientConfig) {
    Optional<Entry<String, String>> credentials = esClientConfig.getCredentials();
    if (credentials.isPresent()) {
        LOG.info("Found auth credentials - setting up user/pass authenticated client connection for ES.");
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials upcredentials = new UsernamePasswordCredentials(credentials.get().getKey(),
                credentials.get().getValue());
        credentialsProvider.setCredentials(AuthScope.ANY, upcredentials);
        return credentialsProvider;
    } else {//from  w  w w  .  j  a v a 2s .co  m
        LOG.info(
                "Elasticsearch client credentials not provided. Defaulting to non-authenticated client connection.");
        return null;
    }
}

From source file:org.apache.manifoldcf.authorities.authorities.jira.JiraSession.java

/**
 * Constructor. Create a session./*from   w  w  w. ja  va  2 s . c o  m*/
 */
public JiraSession(String clientId, String clientSecret, String protocol, String host, int port, String path,
        String proxyHost, int proxyPort, String proxyDomain, String proxyUsername, String proxyPassword)
        throws ManifoldCFException {
    this.host = new HttpHost(host, port, protocol);
    this.path = path;
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    int socketTimeout = 900000;
    int connectionTimeout = 60000;

    javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory();
    SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
            new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // If authentication needed, set that
    if (clientId != null) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(clientId, clientSecret));
    }

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

    // If there's a proxy, set that too.
    if (proxyHost != null && proxyHost.length() > 0) {

        // Configure proxy authentication
        if (proxyUsername != null && proxyUsername.length() > 0) {
            if (proxyPassword == null)
                proxyPassword = "";
            if (proxyDomain == null)
                proxyDomain = "";

            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
        }

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        requestBuilder.setProxy(proxy);
    }

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

}

From source file:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceSession.java

public ConfluenceSession(String clientId, String clientSecret, String protocol, String host, int port,
        String path, String proxyHost, int proxyPort, String proxyDomain, String proxyUsername,
        String proxyPassword) throws ManifoldCFException {
    this.host = new HttpHost(host, port, protocol);
    this.path = path;
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    int socketTimeout = 900000;
    int connectionTimeout = 60000;

    javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory();
    SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
            new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // If authentication needed, set that
    if (clientId != null) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(clientId, clientSecret));
    }/*from  w w w  .jav a 2 s.  c o  m*/

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

    // If there's a proxy, set that too.
    if (proxyHost != null && proxyHost.length() > 0) {

        // Configure proxy authentication
        if (proxyUsername != null && proxyUsername.length() > 0) {
            if (proxyPassword == null)
                proxyPassword = "";
            if (proxyDomain == null)
                proxyDomain = "";

            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
        }

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        requestBuilder.setProxy(proxy);
    }

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

From source file:org.alfresco.rad.test.AlfrescoTestRunner.java

/**
 * Call a remote Alfresco server and have the test run there.
 *
 * @param method   the test method to run
 * @param notifier/* w w  w  .j  av a 2s . c  o  m*/
 * @param desc
 */
protected void callProxiedChild(FrameworkMethod method, RunNotifier notifier, Description desc) {
    notifier.fireTestStarted(desc);

    String className = method.getMethod().getDeclaringClass().getCanonicalName();
    String methodName = method.getName();
    if (null != methodName) {
        className += "#" + methodName;
    }

    // Login credentials for Alfresco Repo
    // TODO: Maybe configure credentials in props...
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin");
    provider.setCredentials(AuthScope.ANY, credentials);

    // Create HTTP Client with credentials
    CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

    // Create the GET Request for the Web Script that will run the test
    String testWebScriptUrl = "/service/testing/test.xml?clazz=" + className.replace("#", "%23");
    //System.out.println("AlfrescoTestRunner: Invoking Web Script for test execution: " + testWebScriptUrl);
    HttpGet get = new HttpGet(getContextRoot(method) + testWebScriptUrl);

    try {
        // Send proxied request and read response
        HttpResponse resp = httpclient.execute(get);
        InputStream is = resp.getEntity().getContent();
        InputStreamReader ir = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(ir);
        String body = "";
        String line;
        while ((line = br.readLine()) != null) {
            body += line + "\n";
        }

        // Process response
        if (body.length() > 0) {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = null;
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(new InputSource(new StringReader(body)));

            Element root = doc.getDocumentElement();
            NodeList results = root.getElementsByTagName("result");
            if (null != results && results.getLength() > 0) {
                String result = results.item(0).getFirstChild().getNodeValue();
                if (SUCCESS.equals(result)) {
                    notifier.fireTestFinished(desc);
                } else {
                    boolean failureFired = false;
                    NodeList throwableNodes = root.getElementsByTagName("throwable");
                    for (int tid = 0; tid < throwableNodes.getLength(); tid++) {
                        String throwableBody = null;
                        Object object = null;
                        Throwable throwable = null;
                        throwableBody = throwableNodes.item(tid).getFirstChild().getNodeValue();
                        if (null != throwableBody) {
                            try {
                                object = objectFromString(throwableBody);
                            } catch (ClassNotFoundException e) {
                            }
                            if (null != object && object instanceof Throwable) {
                                throwable = (Throwable) object;
                            }
                        }
                        if (null == throwable) {
                            throwable = new Throwable("Unable to process exception body: " + throwableBody);
                        }

                        notifier.fireTestFailure(new Failure(desc, throwable));
                        failureFired = true;
                    }
                    if (!failureFired) {
                        notifier.fireTestFailure(new Failure(desc, new Throwable(
                                "There was an error but we can't figure out what it was, sorry!")));
                    }
                }
            } else {
                notifier.fireTestFailure(new Failure(desc,
                        new Throwable("Unable to process response for proxied test request: " + body)));
            }
        } else {
            notifier.fireTestFailure(new Failure(desc, new Throwable(
                    "Attempt to proxy test into running Alfresco instance failed, no response received")));
        }
    } catch (IOException e) {
        notifier.fireTestFailure(new Failure(desc, e));
    } catch (ParserConfigurationException e) {
        notifier.fireTestFailure(new Failure(desc, e));
    } catch (SAXException e) {
        notifier.fireTestFailure(new Failure(desc, e));
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:ch.admin.hermes.etl.load.SharePoint2010RESTClient.java

/**
 * @throws IOException//from  w w  w  . j a v  a 2  s .co  m
 */
private void init(String remote, String user, String pass) throws IOException {
    this.remote = (remote != null) ? remote : this.remote;
    this.user = (user != null) ? user : this.user;
    this.pass = (pass != null) ? pass : this.pass;

    client = getHttpClient();

    // localhost und domain nicht setzen, gibt Probleme mit https://
    NTCredentials creds = new NTCredentials(this.user, this.pass, "", "");
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.NTLM);
    client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
}

From source file:it.cloudicaro.disit.kb.rdf.HttpUtil.java

public static void delete(URL url, String user, String passwd) throws Exception {
    //System.out.println("DELETE "+url);
    HttpClient client = HttpClients.createDefault();
    HttpDelete request = new HttpDelete(url.toURI());

    HttpClientContext context = HttpClientContext.create();
    if (user != null && passwd != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, passwd));
        context.setCredentialsProvider(credsProvider);
    }//from  w  ww . ja v a2s  . c  o m

    HttpResponse response = client.execute(request, context);

    StatusLine s = response.getStatusLine();
    int code = s.getStatusCode();
    //System.out.println(code);
    if (code != 204 && code != 404)
        throw new Exception(
                "failed access to " + url.toString() + " code: " + code + " " + s.getReasonPhrase());
}

From source file:org.mobicents.servlet.restcomm.provisioning.number.bandwidth.BandwidthNumberProvisioningManager.java

@Override
public void init(org.apache.commons.configuration.Configuration phoneNumberProvisioningConfiguration,
        org.apache.commons.configuration.Configuration telestaxProxyConfiguration,
        ContainerConfiguration containerConfiguration) {
    this.containerConfiguration = containerConfiguration;
    telestaxProxyEnabled = telestaxProxyConfiguration.getBoolean("enabled", false);
    if (telestaxProxyEnabled) {
        uri = telestaxProxyConfiguration.getString("uri");
        username = telestaxProxyConfiguration.getString("login");
        password = telestaxProxyConfiguration.getString("password");
        accountId = telestaxProxyConfiguration.getString("endpoint");
        siteId = telestaxProxyConfiguration.getString("siteId");
        activeConfiguration = telestaxProxyConfiguration;
    } else {/*from   w  ww  .  ja  va2 s  .c  o  m*/
        Configuration bandwidthConfiguration = phoneNumberProvisioningConfiguration.subset("bandwidth");
        uri = bandwidthConfiguration.getString("uri");
        username = bandwidthConfiguration.getString("username");
        password = bandwidthConfiguration.getString("password");
        accountId = bandwidthConfiguration.getString("accountId");
        siteId = bandwidthConfiguration.getString("siteId");
        activeConfiguration = bandwidthConfiguration;
    }
    httpClient = new DefaultHttpClient();
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
}

From source file:org.testcontainers.elasticsearch.ElasticsearchContainerTest.java

private RestClient getClient(ElasticsearchContainer container) {
    if (client == null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD));

        client = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                        .setDefaultCredentialsProvider(credentialsProvider))
                .build();//from w w w.j av a 2s.  c o m
    }

    return client;
}