Example usage for org.apache.http.auth.params AuthPNames PROXY_AUTH_PREF

List of usage examples for org.apache.http.auth.params AuthPNames PROXY_AUTH_PREF

Introduction

In this page you can find the example usage for org.apache.http.auth.params AuthPNames PROXY_AUTH_PREF.

Prototype

String PROXY_AUTH_PREF

To view the source code for org.apache.http.auth.params AuthPNames PROXY_AUTH_PREF.

Click Source Link

Document

Defines the order of preference for supported org.apache.http.auth.AuthScheme s when authenticating with the proxy host.

Usage

From source file:org.datacleaner.cluster.http.SimpleMainAppForManualTesting.java

public static void main(String[] args) throws Throwable {

    // create a HTTP BASIC enabled HTTP client
    final DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    final CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin");
    final List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);//from ww  w.  j av a2s.c om
    authpref.add(AuthPolicy.DIGEST);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    credentialsProvider.setCredentials(new AuthScope("localhost", 8080), credentials);
    credentialsProvider.setCredentials(new AuthScope("localhost", 9090), credentials);

    // register endpoints
    final List<String> slaveEndpoints = new ArrayList<String>();
    slaveEndpoints.add("http://localhost:8080/DataCleaner-monitor/repository/DC/cluster_slave_endpoint");
    slaveEndpoints.add("http://localhost:9090/DataCleaner-monitor/repository/DC/cluster_slave_endpoint");

    final HttpClusterManager clusterManager = new HttpClusterManager(httpClient, slaveEndpoints);

    final DataCleanerConfiguration configuration = ClusterTestHelper.createConfiguration("manual_test", false);

    // build a job that concats names and inserts the concatenated names
    // into a file
    final AnalysisJobBuilder jobBuilder = new AnalysisJobBuilder(configuration);
    jobBuilder.setDatastore("orderdb");
    jobBuilder.addSourceColumns("CUSTOMERS.CUSTOMERNUMBER", "CUSTOMERS.CUSTOMERNAME",
            "CUSTOMERS.CONTACTFIRSTNAME", "CUSTOMERS.CONTACTLASTNAME");

    AnalyzerComponentBuilder<CompletenessAnalyzer> completeness = jobBuilder
            .addAnalyzer(CompletenessAnalyzer.class);
    completeness.addInputColumns(jobBuilder.getSourceColumns());
    completeness.setConfiguredProperty("Conditions",
            new CompletenessAnalyzer.Condition[] { CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL });

    AnalysisJob job = jobBuilder.toAnalysisJob();
    jobBuilder.close();

    AnalysisResultFuture result = new DistributedAnalysisRunner(configuration, clusterManager).run(job);

    if (result.isErrornous()) {
        throw result.getErrors().get(0);
    }

    final List<AnalyzerResult> results = result.getResults();
    for (AnalyzerResult analyzerResult : results) {
        System.out.println("result:" + analyzerResult);
        if (analyzerResult instanceof CompletenessAnalyzerResult) {
            int invalidRowCount = ((CompletenessAnalyzerResult) analyzerResult).getInvalidRowCount();
            System.out.println("invalid records found: " + invalidRowCount);
        } else {
            System.out.println("class: " + analyzerResult.getClass().getName());
        }
    }
}

From source file:org.eobjects.analyzer.cluster.http.SimpleMainAppForManualTesting.java

public static void main(String[] args) throws Throwable {

    // create a HTTP BASIC enabled HTTP client
    final DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    final CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin");
    final List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);//from   w ww .j av  a2  s. co m
    authpref.add(AuthPolicy.DIGEST);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    credentialsProvider.setCredentials(new AuthScope("localhost", 8080), credentials);
    credentialsProvider.setCredentials(new AuthScope("localhost", 9090), credentials);

    // register endpoints
    final List<String> slaveEndpoints = new ArrayList<String>();
    slaveEndpoints.add("http://localhost:8080/DataCleaner-monitor/repository/DC/cluster_slave_endpoint");
    slaveEndpoints.add("http://localhost:9090/DataCleaner-monitor/repository/DC/cluster_slave_endpoint");

    final HttpClusterManager clusterManager = new HttpClusterManager(httpClient, slaveEndpoints);

    final AnalyzerBeansConfiguration configuration = ClusterTestHelper.createConfiguration("manual_test",
            false);

    // build a job that concats names and inserts the concatenated names
    // into a file
    final AnalysisJobBuilder jobBuilder = new AnalysisJobBuilder(configuration);
    jobBuilder.setDatastore("orderdb");
    jobBuilder.addSourceColumns("CUSTOMERS.CUSTOMERNUMBER", "CUSTOMERS.CUSTOMERNAME",
            "CUSTOMERS.CONTACTFIRSTNAME", "CUSTOMERS.CONTACTLASTNAME");

    AnalyzerJobBuilder<CompletenessAnalyzer> completeness = jobBuilder.addAnalyzer(CompletenessAnalyzer.class);
    completeness.addInputColumns(jobBuilder.getSourceColumns());
    completeness.setConfiguredProperty("Conditions",
            new CompletenessAnalyzer.Condition[] { CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL,
                    CompletenessAnalyzer.Condition.NOT_BLANK_OR_NULL });

    AnalysisJob job = jobBuilder.toAnalysisJob();
    jobBuilder.close();

    AnalysisResultFuture result = new DistributedAnalysisRunner(configuration, clusterManager).run(job);

    if (result.isErrornous()) {
        throw result.getErrors().get(0);
    }

    final List<AnalyzerResult> results = result.getResults();
    for (AnalyzerResult analyzerResult : results) {
        System.out.println("result:" + analyzerResult);
        if (analyzerResult instanceof CompletenessAnalyzerResult) {
            int invalidRowCount = ((CompletenessAnalyzerResult) analyzerResult).getInvalidRowCount();
            System.out.println("invalid records found: " + invalidRowCount);
        } else {
            System.out.println("class: " + analyzerResult.getClass().getName());
        }
    }
}

