Search in sources :

Example 36 with HttpContext

use of org.apache.http.protocol.HttpContext in project service-proxy by membrane.

the class AssertUtils method getAuthenticatingHttpClient.

private static HttpClient getAuthenticatingHttpClient(String host, int port, String user, String pass) {
    Credentials defaultcreds = new UsernamePasswordCredentials(user, pass);
    BasicCredentialsProvider bcp = new BasicCredentialsProvider();
    bcp.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds);
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

        public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.update(new BasicScheme(), creds);
                }
            }
        }
    };
    HttpClient hc = HttpClientBuilder.create().setDefaultCookieStore(new BasicCookieStore()).setDefaultCredentialsProvider(bcp).addInterceptorFirst(preemptiveAuth).build();
    return hc;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpContext(org.apache.http.protocol.HttpContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) AuthState(org.apache.http.auth.AuthState) HttpHost(org.apache.http.HttpHost) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 37 with HttpContext

use of org.apache.http.protocol.HttpContext in project docker-java-api by amihaiemil.

the class UnixHttpClientTestCase method executesRequestWithHostHandlerAndContext.

/**
 * UnixHttpClient can execute the HttpRequest with the given host,
 * response handler and context.
 * @throws IOException If something goes wrong.
 */
@Test
public void executesRequestWithHostHandlerAndContext() throws IOException {
    final HttpHost host = new HttpHost("127.0.0.1");
    final HttpRequest req = Mockito.mock(HttpRequest.class);
    final ResponseHandler<String> handler = Mockito.mock(ResponseHandler.class);
    final HttpContext context = Mockito.mock(HttpContext.class);
    final HttpClient decorated = Mockito.mock(HttpClient.class);
    Mockito.when(decorated.execute(host, req, handler, context)).thenReturn("executed");
    final HttpClient unix = new UnixHttpClient(decorated);
    MatcherAssert.assertThat(unix.execute(host, req, handler, context), Matchers.equalTo("executed"));
    Mockito.verify(decorated, Mockito.times(1)).execute(host, req, handler, context);
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpHost(org.apache.http.HttpHost) HttpClient(org.apache.http.client.HttpClient) HttpContext(org.apache.http.protocol.HttpContext) Test(org.junit.Test)

Example 38 with HttpContext

use of org.apache.http.protocol.HttpContext in project stocator by CODAIT.

the class SwiftConnectionManager method getRetryHandler.

/**
 * Creates custom retry handler to be used if HTTP exception happens
 *
 * @return retry handler
 */
private HttpRequestRetryHandler getRetryHandler() {
    HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= connectionConfiguration.getExecutionCount()) {
                // Do not retry if over max retry count
                LOG.debug("Execution count {} is bigger then threashold. Stop", executionCount);
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                LOG.debug("NoHttpResponseException exception. Retry count {}", executionCount);
                return true;
            }
            if (exception instanceof UnknownHostException) {
                LOG.debug("UnknownHostException. Retry count {}", executionCount);
                return true;
            }
            if (exception instanceof ConnectTimeoutException) {
                LOG.debug("ConnectTimeoutException. Retry count {}", executionCount);
                return true;
            }
            if (exception instanceof SocketTimeoutException || exception.getClass() == SocketTimeoutException.class || exception.getClass().isInstance(SocketTimeoutException.class)) {
                // Connection refused
                LOG.debug("socketTimeoutException Retry count {}", executionCount);
                return true;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                LOG.debug("InterruptedIOException Retry count {}", executionCount);
                return true;
            }
            if (exception instanceof SSLException) {
                LOG.debug("SSLException Retry count {}", executionCount);
                return true;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                LOG.debug("HttpEntityEnclosingRequest. Retry count {}", executionCount);
                return true;
            }
            LOG.debug("Retry stopped. Retry count {}", executionCount);
            return false;
        }
    };
    return myRetryHandler;
}
Also used : NoHttpResponseException(org.apache.http.NoHttpResponseException) HttpRequest(org.apache.http.HttpRequest) InterruptedIOException(java.io.InterruptedIOException) UnknownHostException(java.net.UnknownHostException) HttpContext(org.apache.http.protocol.HttpContext) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) SocketTimeoutException(java.net.SocketTimeoutException) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 39 with HttpContext

