Java Code Examples for org.apache.http.impl.client.HttpClientBuilder#addInterceptorLast()

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#addInterceptorLast() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DriveSession.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Drive connect(final Proxy proxy, final HostKeyCallback callback, final LoginCallback prompt) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(configuration.build(), host.getProtocol())
        .withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    configuration.addInterceptorLast(new RateLimitingHttpRequestInterceptor(new DefaultHttpRateLimiter(
        PreferencesFactory.get().getInteger("googledrive.limit.requests.second")
    )));
    this.transport = new ApacheHttpTransport(configuration.build());
    final UseragentProvider ua = new PreferencesUseragentProvider();
    return new Drive.Builder(transport, new JacksonFactory(), new UserAgentHttpRequestInitializer(ua))
        .setApplicationName(ua.get())
        .build();
}
 
Example 2
Source File: GoogleStorageSession.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Storage connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(configuration.build(), host.getProtocol())
        .withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    this.transport = new ApacheHttpTransport(configuration.build());
    final UseragentProvider ua = new PreferencesUseragentProvider();
    return new Storage.Builder(transport, new JacksonFactory(), new UserAgentHttpRequestInitializer(ua))
        .setApplicationName(ua.get())
        .build();
}
 
Example 3
Source File: TraceeHttpInterceptorsIT.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testWritesToServerAndParsesResponse() throws IOException {

	HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	httpClientBuilder.addInterceptorLast(new TraceeHttpRequestInterceptor());
	httpClientBuilder.addInterceptorFirst(new TraceeHttpResponseInterceptor());
	CloseableHttpClient httpClient = httpClientBuilder.build();

	HttpGet getMethod = new HttpGet(serverEndpoint);
	Tracee.getBackend().put("before Request", "yip");
	final HttpResponse response = httpClient.execute(getMethod);

	assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_NO_CONTENT));
	assertThat(Tracee.getBackend().get("responseFromServer"), equalTo("yes Sir"));
}
 
Example 4
Source File: GerritRestClient.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

    client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    RequestConfig.Builder requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to connect to remote host
            .setSocketTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to retrieve data from remote host
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);
    client.setDefaultRequestConfig(requestConfig.build());

    CredentialsProvider credentialsProvider = getCredentialsProvider();
    client.setDefaultCredentialsProvider(credentialsProvider);

    if (authData.isLoginAndPasswordAvailable()) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

        BasicScheme basicAuth = new BasicScheme();
        httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
        client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
    }

    client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

    for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
        client = httpClientBuilderExtension.extend(client, authData);
        credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider, authData);
    }

    return client;
}
 
Example 5
Source File: HubicSession.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Client connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(configuration.build(), host.getProtocol())
        .withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    return new Client(configuration.build());
}
 
Example 6
Source File: DropboxSession.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected CustomDbxRawClientV2 connect(final Proxy proxy, final HostKeyCallback callback, final LoginCallback prompt) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(configuration.build(), host.getProtocol())
        .withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    final CloseableHttpClient client = configuration.build();
    return new CustomDbxRawClientV2(DbxRequestConfig.newBuilder(useragent.get())
        .withAutoRetryDisabled()
        .withHttpRequestor(new DropboxCommonsHttpRequestExecutor(client)).build(),
        DbxHost.DEFAULT, null, null);
}
 
Example 7
Source File: StoregateSession.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected StoregateApiClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(builder.build(proxy, this, prompt).addInterceptorLast(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            request.addHeader(HttpHeaders.AUTHORIZATION,
                String.format("Basic %s", Base64.encodeToString(String.format("%s:%s", host.getProtocol().getOAuthClientId(), host.getProtocol().getOAuthClientSecret()).getBytes(StandardCharsets.UTF_8), false)));
        }
    }).build(),
        host).withRedirectUri(CYBERDUCK_REDIRECT_URI.equals(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() :
        Scheme.isURL(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : new HostUrlProvider().withUsername(false).withPath(true).get(
            host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getOAuthRedirectUrl())
    );
    // Force login even if browser session already exists
    authorizationService.withParameter("prompt", "login");
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    configuration.addInterceptorLast(authorizationService);
    final CloseableHttpClient apache = configuration.build();
    final StoregateApiClient client = new StoregateApiClient(apache);
    final int timeout = PreferencesFactory.get().getInteger("connection.timeout.seconds") * 1000;
    client.setConnectTimeout(timeout);
    client.setBasePath(new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(),
        null, host.getHostname(), host.getProtocol().getContext()));
    client.setHttpClient(ClientBuilder.newClient(new ClientConfig()
        .register(new InputStreamProvider())
        .register(MultiPartFeature.class)
        .register(new JSON())
        .register(JacksonFeature.class)
        .connectorProvider(new HttpComponentsProvider(apache))));
    client.setUserAgent(new PreferencesUseragentProvider().get());
    return client;
}
 