From source file:org.datacleaner.util.http.HttpBasicMonitorHttpClient.java

public HttpBasicMonitorHttpClient(HttpClient httpClient, String hostname, int port, String username,
        String password) {//from  w  ww. j  av a2  s.  c  o m
    _httpClient = (DefaultHttpClient) httpClient;

    final CredentialsProvider credentialsProvider = _httpClient.getCredentialsProvider();

    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    final List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    _httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);

    credentialsProvider.setCredentials(new AuthScope(hostname, port), credentials);
}

From source file:org.datacleaner.monitor.cluster.HttpClusterManagerFactory.java

@Override
public ClusterManager getClusterManager(TenantIdentifier tenant) {
    final DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    if (username != null && password != null) {
        final CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider();
        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        final List<String> authpref = new ArrayList<String>();
        authpref.add(AuthPolicy.BASIC);/*w w  w. j av a  2  s  .c  om*/
        authpref.add(AuthPolicy.DIGEST);
        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
        credentialsProvider.setCredentials(new AuthScope(null, -1), credentials);
    }

    // use the server list
    final List<String> finalEndpoints = new ArrayList<String>();
    for (String endpoint : slaveServerUrls) {
        if (!endpoint.endsWith("/")) {
            endpoint = endpoint + "/";
        }
        endpoint = endpoint + "repository/" + tenant.getId() + "/cluster_slave_endpoint";
        finalEndpoints.add(endpoint);
    }

    return new HttpClusterManager(httpClient, finalEndpoints);
}

From source file:com.github.restdriver.clientdriver.integration.BasicAuthTest.java

@Test
public void basicAuthWorks() throws Exception {

    clientDriver.addExpectation(onRequestTo("/").withBasicAuth("Aladdin", "open sesame"),
            giveEmptyResponse().withStatus(418)).anyTimes();

    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("Aladdin", "open sesame"));

    HttpHost host = new HttpHost("localhost", 12345);

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);//w  ww.  j ava 2  s.  c  o m

    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTH_CACHE, authCache);

    List<String> authPrefs = new ArrayList<String>();
    authPrefs.add(AuthPolicy.BASIC);
    client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPrefs);

    HttpGet get = new HttpGet(clientDriver.getBaseUrl() + "/");

    HttpResponse response = client.execute(host, get, context);

    assertThat(response.getStatusLine().getStatusCode(), is(418));

}

From source file:org.eobjects.datacleaner.monitor.pentaho.PentahoCarteClient.java

private HttpClient createHttpClient(PentahoJobType pentahoJobType) {
    final String hostname = pentahoJobType.getCarteHostname();
    final Integer port = pentahoJobType.getCartePort();
    final String username = pentahoJobType.getCarteUsername();
    final String password = pentahoJobType.getCartePassword();

    final DefaultHttpClient httpClient = new DefaultHttpClient();
    final CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider();

    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    final List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);/*  www .  j a  va  2s.  c  om*/
    authpref.add(AuthPolicy.DIGEST);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);

    credentialsProvider.setCredentials(new AuthScope(hostname, port), credentials);
    return httpClient;
}

From source file:dk.deck.resolver.ArtifactResolverRemote.java

public ArtifactResolverRemote(List<String> repositories, String username, String password) {
    this.repositories = Collections.unmodifiableList(repositories);
    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    connectionManager.setMaxTotal(MAX_HTTP_THREADS);
    connectionManager.setDefaultMaxPerRoute(MAX_HTTP_THREADS);
    httpclient = new DefaultHttpClient(connectionManager);

    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);/* w w  w  .j a va 2s . c o  m*/
    authpref.add(AuthPolicy.DIGEST);
    httpclient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

}

From source file:glaze.oauth.PreemptiveAuthorizer.java

/**
 * If no auth scheme has been selected for the given context, consider each
 * of the preferred auth schemes and select the first one for which an
 * AuthScheme and matching Credentials are available.
 *//*from   w ww.j a va  2  s  . c o  m*/
