Example usage for org.apache.http.client.protocol HttpClientContext getAuthCache

List of usage examples for org.apache.http.client.protocol HttpClientContext getAuthCache

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext getAuthCache.

Prototype

public AuthCache getAuthCache() 

Source Link

Usage

From source file:com.joyent.http.signature.apache.httpclient.HttpSignatureAuthenticationStrategy.java

@Override
public void authSucceeded(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    Objects.requireNonNull(authhost, "Authentication host must be present");
    Objects.requireNonNull(authScheme, "Authentication scheme must be present");
    Objects.requireNonNull(context, "HTTP context must be present");

    LOG.debug("HTTP Signature authentication succeeded");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    AuthCache authCache = clientContext.getAuthCache();
    if (authCache == null) {
        authCache = new BasicAuthCache();
        clientContext.setAuthCache(authCache);
    }//  w w w . j  av a 2 s.c om
    if (LOG.isDebugEnabled()) {
        LOG.debug("Caching '" + authScheme.getSchemeName() + "' auth scheme for " + authhost);
    }
    authCache.put(authhost, authScheme);
}

From source file:com.joyent.http.signature.apache.httpclient.HttpSignatureAuthenticationStrategy.java

@Override
public void authFailed(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    Objects.requireNonNull(authhost, "Authentication host must be present");
    Objects.requireNonNull(context, "HTTP context must be present");

    LOG.debug("HTTP Signature authentication failed");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    final AuthCache authCache = clientContext.getAuthCache();
    if (authCache != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Clearing cached auth scheme for " + authhost);
        }/*from www. j  a  va2 s  .  c o  m*/
        authCache.remove(authhost);
    }
}

From source file:org.sonatype.spice.zapper.client.hc4.Hc4Client.java

@Override
public State upload(final Payload payload, final Hc4Track track) throws IOException {
    final String url = getRemoteUrl() + payload.getPath().stringValue();
    final HttpPut put = new HttpPut(url);
    if (payload instanceof SegmentPayload) {
        put.setEntity(new ZapperEntity(payload, getParameters().getCodecSelector()
                .selectCodecs(SegmentPayload.class.cast(payload).getSegment().getZFile())));
    } else {//w  w w  .  ja  v a  2 s.  c om
        put.setEntity(new ZapperEntity(payload));
    }
    put.addHeader("X-Zapper-Transfer-ID", payload.getTransferIdentifier().stringValue());
    if (track != null) {
        put.addHeader("X-Zapper-Track-ID", track.getIdentifier().stringValue());
    }
    final HttpClientContext context = new HttpClientContext();
    if (preemptiveCredentialsProvider != null) {
        context.setCredentialsProvider(preemptiveCredentialsProvider);
        context.setAuthCache(new BasicAuthCache());
        context.getAuthCache().put(
                new HttpHost(put.getURI().getHost(), put.getURI().getPort(), put.getURI().getScheme()),
                new BasicScheme());
    }
    final HttpResponse response = httpClient.execute(put, context);
    final StatusLine statusLine = response.getStatusLine();
    EntityUtils.consume(response.getEntity());
    if (!(statusLine.getStatusCode() > 199 && statusLine.getStatusCode() < 299)) {
        throw new IOException(String.format("Unexpected server response: %s %s", statusLine.getStatusCode(),
                statusLine.getReasonPhrase()));
    }
    return State.SUCCESS;
}

From source file:org.elasticsearch.client.RestClientMultipleHostsTests.java

