Example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider.

Prototype

public synchronized final CredentialsProvider getCredentialsProvider() 

Source Link

Usage

From source file:de.escidoc.core.test.common.fedora.TripleStoreTestBase.java

protected DefaultHttpClient getHttpClient() throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    URL url = new URL(getFedoraUrl());
    AuthScope m_authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
    UsernamePasswordCredentials m_creds = new UsernamePasswordCredentials("fedoraAdmin", "fedoraAdmin");
    httpClient.getCredentialsProvider().setCredentials(m_authScope, m_creds);

    return httpClient;
}

From source file:org.apache.ambari.server.controller.internal.AppCookieManager.java

/**
 * Returns hadoop.auth cookie, doing needed SPNego authentication
 * //from   w  w w . j  ava2s. c o  m
 * @param endpoint
 *          the URL of the Hadoop service
 * @param refresh
 *          flag indicating wehther to refresh the cookie, if
 *          <code>true</code>, we do a new SPNego authentication and refresh
 *          the cookie even if the cookie already exists in local cache
 * @return hadoop.auth cookie value
 * @throws IOException
 *           in case of problem getting hadoop.auth cookie
 */
public String getAppCookie(String endpoint, boolean refresh) throws IOException {

    HttpUriRequest outboundRequest = new HttpGet(endpoint);
    URI uri = outboundRequest.getURI();
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    String path = uri.getPath();
    if (!refresh) {
        String appCookie = endpointCookieMap.get(endpoint);
        if (appCookie != null) {
            return appCookie;
        }
    }

    clearAppCookie(endpoint);

    DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);

    String hadoopAuthCookie = null;
    HttpResponse httpResponse = null;
    try {
        HttpHost httpHost = new HttpHost(host, port, scheme);
        HttpRequest httpRequest = new HttpOptions(path);
        httpResponse = client.execute(httpHost, httpRequest);
        Header[] headers = httpResponse.getHeaders(SET_COOKIE);
        hadoopAuthCookie = getHadoopAuthCookieValue(headers);
        if (hadoopAuthCookie == null) {
            LOG.error("SPNego authentication failed, can not get hadoop.auth cookie for URL: " + endpoint);
            throw new IOException("SPNego authentication failed, can not get hadoop.auth cookie");
        }
    } finally {
        if (httpResponse != null) {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                entity.getContent().close();
            }
        }

    }

    hadoopAuthCookie = HADOOP_AUTH_EQ + quote(hadoopAuthCookie);
    setAppCookie(endpoint, hadoopAuthCookie);
    if (LOG.isInfoEnabled()) {
        LOG.info("Successful SPNego authentication to URL:" + uri.toString());
    }
    return hadoopAuthCookie;
}

From source file:com.cheddargetter.client.service.CheddarGetterPaymentService.java

public void afterPropertiesSet() throws Exception {
    context = newInstance(Customers.class, Plans.class, Error.class, Success.class);

    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager();
    connManager.setMaxTotal(25);/*from   w  w w  .ja va2  s.c  o  m*/
    DefaultHttpClient httpClient = new DefaultHttpClient(connManager);
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(getHost().getHostName(), getHost().getPort()),
            new UsernamePasswordCredentials(getUserName(), getPassword()));
    this.httpClient = httpClient;
}

From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java

/**
 * Makes a request after setting the user agent and verifies that the session cookie is NOT set.
 *//*  ww  w  . j  ava 2s  . c o  m*/
private void testCookieNotSetForKnownStateLessClients(final String userAgent) throws Exception {
    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + "content/";
    URI uri = new URI(url);

    Header header = new BasicHeader("User-Agent", userAgent + "/1.6"); // user agent plus some version

    DefaultHttpClient httpClient = new DefaultHttpClient();

    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet getMethod = new HttpGet(url);
    getMethod.addHeader(header);
    assertThat(executeAndRelease(httpClient, getMethod, localcontext), equalTo(200));

    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    assertThat("Session Cookie should not be set for user agent: " + userAgent, sessionCookie, nullValue());
}

From source file:org.apache.hadoop.gateway.hive.HiveHttpClientDispatch.java

protected HttpResponse executeKerberosDispatch(HttpUriRequest outboundRequest, DefaultHttpClient client)
        throws IOException, ClientProtocolException {
    //DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);// w  w w . j  a v a 2  s .  co  m
    return client.execute(outboundRequest);
}

From source file:org.squale.squalerest.client.SqualeRestHttpClient.java

/**
 * This method executes the search//www .  j  ava 2s. c  om
 * 
 * @param path The query
 * @param xstream The xstream processor
 * @return The object result of the query
 * @throws SqualeRestException Exception occurs during the serach
 */