@SuppressWarnings("unchecked")
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

    if (authState != null && authState.getAuthScheme() != null) {
        return;
    }

    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    CredentialsProvider provider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
    AuthSchemeRegistry schemes = (AuthSchemeRegistry) context.getAttribute(ClientContext.AUTHSCHEME_REGISTRY);
    HttpParams params = request.getParams();

    for (String schemeName : (Iterable<String>) params.getParameter(AuthPNames.PROXY_AUTH_PREF)) {
        AuthScheme scheme = schemes.getAuthScheme(schemeName, params);
        if (scheme != null) {
            AuthScope targetScope = new AuthScope(target.getHostName(), target.getPort(), scheme.getRealm(),
                    scheme.getSchemeName());
            Credentials creds = provider.getCredentials(targetScope);

            if (creds != null) {
                authState.update(scheme, creds);
                return;
            }
        }
    }
}

From source file:org.openrepose.commons.utils.http.ServiceClient.java

private HttpClient getClientWithBasicAuth() throws ServiceClientException {
    HttpClientResponse clientResponse = null;

    try {/*  www  .j  ava2  s. c  om*/

        clientResponse = httpClientService.getClient(connectionPoolId);
        final HttpClient client = clientResponse.getHttpClient();

        if (!StringUtilities.isEmpty(targetHostUri) && !StringUtilities.isEmpty(username)
                && !StringUtilities.isEmpty(password)) {

            client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, AuthPolicy.BASIC);

            CredentialsProvider credsProvider = new BasicCredentialsProvider();

            credsProvider.setCredentials(new AuthScope(targetHostUri, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(username, password));
            client.getParams().setParameter("http.authentication.credential-provider", credsProvider);

        }

        return client;

    } catch (HttpClientNotFoundException e) {
        LOG.error("Failed to obtain an HTTP default client connection");
        throw new ServiceClientException("Failed to obtain an HTTP default client connection", e);
    } finally {
        if (clientResponse != null) {
            httpClientService.releaseClient(clientResponse);
        }
    }

}

From source file:com.android.sdklib.internal.repository.UrlOpener.java

private static InputStream openWithHttpClient(String url, ITaskMonitor monitor)
        throws IOException, ClientProtocolException, CanceledByUserException {
    UserCredentials result = null;/*from   w w  w  .  j a v a 2 s .c om*/
    String realm = null;

    // use the simple one
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpget = new HttpGet(url);

    // retrieve local java configured network in case there is the need to
    // authenticate a proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Set preference order for authentication options.
    // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in
    // servers that support both, as it is more secure. However, we don't seem to handle it
    // very well, so we leave it off the list.
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for
    // more info.
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.NTLM);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    boolean trying = true;
    // loop while the response is being fetched
    while (trying) {
        // connect and get status code
        HttpResponse response = httpClient.execute(httpget, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        // check whether any authentication is required
        AuthState authenticationState = null;
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_OK) {
            // in case the status is OK and there is a realm and result,
            // cache it
            if (realm != null && result != null) {
                sRealmCache.put(realm, result);
            }
        }

        // there is the need for authentication
        if (authenticationState != null) {

            // get scope and realm
            AuthScope authScope = authenticationState.getAuthScope();

            // If the current realm is different from the last one it means
            // a pass was performed successfully to the last URL, therefore
            // cache the last realm
            if (realm != null && !realm.equals(authScope.getRealm())) {
                sRealmCache.put(realm, result);
            }

            realm = authScope.getRealm();

            // in case there is cache for this Realm, use it to authenticate
            if (sRealmCache.containsKey(realm)) {
                result = sRealmCache.get(realm);
            } else {
                // since there is no cache, request for login and password
                result = monitor.displayLoginCredentialsPrompt("Site Authentication",
                        "Please login to the following domain: " + realm
                                + "\n\nServer requiring authentication:\n" + authScope.getHost());
                if (result == null) {
                    throw new CanceledByUserException("User canceled login dialog.");
                }
            }

            // retrieve authentication data
            String user = result.getUserName();
            String password = result.getPassword();
            String workstation = result.getWorkstation();
            String domain = result.getDomain();

            // proceed in case there is indeed a user
            if (user != null && user.length() > 0) {
                Credentials credentials = new NTCredentials(user, password, workstation, domain);
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (trying) {
                // in case another pass to the Http Client will be performed, close the entity.
                entity.getContent().close();
            } else {
                // since no pass to the Http Client is needed, retrieve the
                // entity's content.

                // Note: don't use something like a BufferedHttpEntity since it would consume
                // all content and store it in memory, resulting in an OutOfMemory exception
                // on a large download.

                return new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        super.close();

                        // since Http Client is no longer needed, close it
                        httpClient.getConnectionManager().shutdown();
                    }
                };
            }
        }
    }

    // We get here if we did not succeed. Callers do not expect a null result.
    httpClient.getConnectionManager().shutdown();
    throw new FileNotFoundException(url);
}