Example 8
Source File: B2Session.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public B2ApiClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    configuration.setServiceUnavailableRetryStrategy(retryHandler = new B2ErrorResponseInterceptor(
        this));
    configuration.addInterceptorLast(retryHandler);
    return new B2ApiClient(configuration.build());
}
 
Example 9
Source File: GraphSession.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected OneDriveAPI connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt) {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    authorizationService = new OAuth2RequestInterceptor(configuration.build(), host.getProtocol()) {
        @Override
        public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
            if(request.containsHeader(HttpHeaders.AUTHORIZATION)) {
                super.process(request, context);
            }
        }
    }.withRedirectUri(host.getProtocol().getOAuthRedirectUrl());
    configuration.addInterceptorLast(authorizationService);
    configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
    final RequestExecutor executor = new GraphCommonsHttpRequestExecutor(configuration.build()) {
        @Override
        public void addAuthorizationHeader(final Set<RequestHeader> headers) {
            // Placeholder
            headers.add(new RequestHeader(HttpHeaders.AUTHORIZATION, "Bearer"));
        }
    };
    return new OneDriveAPI() {
        @Override
        public RequestExecutor getExecutor() {
            return executor;
        }

        @Override
        public boolean isBusinessConnection() {
            return false;
        }

        @Override
        public boolean isGraphConnection() {
            if(StringUtils.equals("graph.microsoft.com", host.getHostname())) {
                return true;
            }
            else if(StringUtils.equals("graph.microsoft.de", host.getHostname())) {
                return true;
            }
            return false;
        }

        @Override
        public String getBaseURL() {
            return String.format("%s://%s%s", host.getProtocol().getScheme(), host.getHostname(), host.getProtocol().getContext());
        }

        @Override
        public String getEmailURL() {
            return String.format("%s://%s%s", host.getProtocol().getScheme(), host.getHostname(), "/v1.0/me");
        }
    };
}
 
Example 10
Source File: HttpClientFactory.java    From vividus with Apache License 2.0 4 votes vote down vote up
@Override
public IHttpClient buildHttpClient(HttpClientConfig config)
{
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultHeaders(config.createHeaders());
    if (config.hasCookieStore())
    {
        builder.setDefaultCookieStore(config.getCookieStore());
    }
    if (config.hasCredentials())
    {
        AuthScope authScope = config.hasAuthScope() ? config.getAuthScope()
                : ClientBuilderUtils.DEFAULT_AUTH_SCOPE;
        CredentialsProvider credProvider = ClientBuilderUtils.createCredentialsProvider(authScope,
                config.getCredentials());
        builder.setDefaultCredentialsProvider(credProvider);
    }

    sslContextFactory.getSslContext(SSLConnectionSocketFactory.SSL, !config.isSslCertificateCheckEnabled())
            .ifPresent(builder::setSSLContext);

    if (!config.isSslHostnameVerificationEnabled())
    {
        builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    }
    builder.setConnectionManager(config.getConnectionManager());
    builder.setMaxConnTotal(config.getMaxTotalConnections());
    builder.setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    builder.addInterceptorLast(config.getLastRequestInterceptor());
    builder.addInterceptorLast(config.getLastResponseInterceptor());
    builder.setRedirectStrategy(config.getRedirectStrategy());
    builder.setRetryHandler(config.getHttpRequestRetryHandler());
    Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(config.getConnectionRequestTimeout());
    requestConfigBuilder.setConnectTimeout(config.getConnectTimeout());
    requestConfigBuilder.setCircularRedirectsAllowed(config.isCircularRedirectsAllowed());
    requestConfigBuilder.setSocketTimeout(config.getSocketTimeout());
    Optional.ofNullable(config.getCookieSpec()).ifPresent(requestConfigBuilder::setCookieSpec);
    builder.setDefaultRequestConfig(requestConfigBuilder.build());
    builder.setDefaultSocketConfig(SocketConfig.copy(SocketConfig.DEFAULT)
            .setSoTimeout(config.getSocketTimeout())
            .build());
    builder.setDnsResolver(config.getDnsResolver());

    HttpClient httpClient = new HttpClient();
    httpClient.setCloseableHttpClient(builder.build());
    if (config.hasBaseUrl())
    {
        httpClient.setHttpHost(HttpHost.create(config.getBaseUrl()));
    }
    httpClient.setSkipResponseEntity(config.isSkipResponseEntity());
    return httpClient;
}
 
