Search in sources :

Example 61 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project metron by apache.

the class TaxiiHandler method createContext.

private static HttpClientContext createContext(URL endpoint, String username, String password, int port) {
    HttpClientContext context = null;
    HttpHost target = new HttpHost(endpoint.getHost(), port, endpoint.getProtocol());
    if (username != null && password != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password));
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
        AuthCache authCache = new BasicAuthCache();
        authCache.put(target, new BasicScheme());
        // Add AuthCache to the execution context
        context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
    } else {
        context = null;
    }
    return context;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 62 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project flow by vaadin.

the class DefaultFileDownloader method execute.

private CloseableHttpResponse execute(URI requestUri) throws IOException {
    CloseableHttpResponse response;
    ProxyConfig.Proxy proxy = proxyConfig.getProxyForUrl(requestUri.toString());
    if (proxy != null) {
        getLogger().info("Downloading via proxy {}", proxy.toString());
        return executeViaProxy(proxy, requestUri);
    } else {
        getLogger().info("No proxy was configured, downloading directly");
        if (userName != null && !userName.isEmpty() && password != null && !password.isEmpty()) {
            getLogger().info("Using credentials ({})", userName);
            // Auth target host
            URL aURL = requestUri.toURL();
            HttpClientContext localContext = makeLocalContext(aURL);
            CredentialsProvider credentialsProvider = makeCredentialsProvider(aURL.getHost(), aURL.getPort(), userName, password);
            response = buildHttpClient(credentialsProvider).execute(new HttpGet(requestUri), localContext);
        } else {
            response = buildHttpClient(null).execute(new HttpGet(requestUri));
        }
    }
    return response;
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) URL(java.net.URL)

Example 63 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project flow by vaadin.

the class DefaultFileDownloader method makeLocalContext.

private HttpClientContext makeLocalContext(URL requestUrl) {
    // Auth target host
    HttpHost target = new HttpHost(requestUrl.getHost(), requestUrl.getPort(), requestUrl.getProtocol());
    // 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
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return localContext;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) HttpHost(org.apache.http.HttpHost) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache)

Example 64 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project stocator by SparkTC.

the class SwiftConnectionManager method getRetryHandler.

/**
 * Creates custom retry handler to be used if HTTP exception happens
 *
 * @return retry handler
 */
private HttpRequestRetryHandler getRetryHandler() {
    final 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 than threshold. 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;
            }
            final HttpClientContext clientContext = HttpClientContext.adapt(context);
            final 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 65 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project pentaho-kettle by pentaho.

the class SlaveServerTest method testSendExportOk.

@Test
public void testSendExportOk() throws Exception {
    slaveServer.setUsername("uname");
    slaveServer.setPassword("passw");
    slaveServer.setHostname("hname");
    slaveServer.setPort("1111");
    HttpPost httpPostMock = mock(HttpPost.class);
    URI uriMock = new URI("fake");
    final String responseContent = "baah";
    when(httpPostMock.getURI()).thenReturn(uriMock);
    doReturn(uriMock).when(httpPostMock).getURI();
    HttpClient client = mock(HttpClient.class);
    when(client.execute(any(), any(HttpContext.class))).then(new Answer<HttpResponse>() {

        @Override
        public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
            HttpClientContext context = invocation.getArgumentAt(1, HttpClientContext.class);
            Credentials cred = context.getCredentialsProvider().getCredentials(new AuthScope("hname", 1111));
            assertEquals("uname", cred.getUserPrincipal().getName());
            return mockResponse(200, responseContent);
        }
    });
    // override init
    when(slaveServer.getHttpClient()).thenReturn(client);
    when(slaveServer.getResponseBodyAsString(any())).thenCallRealMethod();
    doReturn(httpPostMock).when(slaveServer).buildSendExportMethod(anyString(), anyString(), any(InputStream.class));
    File tempFile;
    tempFile = File.createTempFile("PDI-", "tmp");
    tempFile.deleteOnExit();
    String result = slaveServer.sendExport(tempFile.getAbsolutePath(), null, null);
    assertEquals(responseContent, result);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpContext(org.apache.http.protocol.HttpContext) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) Matchers.anyString(org.mockito.Matchers.anyString) URI(java.net.URI) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) File(java.io.File) Credentials(org.apache.http.auth.Credentials) Test(org.junit.Test)

Aggregations

HttpClientContext (org.apache.http.client.protocol.HttpClientContext)160 HttpGet (org.apache.http.client.methods.HttpGet)56 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)54 IOException (java.io.IOException)48 HttpHost (org.apache.http.HttpHost)47 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)45 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)45 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)39 CredentialsProvider (org.apache.http.client.CredentialsProvider)39 URI (java.net.URI)32 HttpResponse (org.apache.http.HttpResponse)32 BasicScheme (org.apache.http.impl.auth.BasicScheme)32 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)32 AuthScope (org.apache.http.auth.AuthScope)31 AuthCache (org.apache.http.client.AuthCache)29 Test (org.junit.Test)29 HttpEntity (org.apache.http.HttpEntity)22 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)21 HttpClient (org.apache.http.client.HttpClient)18 RequestConfig (org.apache.http.client.config.RequestConfig)17