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:org.alfresco.tutorials.webscripts.HelloWorldWebScriptIT.java

@Test
public void testWebScriptCall() throws Exception {
    String webscriptURL = "http://localhost:8080/alfresco/service/sample/helloworld";
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 8080),
            new UsernamePasswordCredentials(ALFRESCO_USERNAME, ALFRESCO_PWD));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    try {//from  w  w w.j  av a  2s  .c  o  m
        HttpGet httpget = new HttpGet(webscriptURL);
        HttpResponse httpResponse = httpclient.execute(httpget);
        assertEquals("HTTP Response Status is not OK(200)", HttpStatus.SC_OK,
                httpResponse.getStatusLine().getStatusCode());
        HttpEntity entity = httpResponse.getEntity();
        assertNotNull("Response from Web Script is null", entity);
        String response = EntityUtils.toString(entity);
        JSONParser parser = new JSONParser();
        JSONObject jsonResponseObj = (JSONObject) parser.parse(response);
        assertTrue("Folder not found", (boolean) jsonResponseObj.get("foundFolder"));
        assertTrue("Doc not found", (boolean) jsonResponseObj.get("foundDoc"));
    } finally {
        httpclient.close();
    }
}

From source file:org.georchestra.extractorapp.ws.extractor.csw.MetadataEntity.java

/**
 * Stores the metadata retrieved from CSW using the request value.
 * //from ww w  .  j  a  v  a  2  s.c  o  m
 * @param fileName file name where the metadata must be saved.
 * 
 * @throws IOException
 */
public void save(final String fileName) throws IOException {

    InputStream content = null;
    BufferedReader reader = null;
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(fileName, "UTF-8");

        HttpGet get = new HttpGet(this.request.buildURI());
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpClientContext localContext = HttpClientContext.create();

        // if credentials are actually provided, use them to configure
        // the HttpClient object.
        try {
            if (this.request.getUser() != null && request.getPassword() != null) {
                Credentials credentials = new UsernamePasswordCredentials(request.getUser(),
                        request.getPassword());
                AuthScope authScope = new AuthScope(get.getURI().getHost(), get.getURI().getPort());
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(authScope, credentials);
                localContext.setCredentialsProvider(credentialsProvider);
            }
        } catch (Exception e) {
            LOG.error(
                    "Unable to set basic-auth on http client to get the Metadata remotely, trying without ...",
                    e);
        }
        content = httpclient.execute(get, localContext).getEntity().getContent();
        reader = new BufferedReader(new InputStreamReader(content));

        String line = reader.readLine();
        while (line != null) {

            writer.println(line);

            line = reader.readLine();
        }

    } catch (Exception e) {

        final String msg = "The metadata could not be extracted";
        LOG.error(msg, e);

        throw new IOException(e);

    } finally {

        if (writer != null)
            writer.close();

        if (reader != null)
            reader.close();

        if (content != null)
            content.close();
    }
}

From source file:net.bioclipse.dbxp.business.DbxpManager.java

public static HttpResponse postValues(HashMap<String, String> postvars, String url)
        throws NoSuchAlgorithmException, ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(userName, password));

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    Iterator<Entry<String, String>> it = postvars.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> next = (Map.Entry<String, String>) it.next();
        Map.Entry<String, String> pairs = next;
        formparams.add(new BasicNameValuePair(pairs.getKey(), pairs.getValue()));
    }/*from  w  w  w  .j  av  a  2  s.  com*/
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost(url);
    httppost.setEntity(entity);
    HttpContext localContext = new BasicHttpContext();
    return httpclient.execute(httppost, localContext);
}

From source file:org.commonjava.indy.httprox.AbstractHttproxFunctionalTest.java

protected CloseableHttpClient proxiedHttp(final String user, final String pass, SSLSocketFactory socketFactory)
        throws Exception {
    CredentialsProvider creds = null;//from   w w w  .  ja va 2 s.c  o m

    if (user != null) {
        creds = new BasicCredentialsProvider();
        creds.setCredentials(new AuthScope(HOST, proxyPort), new UsernamePasswordCredentials(user, pass));
    }

    HttpHost proxy = new HttpHost(HOST, proxyPort);

    final HttpRoutePlanner planner = new DefaultProxyRoutePlanner(proxy);
    HttpClientBuilder builder = HttpClients.custom().setRoutePlanner(planner)
            .setDefaultCredentialsProvider(creds).setProxy(proxy).setSSLSocketFactory(socketFactory);

    return builder.build();
}