Example 11
Source File: HttpClient.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
protected void initialzeInternalClient() {

        if (!needsInternalClientInialization) {
            // internal client is already initialized
            return;
        }

        // release any resources if this client was already used
        close();

        // rebuild the client
        HttpClientBuilder httpClientBuilder = HttpClients.custom();

        // Add this interceptor to get the values of all HTTP headers in the request.
        // Some of them are provided by the user while others are generated by Apache HTTP Components.
        httpClientBuilder.addInterceptorLast(new HttpRequestInterceptor() {
            @Override
            public void process( HttpRequest request, HttpContext context ) throws HttpException,
                                                                            IOException {

                Header[] requestHeaders = request.getAllHeaders();
                actualRequestHeaders = new ArrayList<HttpHeader>();
                for (Header header : requestHeaders) {
                    addHeaderToList(actualRequestHeaders, header.getName(), header.getValue());
                }
                if (debugLevel != HttpDebugLevel.NONE) {
                    logHTTPRequest(requestHeaders, request);
                }
            }
        });

        // connect and read timeouts
        httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
                                                               .setConnectTimeout(connectTimeoutSeconds
                                                                                  * 1000)
                                                               .setSocketTimeout(readTimeoutSeconds
                                                                                 * 1000)
                                                               .build());

        // socket buffer size
        if (this.socketBufferSize > 0) {
            httpClientBuilder.setDefaultSocketConfig(SocketConfig.custom()
                                                                 .setRcvBufSize(this.socketBufferSize)
                                                                 .setSndBufSize(this.socketBufferSize)
                                                                 .build());
        }

        // SSL
        if (isOverSsl) {
            setupSSL(httpClientBuilder);
        }

        // setup authentication
        if (!StringUtils.isNullOrEmpty(username)) {
            setupAuthentication(httpClientBuilder);
        }

        // set proxy
        if (AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST != null
            && AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT != null) {

            HttpHost proxy = new HttpHost(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST,
                                          Integer.parseInt(AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT));
            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
            httpClientBuilder.setRoutePlanner(routePlanner);
        }

        // now build the client after we have already set everything needed on the client builder
        httpClient = httpClientBuilder.build();

        // do not come here again until not needed
        needsInternalClientInialization = false;
    }
 
Example 12
Source File: ApacheHttpClientFactory.java    From ibm-cos-sdk-java with Apache License 2.0 4 votes vote down vote up
@Override
public ConnectionManagerAwareHttpClient create(HttpClientSettings settings) {
    final HttpClientBuilder builder = HttpClients.custom();
    // Note that it is important we register the original connection manager with the
    // IdleConnectionReaper as it's required for the successful deregistration of managers
    // from the reaper. See https://github.com/aws/aws-sdk-java/issues/722.
    final HttpClientConnectionManager cm = cmFactory.create(settings);

    builder.setRequestExecutor(new SdkHttpRequestExecutor())
            .setKeepAliveStrategy(buildKeepAliveStrategy(settings))
            .disableRedirectHandling()
            .disableAutomaticRetries()
            .setConnectionManager(ClientConnectionManagerFactory.wrap(cm));

    // By default http client enables Gzip compression. So we disable it
    // here.
    // Apache HTTP client removes Content-Length, Content-Encoding and
    // Content-MD5 headers when Gzip compression is enabled. Currently
    // this doesn't affect S3 or Glacier which exposes these headers.
    //
    if (!(settings.useGzip())) {
        builder.disableContentCompression();
    }

    HttpResponseInterceptor itcp = new CRC32ChecksumResponseInterceptor();
    if (settings.calculateCRC32FromCompressedData()) {
        builder.addInterceptorFirst(itcp);
    } else {
        builder.addInterceptorLast(itcp);
    }

    addProxyConfig(builder, settings);

    final ConnectionManagerAwareHttpClient httpClient = new SdkHttpClient(builder.build(), cm);

    if (settings.useReaper()) {
        IdleConnectionReaper.registerConnectionManager(cm, settings.getMaxIdleConnectionTime());
    }

    return httpClient;
}
 
Example 13
Source File: ElasticSearchTransportFactory.java    From bender with Apache License 2.0 4 votes vote down vote up
private HttpClientBuilder addSigningAuth(HttpClientBuilder cb, UrlSigningAuthConfig auth) {
  return cb.addInterceptorLast(auth.getHttpInterceptor());
}
 
Example 14
Source File: JestClientFactory.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
protected HttpClientBuilder configureHttpClient(HttpClientBuilder builder)
{
    builder.addInterceptorLast(requestInterceptor);
    return builder;
}
 
Example 15
Source File: SSLCertificateLoader.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
private synchronized CloseableHttpClient getHttpClient(final String url) {
	HttpClientBuilder httpClientBuilder = getCommonsDataLoader().getHttpClientBuilder(url);
	httpClientBuilder.addInterceptorLast(getHttpResponseInterceptor());
	return httpClientBuilder.build();
}
 
Example 16
Source File: UserAgentClientBuilderExtension.java    From gerrit-code-review-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public HttpClientBuilder extend(HttpClientBuilder httpClientBuilder, GerritAuthData authData) {
  HttpClientBuilder builder = super.extend(httpClientBuilder, authData);
  httpClientBuilder.addInterceptorLast(new UserAgentHttpRequestInterceptor());
  return builder;
}
 
Example 17
Source File: HttpClientBuilderCustomizer.java    From summerframework with Apache License 2.0 4 votes vote down vote up
public CloseableHttpClient build(HttpClientBuilder builder) {
    builder.addInterceptorLast(grayHttpRequestInterceptor);
    return builder.build();
}