use of org.apache.http.protocol.HttpContext in project k-9 by k9mail.

the class WebDavStoreTest method createOkResponseWithCookie.

private Answer<HttpResponse> createOkResponseWithCookie() {
    return new Answer<HttpResponse>() {

        @Override
        public HttpResponse answer(InvocationOnMock invocation) {
            HttpContext context = (HttpContext) invocation.getArguments()[1];
            if (context.getAttribute(ClientContext.COOKIE_STORE) != null) {
                BasicCookieStore cookieStore = (BasicCookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
                BasicClientCookie cookie = new BasicClientCookie("cookie", "meLikeCookie");
                cookieStore.addCookie(cookie);
            }
            return OK_200_RESPONSE;
        }
    };
}
Also used : Answer(org.mockito.stubbing.Answer) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpContext(org.apache.http.protocol.HttpContext) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie)

Example 40 with HttpContext

use of org.apache.http.protocol.HttpContext in project seldon-core by SeldonIO.

the class InternalPredictionService method sendFeedbackREST.

public void sendFeedbackREST(String feedback, String serviceName) {
    long timeNow = System.currentTimeMillis();
    URI uri;
    try {
        URIBuilder builder = new URIBuilder().setScheme("http").setHost(serviceName).setPort(appProperties.getEngineContainerPort()).setPath("/api/v0.1/feedback");
        uri = builder.build();
    } catch (URISyntaxException e) {
        throw new SeldonAPIException(SeldonAPIException.ApiExceptionType.APIFE_INVALID_ENDPOINT_URL, "Host: " + serviceName + " port:" + appProperties.getEngineContainerPort());
    }
    StringEntity requestEntity = new StringEntity(feedback, ContentType.APPLICATION_JSON);
    HttpContext context = HttpClientContext.create();
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(requestEntity);
    try {
        if (logger.isDebugEnabled())
            logger.debug("Requesting " + httpPost.getURI().toString());
        CloseableHttpResponse resp = httpClient.execute(httpPost, context);
        try {
            resp.getEntity();
        } finally {
            if (resp != null)
                resp.close();
            if (logger.isDebugEnabled())
                logger.debug("External prediction server took " + (System.currentTimeMillis() - timeNow) + "ms");
        }
    } catch (IOException e) {
        logger.error("Couldn't retrieve prediction from external prediction server - ", e);
        throw new SeldonAPIException(SeldonAPIException.ApiExceptionType.APIFE_MICROSERVICE_ERROR, e.toString());
    } catch (Exception e) {
        logger.error("Couldn't retrieve prediction from external prediction server - ", e);
        throw new SeldonAPIException(SeldonAPIException.ApiExceptionType.APIFE_MICROSERVICE_ERROR, e.toString());
    } finally {
    }
}
Also used : StringEntity(org.apache.http.entity.StringEntity) HttpPost(org.apache.http.client.methods.HttpPost) SeldonAPIException(io.seldon.apife.exception.SeldonAPIException) HttpContext(org.apache.http.protocol.HttpContext) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) SeldonAPIException(io.seldon.apife.exception.SeldonAPIException) URIBuilder(org.apache.http.client.utils.URIBuilder)

Aggregations

HttpContext (org.apache.http.protocol.HttpContext)187 HttpResponse (org.apache.http.HttpResponse)81 IOException (java.io.IOException)74 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)59 HttpRequest (org.apache.http.HttpRequest)57 HttpException (org.apache.http.HttpException)34 HttpGet (org.apache.http.client.methods.HttpGet)31 Test (org.junit.Test)30 HttpHost (org.apache.http.HttpHost)28 HttpPost (org.apache.http.client.methods.HttpPost)28 StringEntity (org.apache.http.entity.StringEntity)23 ArrayList (java.util.ArrayList)22 Header (org.apache.http.Header)22 MessageContext (org.apache.axis2.context.MessageContext)19 NameValuePair (org.apache.http.NameValuePair)18 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)18 ProtocolException (org.apache.http.ProtocolException)17 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)17 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)17 URI (java.net.URI)16