@Before
@SuppressWarnings("unchecked")
public void createRestClient() throws IOException {
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class),
            any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class)))
                    .thenAnswer(new Answer<Future<HttpResponse>>() {
                        @Override
                        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
                            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock
                                    .getArguments()[0];
                            HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest();
                            HttpHost httpHost = requestProducer.getTarget();
                            HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2];
                            assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class));
                            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock
                                    .getArguments()[3];
                            //return the desired status code or exception depending on the path
                            if (request.getURI().getPath().equals("/soe")) {
                                futureCallback.failed(new SocketTimeoutException(httpHost.toString()));
                            } else if (request.getURI().getPath().equals("/coe")) {
                                futureCallback.failed(new ConnectTimeoutException(httpHost.toString()));
                            } else if (request.getURI().getPath().equals("/ioe")) {
                                futureCallback.failed(new IOException(httpHost.toString()));
                            } else {
                                int statusCode = Integer.parseInt(request.getURI().getPath().substring(1));
                                StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1),
                                        statusCode, "");
                                futureCallback.completed(new BasicHttpResponse(statusLine));
                            }//from w ww .  j  a v a2 s. c o  m
                            return null;
                        }
                    });
    int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5);
    httpHosts = new HttpHost[numHosts];
    for (int i = 0; i < numHosts; i++) {
        httpHosts[i] = new HttpHost("localhost", 9200 + i);
    }
    failureListener = new HostsTrackingFailureListener();
    restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener);
}

From source file:org.elasticsearch.client.RestClientSingleHostTests.java

@Before
@SuppressWarnings("unchecked")
public void createRestClient() throws IOException {
    httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class),
            any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class)))
                    .thenAnswer(new Answer<Future<HttpResponse>>() {
                        @Override
                        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
                            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock
                                    .getArguments()[0];
                            HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2];
                            assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class));
                            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock
                                    .getArguments()[3];
                            HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest();
                            //return the desired status code or exception depending on the path
                            if (request.getURI().getPath().equals("/soe")) {
                                futureCallback.failed(new SocketTimeoutException());
                            } else if (request.getURI().getPath().equals("/coe")) {
                                futureCallback.failed(new ConnectTimeoutException());
                            } else {
                                int statusCode = Integer.parseInt(request.getURI().getPath().substring(1));
                                StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1),
                                        statusCode, "");

                                HttpResponse httpResponse = new BasicHttpResponse(statusLine);
                                //return the same body that was sent
                                if (request instanceof HttpEntityEnclosingRequest) {
                                    HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                                    if (entity != null) {
                                        assertTrue(
                                                "the entity is not repeatable, cannot set it to the response directly",
                                                entity.isRepeatable());
                                        httpResponse.setEntity(entity);
                                    }/*from   w  w  w  . j  a va 2 s .c o  m*/
                                }
                                //return the same headers that were sent
                                httpResponse.setHeaders(request.getAllHeaders());
                                futureCallback.completed(httpResponse);
                            }
                            return null;
                        }
                    });

    defaultHeaders = RestClientTestUtil.randomHeaders(getRandom(), "Header-default");
    httpHost = new HttpHost("localhost", 9200);
    failureListener = new HostsTrackingFailureListener();
    restClient = new RestClient(httpClient, 10000, defaultHeaders, new HttpHost[] { httpHost }, null,
            failureListener);
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClientTest.java

@Test
public void sendRequest_withProvidedUsernameAndPassword_setsCredentialsProvider() throws Exception {
    // arrange//from   w  ww .  jav  a2s.c  o m
    CloseableHttpClient closeableHttpClient = anyCloseableHttpClient();
    ConfluenceRestClient confluenceRestClient = new ConfluenceRestClient("http://confluence.com",
            closeableHttpClient, "username", "password");
    HttpGet httpRequest = new HttpGet("http://confluence.com");
    ArgumentCaptor<HttpContext> httpContentArgumentCaptor = ArgumentCaptor.forClass(HttpContext.class);

    // act
    confluenceRestClient.sendRequest(httpRequest);

    // assert
    verify(closeableHttpClient, times(1)).execute(eq(httpRequest), httpContentArgumentCaptor.capture());
    HttpContext httpContext = httpContentArgumentCaptor.getValue();
    HttpClientContext httpClientContext = (HttpClientContext) httpContext;
    HttpHost httpHost = HttpHost.create("http://confluence.com");
    assertThat(httpClientContext.getAuthCache().get(httpHost), not(nullValue()));

    Credentials credentials = httpClientContext.getCredentialsProvider()
            .getCredentials(new AuthScope(httpHost));
    assertThat(credentials.getPassword(), is("password"));
    assertThat(credentials.getUserPrincipal().getName(), is("username"));
}