private Object execute(String path, XStream xstream) throws SqualeRestException {
    Object objectToReturn = null;
    DefaultHttpClient httpclient = null;
    try {
        httpclient = new DefaultHttpClient();

        // Create credentials
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
        httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

        // Define the host
        HttpHost targetHost = new HttpHost(host, port);

        // Define the get method
        HttpGet httpget = new HttpGet(path);

        // Execute the request
        HttpResponse response = httpclient.execute(targetHost, httpget);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream is = null;
                try {
                    // Transform the xml stream into java object
                    is = entity.getContent();
                    objectToReturn = xstream.fromXML(is);
                } finally {
                    // In all case close the input stream
                    if (is != null) {
                        is.close();
                    }
                }
            }
        } else {
            throw new SqualeRestException(response.getStatusLine().getStatusCode() + " : "
                    + response.getStatusLine().getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        throw new SqualeRestException(e);
    } catch (IOException e) {
        throw new SqualeRestException(e);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return objectToReturn;
}

From source file:org.apache.olingo.client.core.http.ProxyWrappingHttpClientFactory.java

@Override
public HttpClient create(final HttpMethod method, final URI uri) {
    // Use wrapped factory to obtain an httpclient instance for given method and uri
    final DefaultHttpClient httpclient = wrapped.create(method, uri);

    final HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());

    // Sets usage of HTTP proxy
    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);

    // Sets proxy authentication, if credentials were provided
    if (proxyUsername != null && proxyPassword != null) {
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost),
                new UsernamePasswordCredentials(proxyUsername, proxyPassword));
    }//from w  ww . ja v a2 s .  c o  m

    return httpclient;
}

From source file:net.homelinux.penecoptero.android.citybikes.app.RESTHelper.java

private DefaultHttpClient setCredentials(DefaultHttpClient httpclient, String url)
        throws HttpException, IOException {
    HttpHost targetHost = new HttpHost(url);
    final UsernamePasswordCredentials access = new UsernamePasswordCredentials(USERNAME, PASSWORD);

    httpclient.getCredentialsProvider()
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), access);

    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override/*from   ww w . j  a v  a  2s.c om*/
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (authState.getAuthScheme() == null) {
                authState.setAuthScheme(new BasicScheme());
                authState.setCredentials(access);
            }
        }
    }, 0);
    return httpclient;
}

From source file:org.sonatype.nexus.error.reporting.NexusPRConnectorTest.java

@Test
public void testProxyReconfigure() {
    final String host = "host";
    final int port = 1234;

    when(proxySettings.isEnabled()).thenReturn(true);
    when(proxySettings.getHostname()).thenReturn(host);
    when(proxySettings.getPort()).thenReturn(port);

    DefaultHttpClient client = (DefaultHttpClient) underTest.client();
    HttpParams params = client.getParams();

    assertThat(ConnRouteParams.getDefaultProxy(params), notNullValue());
    assertThat(params.getParameter(AuthPNames.PROXY_AUTH_PREF), nullValue());

    assertThat(client.getCredentialsProvider().getCredentials(new AuthScope(host, port)), nullValue());

    when(proxySettings.getProxyAuthentication()).thenReturn(proxyAuth);
    when(proxyAuth.getUsername()).thenReturn("user");
    when(proxyAuth.getPassword()).thenReturn("pass");

    final DefaultHttpClient reconfigured = (DefaultHttpClient) underTest.client();
    params = reconfigured.getParams();//from w  ww  . java2 s  .c  om

    assertThat(reconfigured, equalTo(client));

    assertThat(ConnRouteParams.getDefaultProxy(params), notNullValue());
    assertThat(params.getParameter(AuthPNames.PROXY_AUTH_PREF), notNullValue());

    assertThat(reconfigured.getCredentialsProvider().getCredentials(new AuthScope(host, port)), notNullValue());
}

From source file:org.sonatype.nexus.error.reporting.NexusPRConnector.java

private static void configureAuthentication(final DefaultHttpClient httpClient, final String proxyHost,
        final int proxyPort, final RemoteAuthenticationSettings ras) {
    if (ras != null) {
        List<String> authorisationPreference = new ArrayList<String>(2);
        authorisationPreference.add(AuthPolicy.DIGEST);
        authorisationPreference.add(AuthPolicy.BASIC);

        Credentials credentials = null;//  w ww  .j av  a2  s  .  c  om

        if (ras instanceof NtlmRemoteAuthenticationSettings) {
            final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras;

            // Using NTLM auth, adding it as first in policies
            authorisationPreference.add(0, AuthPolicy.NTLM);

            credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(),
                    nras.getNtlmDomain());

        } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) {
            UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras;

            credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword());
        }

        if (credentials != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    credentials);
        }

        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authorisationPreference);
    }
}