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.frank.search.solr.server.support.HttpSolrClientFactory.java

private void appendAuthentication(Credentials credentials, String authPolicy, SolrClient solrClient) {
    if (isHttpSolrClient(solrClient)) {
        HttpSolrClient httpSolrClient = (HttpSolrClient) solrClient;

        if (credentials != null && StringUtils.isNotBlank(authPolicy)
                && assertHttpClientInstance(httpSolrClient.getHttpClient())) {
            AbstractHttpClient httpClient = (AbstractHttpClient) httpSolrClient.getHttpClient();
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
            httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Arrays.asList(authPolicy));
        }//from  w w  w  .  j a  v  a  2  s. c  o m
    }
}

From source file:neembuu.release1.httpclient.NHttpClient.java

public static DefaultHttpClient getNewInstance() {
    DefaultHttpClient new_httpClient = null;
    new_httpClient = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {/*from   w  ww  . ja  va  2 s .c  o  m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            new_httpClient.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    new_httpClient = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        new_httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return new_httpClient;
}

From source file:ch.sbb.releasetrain.utils.http.HttpUtilImpl.java

/**
 * authenticates the context if user and password are set
 *//* w  ww .jav  a  2  s  .  c o m*/
private HttpClientContext initAuthIfNeeded(String url) {

    HttpClientContext context = HttpClientContext.create();
    if (this.user.isEmpty() || this.password.isEmpty()) {
        log.debug(
                "http connection without autentication, because no user / password ist known to HttpUtilImpl ...");
        return context;
    }

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(user, password));
    URL url4Host;
    try {
        url4Host = new URL(url);
    } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
        return context;
    }

    HttpHost targetHost = new HttpHost(url4Host.getHost(), url4Host.getPort(), url4Host.getProtocol());
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}

From source file:org.apache.jena.fuseki.embedded.TestFusekiTestAuth.java

@Test(expected = HttpException.class)
public void testServer_auth_bad_password() {
    BasicCredentialsProvider credsProv = new BasicCredentialsProvider();
    credsProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER, "WRONG"));
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProv).build();

    try (TypedInputStream in = HttpOp.execHttpGet(FusekiTestAuth.urlDataset(), "*/*", client, null)) {
    } catch (HttpException ex) {
        throw assertAuthHttpException(ex);
    }/*from w  w  w  . jav a2  s. c om*/
}

From source file:de.dan_nrw.web.WebClient.java

/**
 * Sends a http request and handles response using specified ResponseHandler
 * @param <T> Type of return/*from  ww w .  j  ava  2  s  . com*/
 * @param uri URI to use
 * @param responseHandler Response handled used for handling response
 * @return
 * @throws IOException if response handling fails
 * @throws ProtocolException if request returns an error
 */
public <T> T sendRequest(URI uri, ResponseHandler<T> responseHandler) throws IOException, ProtocolException {
    HttpGet request = new HttpGet(uri);
    request.addHeader("User-agent", this.userAgent.getHeaderValue());

    DefaultHttpClient client = new DefaultHttpClient();

    if (this.credentials != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, this.credentials);
    }

    return client.execute(request, responseHandler);
}

From source file:com.ontotext.s4.gdbaas.createRepo.service.GdbaasClient.java

/**
 * Sets up a HTTPContext for authentication
 *//*w ww . j  ava2  s.  c o m*/
private void setupContext() {
    ctx = HttpClientContext.create();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(keyId, password);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, creds);
    ctx.setCredentialsProvider(credsProvider);
}

From source file:org.apache.activemq.artemis.rest.queue.push.UriStrategy.java

protected void initAuthentication() {
    if (registration.getAuthenticationMechanism() != null) {
        if (registration.getAuthenticationMechanism().getType() instanceof BasicAuth) {
            BasicAuth basic = (BasicAuth) registration.getAuthenticationMechanism().getType();
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(basic.getUsername(),
                    basic.getPassword());
            AuthScope authScope = new AuthScope(AuthScope.ANY);
            ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(authScope, creds);

            localContext = new BasicHttpContext();

            // Generate BASIC scheme object and stick it to the local execution context
            BasicScheme basicAuth = new BasicScheme();
            localContext.setAttribute("preemptive-auth", basicAuth);

            // Add as the first request interceptor
            ((DefaultHttpClient) client).addRequestInterceptor(new PreemptiveAuth(), 0);
            executor.setHttpContext(localContext);
        }//  w  w w  . ja va 2  s. com
    }
}