From source file:de.undercouch.gradle.tasks.download.DownloadAction.java

/**
 * Add authentication information for the given host
 * @param host the host// ww  w  .  j  a  v  a2s . c  om
 * @param credentials the credentials
 * @param authScheme the scheme for preemptive authentication (should be
 * <code>null</code> if adding authentication for a proxy server)
 * @param context the context in which the authentication information
 * should be saved
 */
private void addAuthentication(HttpHost host, Credentials credentials, AuthScheme authScheme,
        HttpClientContext context) {
    AuthCache authCache = context.getAuthCache();
    if (authCache == null) {
        authCache = new BasicAuthCache();
        context.setAuthCache(authCache);
    }

    CredentialsProvider credsProvider = context.getCredentialsProvider();
    if (credsProvider == null) {
        credsProvider = new BasicCredentialsProvider();
        context.setCredentialsProvider(credsProvider);
    }

    credsProvider.setCredentials(new AuthScope(host), credentials);

    if (authScheme != null) {
        authCache.put(host, authScheme);
    }
}

From source file:org.apache.http.client.protocol.RequestAuthCache.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    final AuthCache authCache = clientContext.getAuthCache();
    if (authCache == null) {
        this.log.debug("Auth cache not set in the context");
        return;/* ww  w .j a  va 2  s . co  m*/
    }

    final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
    if (credsProvider == null) {
        this.log.debug("Credentials provider not set in the context");
        return;
    }

    final RouteInfo route = clientContext.getHttpRoute();
    HttpHost target = clientContext.getTargetHost();
    if (target.getPort() < 0) {
        target = new HttpHost(target.getHostName(), route.getTargetHost().getPort(), target.getSchemeName());
    }

    final AuthState targetState = clientContext.getTargetAuthState();
    if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) {
        final AuthScheme authScheme = authCache.get(target);
        if (authScheme != null) {
            doPreemptiveAuth(target, authScheme, targetState, credsProvider);
        }
    }

    final HttpHost proxy = route.getProxyHost();
    final AuthState proxyState = clientContext.getProxyAuthState();
    if (proxy != null && proxyState != null && proxyState.getState() == AuthProtocolState.UNCHALLENGED) {
        final AuthScheme authScheme = authCache.get(proxy);
        if (authScheme != null) {
            doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
        }
    }
}

From source file:org.apache.http.impl.client.AuthenticationStrategyImpl.java

public void authSucceeded(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    Args.notNull(authhost, "Host");
    Args.notNull(authScheme, "Auth scheme");
    Args.notNull(context, "HTTP context");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    if (isCachable(authScheme)) {
        AuthCache authCache = clientContext.getAuthCache();
        if (authCache == null) {
            authCache = new BasicAuthCache();
            clientContext.setAuthCache(authCache);
        }//from  w  w  w  .  jav  a  2s .  co m
        if (this.log.isDebugEnabled()) {
            this.log.debug("Caching '" + authScheme.getSchemeName() + "' auth scheme for " + authhost);
        }
        authCache.put(authhost, authScheme);
    }
}

From source file:org.apache.http.impl.client.AuthenticationStrategyImpl.java

public void authFailed(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    Args.notNull(authhost, "Host");
    Args.notNull(context, "HTTP context");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    final AuthCache authCache = clientContext.getAuthCache();
    if (authCache != null) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("Clearing cached auth scheme for " + authhost);
        }//from   w  ww.ja  va2  s  .  c o  m
        authCache.remove(authhost);
    }
}