Example usage for org.apache.http.client AuthCache put

List of usage examples for org.apache.http.client AuthCache put

Introduction

In this page you can find the example usage for org.apache.http.client AuthCache put.

Prototype

void put(HttpHost host, AuthScheme authScheme);

Source Link

Usage

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Creates HttpClient Context object based on the internal request.
 *
 * @param request The internal request./* w w w . j av  a 2 s  .com*/
 * @return HttpClient Context object.
 */
protected HttpClientContext createHttpContext(InternalRequest request) {
    HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(
            this.requestConfigBuilder.setExpectContinueEnabled(request.isExpectContinueEnabled()).build());
    if (this.credentialsProvider != null) {
        context.setCredentialsProvider(this.credentialsProvider);
    }
    if (this.config.isProxyPreemptiveAuthenticationEnabled()) {
        AuthCache authCache = new BasicAuthCache();
        authCache.put(this.proxyHttpHost, new BasicScheme());
        context.setAuthCache(authCache);
    }
    return context;
}

From source file:org.pentaho.di.trans.steps.couchdbinput.CouchDbInput.java

@VisibleForTesting
HttpClientContext getHttpClientContext(String hostname, int port) {
    HttpClientContext context;//from w  w  w . j  a  v a  2s  . c  o m
    HttpHost target = new HttpHost(hostname, port, "http");
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);

    // Add AuthCache to the execution context
    context = HttpClientContext.create();
    context.setAuthCache(authCache);
    return context;
}

From source file:org.apache.hadoop.gateway.GatewayMultiFuncTest.java

@Test(timeout = TestUtils.MEDIUM_TIMEOUT)
public void testPostWithContentTypeKnox681() throws Exception {
    LOG_ENTER();//from   w ww. j av  a2 s  .  com

    MockServer mock = new MockServer("REPEAT", true);

    params = new Properties();
    params.put("MOCK_SERVER_PORT", mock.getPort());
    params.put("LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort());

    String topoStr = TestUtils.merge(DAT, "topologies/test-knox678-utf8-chars-topology.xml", params);
    File topoFile = new File(config.getGatewayTopologyDir(), "knox681.xml");
    FileUtils.writeStringToFile(topoFile, topoStr);

    topos.reloadTopologies();

    mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED)
            .content("{\"name\":\"value\"}".getBytes()).contentLength(-1)
            .contentType("application/json; charset=UTF-8").header("Location", gatewayUrl + "/knox681/repeat");

    String uname = "guest";
    String pword = uname + "-password";

    HttpHost targetHost = new HttpHost("localhost", gatewayPort, "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(uname, pword));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPut request = new HttpPut(gatewayUrl + "/knox681/repeat");
    request.addHeader("X-XSRF-Header", "jksdhfkhdsf");
    request.addHeader("Content-Type", "application/json");
    CloseableHttpResponse response = client.execute(request, context);
    assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED));
    assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat"));
    assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/json; charset=UTF-8"));
    String body = new String(IOUtils.toByteArray(response.getEntity().getContent()), Charset.forName("UTF-8"));
    assertThat(body, is("{\"name\":\"value\"}"));
    response.close();
    client.close();

    mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED)
            .content("<test-xml/>".getBytes()).contentType("application/xml; charset=UTF-8")
            .header("Location", gatewayUrl + "/knox681/repeat");

    client = HttpClients.createDefault();
    request = new HttpPut(gatewayUrl + "/knox681/repeat");
    request.addHeader("X-XSRF-Header", "jksdhfkhdsf");
    request.addHeader("Content-Type", "application/xml");
    response = client.execute(request, context);
    assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED));
    assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat"));
    assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/xml; charset=UTF-8"));
    body = new String(IOUtils.toByteArray(response.getEntity().getContent()), Charset.forName("UTF-8"));
    assertThat(the(body), hasXPath("/test-xml"));
    response.close();
    client.close();

    mock.stop();

    LOG_EXIT();
}

From source file:tools.devnull.boteco.client.rest.impl.DefaultRestConfiguration.java

@Override
public RestConfiguration withAuthentication(String user, String password) {
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    CredentialsProvider provider = new BasicCredentialsProvider();

    URI uri = request.getURI();//w  ww .j a  v a2 s. c o  m
    authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth);
    provider.setCredentials(new AuthScope(uri.getHost(), AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(user, password));

    this.context.setCredentialsProvider(provider);
    this.context.setAuthCache(authCache);

    return this;
}

From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java

private void setAuthCache(HttpHost host, BasicHttpContext context) {
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);
    if (context == null && localcontext != null)
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    else//from   www  . ja  v  a 2  s .  co m
        context.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:org.ops4j.pax.web.itest.base.HttpTestClient.java

public HttpResponse getHttpResponse(String path, boolean authenticate, BasicHttpContext basicHttpContext,
        boolean async) throws IOException, KeyManagementException, UnrecoverableKeyException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, AuthenticationException,
        InterruptedException, ExecutionException {
    HttpGet httpget = null;//from  w  w  w.  j a va  2  s.c  o m

    HttpHost targetHost = getHttpHost(path);

    BasicHttpContext localcontext = basicHttpContext == null ? new BasicHttpContext() : basicHttpContext;

    httpget = new HttpGet(path);
    httpget.addHeader("Accept-Language", "en");
    LOG.info("calling remote {} ...", path);
    HttpResponse response = null;
    if (!authenticate && basicHttpContext == null) {
        if (localcontext.getAttribute(ClientContext.AUTH_CACHE) != null) {
            localcontext.removeAttribute(ClientContext.AUTH_CACHE);
        }
        if (!async) {
            response = httpclient.execute(httpget, context);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(httpget, context, null);
            response = future.get();
        }
    } else {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        httpget.addHeader(basicAuth.authenticate(creds, httpget, localcontext));
        httpget.addHeader("Accept-Language", "en-us;q=0.8,en;q=0.5");
        if (!async) {
            response = httpclient.execute(targetHost, httpget, localcontext);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(targetHost, httpget, localcontext, null);
            response = future.get();
        }
    }

    LOG.info("... responded with: {}", response.getStatusLine().getStatusCode());
    return response;
}

From source file:edu.ucsb.nceas.ezid.EZIDService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EZIDService,
 * and so subsequent calls uning this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 * @throws EZIDException if authentication fails for any reason
 *//*from w  ww  . j a  v  a 2  s. c  o m*/
public void login(String username, String password) throws EZIDException {
    try {
        URI serviceUri = new URI(loginServiceEndpoint);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        HttpClientContext localcontext = HttpClientContext.create();
        localcontext.setAuthCache(authCache);
        localcontext.setCredentialsProvider(credsProvider);

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(loginServiceEndpoint);
        body = httpclient.execute(httpget, handler, localcontext);
        String message = new String(body);
        String msg = parseIdentifierResponse(message);
    } catch (URISyntaxException e) {
        throw new EZIDException(e.getMessage());
    } catch (ClientProtocolException e) {
        throw new EZIDException(e.getMessage());
    } catch (IOException e) {
        throw new EZIDException(e.getMessage());
    }
}

From source file:org.jspringbot.keyword.http.HTTPHelper.java

/**
 * Set Basic Authentication//from  w  w  w  . j  av  a  2s  .  co m
 * @param username
 * @param password
 */
public void setBasicAuthentication(String username, String password) {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    client.getCredentialsProvider()
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), credentials);

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    LOG.createAppender().appendBold("Set Basic Authentication:").appendProperty("Username", username)
            .appendProperty("Password", password).log();

    context.setAttribute(ClientContext.AUTH_CACHE, authCache);
}