From source file:org.nuxeo.scim.server.tests.ScimServerTest.java

protected static ClientConfig createHttpBasicClientConfig(final String userName, final String password) {

    final HttpParams params = new BasicHttpParams();
    DefaultHttpClient.setDefaultHttpParams(params);
    params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, true);
    params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);

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

    final PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(schemeRegistry);
    mgr.setMaxTotal(200);/*  w w  w.  ja  va2  s .  co m*/
    mgr.setDefaultMaxPerRoute(20);

    final DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params);

    final Credentials credentials = new UsernamePasswordCredentials(userName, password);
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

    ClientConfig clientConfig = new ApacheHttpClientConfig(httpClient);
    clientConfig.setBypassHostnameVerification(true);

    return clientConfig;
}

From source file:fr.logfiletoes.config.Unit.java

/**
 * Initialise ElasticSearch Index ans taile file
 * @throws IOException //  w w w. j  a  v  a 2s .  c om
 */
public void start() throws IOException {
    httpclient = HttpClients.createDefault();
    context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(getElasticSearch().getUrl());
    if (getElasticSearch().getLogin() != null && getElasticSearch().getPassword() != null) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getElasticSearch().getLogin(),
                getElasticSearch().getPassword());
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, credentials);
        context.setCredentialsProvider(credentialsProvider);
    }
    CloseableHttpResponse elasticSearchCheck = httpclient.execute(httpGet, context);
    LOG.log(Level.INFO, "Check index : \"{0}\"", elasticSearchCheck.getStatusLine().getStatusCode());
    LOG.log(Level.INFO, inputSteamToString(elasticSearchCheck.getEntity().getContent()));
    int statusCodeCheck = elasticSearchCheck.getStatusLine().getStatusCode();
    EntityUtils.consume(elasticSearchCheck.getEntity());
    elasticSearchCheck.close();

    if (statusCodeCheck == 404) {
        // Cration de l'index
        HttpPut httpPut = new HttpPut(getElasticSearch().getUrl());
        CloseableHttpResponse executeCreateIndex = httpclient.execute(httpPut, context);
        LOG.log(Level.INFO, "Create index : \"{0}\"", executeCreateIndex.getStatusLine().getStatusCode());
        LOG.log(Level.INFO, inputSteamToString(executeCreateIndex.getEntity().getContent()));
        EntityUtils.consume(executeCreateIndex.getEntity());
        executeCreateIndex.close();

        CloseableHttpResponse elasticSearchCheckCreate = httpclient.execute(httpGet, context);
        LOG.log(Level.INFO, "Check create index : \"{0}\"",
                elasticSearchCheckCreate.getStatusLine().getStatusCode());
        LOG.log(Level.INFO, inputSteamToString(elasticSearchCheckCreate.getEntity().getContent()));
        int statusCodeCheckCreate = elasticSearchCheckCreate.getStatusLine().getStatusCode();
        EntityUtils.consume(elasticSearchCheckCreate.getEntity());
        elasticSearchCheckCreate.close();

        if (statusCodeCheckCreate != 200) {
            LOG.log(Level.SEVERE, "unable to create index \"{0}\"", getElasticSearch().getUrl());
            throw new IOException("unable to create index \"" + getElasticSearch().getUrl() + "\"");
        }
    } else if (elasticSearchCheck.getStatusLine().getStatusCode() != 200) {
        LOG.severe("unkown error elasticsearch");
        throw new IOException("unkown error elasticsearch");
    }
    LOG.log(Level.INFO, "Initialisation ElasticSearch r\u00e9ussi pour {0}", getElasticSearch().getUrl());

    tailer = Tailer.create(getLogFile(), new TailerListenerUnit(this, httpclient, context));
}

From source file:org.wildfly.test.integration.elytron.http.PasswordMechTestBase.java

@Test
public void testInvalidPrincipal() throws Exception {
    HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1wrong", "password1");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, credentials);

    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build()) {// w  w  w .ja  v a 2 s.  co m
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            int statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
        }
    }
}