From source file:io.wcm.caravan.commons.httpasyncclient.impl.HttpAsyncClientItem.java

/**
 * @param config Http client configuration
 *//* w  w  w.j a  va  2s.c  o m*/
HttpAsyncClientItem(HttpClientConfig config) {
    this.config = config;

    // optional SSL client certificate support
    SSLContext sslContext;
    if (CertificateLoader.isSslKeyManagerEnabled(config) || CertificateLoader.isSslTrustStoreEnbaled(config)) {
        try {
            sslContext = CertificateLoader.buildSSLContext(config);
        } catch (IOException | GeneralSecurityException ex) {
            throw new IllegalArgumentException("Invalid SSL client certificate configuration.", ex);
        }
    } else {
        sslContext = CertificateLoader.createDefaultSSlContext();
    }

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // optional proxy authentication
    if (StringUtils.isNotEmpty(config.getProxyUser())) {
        credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                new UsernamePasswordCredentials(config.getProxyUser(), config.getProxyPassword()));
    }
    // optional http basic authentication support
    if (StringUtils.isNotEmpty(config.getHttpUser())) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(config.getHttpUser(), config.getHttpPassword()));
    }

    // build http clients
    asyncConnectionManager = buildAsyncConnectionManager(config, sslContext);
    httpAsyncClient = buildHttpAsyncClient(config, asyncConnectionManager, credentialsProvider);

    // start async client
    httpAsyncClient.start();
}

From source file:org.jboss.as.test.integration.web.security.basic.WebSecurityBASICTestCase.java

@Override
protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*  w w  w  . j  av a2s.c  o  m*/
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/");

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:io.bosh.client.SpringDirectorClientBuilder.java

private ClientHttpRequestFactory createRequestFactory(String host, String username, String password) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555),
            new UsernamePasswordCredentials(username, password));

    SSLContext sslContext = null;
    try {/*w ww .j a  v a2 s.  c om*/
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
                .build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new DirectorException("Unable to configure ClientHttpRequestFactory", e);
    }

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());

    // disabling redirect handling is critical for the way BOSH uses 302's
    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling()
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(connectionFactory).build();

    return new HttpComponentsClientHttpRequestFactory(httpClient);
}

From source file:org.sonatype.nexus.testsuite.NexusHttpsITSupport.java

/**
 * @return Provider of credentials for preemptive auth
 *//*from   w  ww . j a v a2  s. co m*/
protected CredentialsProvider credentialsProvider() {
    String hostname = nexusUrl.getHost();
    AuthScope scope = new AuthScope(hostname, -1);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(scope, credentials());
    return credentialsProvider;
}

From source file:ca.uhn.fhir.rest.client.apache.ApacheRestfulClientFactory.java

public synchronized HttpClient getNativeHttpClient() {
    if (myHttpClient == null) {

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000,
                TimeUnit.MILLISECONDS);
        connectionManager.setMaxTotal(getPoolMaxTotal());
        connectionManager.setDefaultMaxPerRoute(getPoolMaxPerRoute());

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

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(defaultRequestConfig).disableCookieManagement();

        if (myProxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(myProxy.getHostName(), myProxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credsProvider);
        }/*  www  . j  a  va  2s .  c om*/

        myHttpClient = builder.build();
        // @formatter:on

    }

    return myHttpClient;
}

From source file:org.qi4j.library.shiro.UsernamePasswordHttpBasicTest.java

@Test
public void test() throws IOException {

    HttpGet get = new HttpGet(SECURED_SERVLET_PATH);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials(UsernameFixtures.USERNAME, new String(UsernameFixtures.PASSWORD)));

    // First request with credentials
    String response = client.execute(httpHost, get, responseHandler);
    assertEquals(ServletUsingSecuredService.OK, response);

    // Cookies logging for the curious
    soutCookies(client.getCookieStore().getCookies());

    // Second request without credentials, should work thanks to sessions
    client.getCredentialsProvider().clear();
    response = client.execute(httpHost, get, responseHandler);
    assertEquals(ServletUsingSecuredService.OK, response);

}