Example usage for org.apache.http.impl.client HttpClientBuilder addInterceptorFirst

List of usage examples for org.apache.http.impl.client HttpClientBuilder addInterceptorFirst

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder addInterceptorFirst.

Prototype

public final HttpClientBuilder addInterceptorFirst(final HttpRequestInterceptor itcp) 

Source Link

Document

Adds this protocol interceptor to the head of the protocol processing list.

Usage

From source file:com.ibm.og.client.ApacheClient.java

private CloseableHttpClient createClient() {
    final HttpClientBuilder builder = HttpClients.custom();
    if (this.userAgent != null) {
        builder.setUserAgent(this.userAgent);
    }/* w  ww.j a v a  2  s  . c  o  m*/

    // Some authentication implementations add Content-Length or Transfer-Encoding headers as a part
    // of their authentication algorithm; remove them here so that the default interceptors do not
    // throw a ProtocolException
    // @see RequestContent interceptor
    builder.addInterceptorFirst(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            request.removeHeaders(HTTP.TRANSFER_ENCODING);
            request.removeHeaders(HTTP.CONTENT_LEN);
        }
    });

    return builder.setRequestExecutor(new HttpRequestExecutor(this.waitForContinue))
            .setConnectionManager(createConnectionManager())
            // TODO investigate ConnectionConfig, particularly bufferSize and fragmentSizeHint
            // TODO defaultCredentialsProvider and defaultAuthSchemeRegistry for pre/passive auth?
            .setConnectionReuseStrategy(createConnectionReuseStrategy())
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE).disableConnectionState()
            .disableCookieManagement().disableContentCompression().disableAuthCaching()
            .setRetryHandler(new CustomHttpRequestRetryHandler(this.retryCount, this.requestSentRetry))
            .setRedirectStrategy(new CustomRedirectStrategy()).setDefaultRequestConfig(createRequestConfig())
            .evictExpiredConnections()
            .evictIdleConnections(Long.valueOf(this.maxIdleTime), TimeUnit.MILLISECONDS).build();
}

From source file:groovyx.net.http.ApacheHttpBuilder.java

/**
 * Creates a new `HttpBuilder` based on the Apache HTTP client. While it is acceptable to create a builder with this method, it is generally
 * preferred to use one of the `static` `configure(...)` methods.
 *
 * @param config the configuration object
 *//* w  ww  .jav a 2s. c o m*/
public ApacheHttpBuilder(final HttpObjectConfig config) {
    super(config);

    this.proxyInfo = config.getExecution().getProxyInfo();
    this.config = new HttpConfigs.ThreadSafeHttpConfig(config.getChainedConfig());
    this.executor = config.getExecution().getExecutor();
    this.clientConfig = config.getClient();

    final HttpClientBuilder myBuilder = HttpClients.custom();

    final Registry<ConnectionSocketFactory> registry = registry(config);

    if (config.getExecution().getMaxThreads() > 1) {
        final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        cm.setMaxTotal(config.getExecution().getMaxThreads());
        cm.setDefaultMaxPerRoute(config.getExecution().getMaxThreads());
        myBuilder.setConnectionManager(cm);
    } else {
        final BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(registry);
        myBuilder.setConnectionManager(cm);
    }

    final SSLContext sslContext = config.getExecution().getSslContext();
    if (sslContext != null) {
        myBuilder.setSSLContext(sslContext);
        myBuilder.setSSLSocketFactory(
                new SSLConnectionSocketFactory(sslContext, config.getExecution().getHostnameVerifier()));
    }

    myBuilder.addInterceptorFirst((HttpResponseInterceptor) (response, context) -> {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    final Consumer<Object> clientCustomizer = clientConfig.getClientCustomizer();
    if (clientCustomizer != null) {
        clientCustomizer.accept(myBuilder);
    }

    this.client = myBuilder.build();
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

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

    OkHttpClient c = new OkHttpClient();
    c.setFollowRedirects(true);/*  w  w  w.  j a v a  2 s.  c o m*/
    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    c.setCookieHandler(cookieManager);

    c.setConnectTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setReadTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setWriteTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    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;
}

From source file:com.cognitivemedicine.nifi.http.PostAdvancedHTTP.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final boolean sendAsFlowFile = context.getProperty(SEND_AS_FLOWFILE).asBoolean();
    final int compressionLevel = context.getProperty(COMPRESSION_LEVEL).asInteger();
    final String userAgent = context.getProperty(USER_AGENT).getValue();

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(
            context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setConnectTimeout(
            context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setRedirectsEnabled(false);
    requestConfigBuilder//from   www. ja  v  a2 s. c o m
            .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    final RequestConfig requestConfig = requestConfigBuilder.build();

    final StreamThrottler throttler = throttlerRef.get();
    final ProcessorLog logger = getLogger();

    final Double maxBatchBytes = context.getProperty(MAX_BATCH_SIZE).asDataSize(DataUnit.B);
    String lastUrl = null;
    long bytesToSend = 0L;

    final List<FlowFile> toSend = new ArrayList<>();
    DestinationAccepts destinationAccepts = null;
    CloseableHttpClient client = null;
    final String transactionId = UUID.randomUUID().toString();

    final ObjectHolder<String> dnHolder = new ObjectHolder<>("none");
    while (true) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            break;
        }

        final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue();
        try {
            new java.net.URL(url);
        } catch (final MalformedURLException e) {
            logger.error(
                    "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure",
                    new Object[] { flowFile, url });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            continue;
        }

        // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles
        if (lastUrl != null && !lastUrl.equals(url)) {
            session.transfer(flowFile);
            break;
        }

        lastUrl = url;
        toSend.add(flowFile);

        if (client == null || destinationAccepts == null) {
            final Config config = getConfig(url, context);
            final HttpClientConnectionManager conMan = config.getConnectionManager();

            final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            clientBuilder.setConnectionManager(conMan);
            clientBuilder.setUserAgent(userAgent);
            clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
                @Override
                public void process(final HttpResponse response, final HttpContext httpContext)
                        throws HttpException, IOException {
                    HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
                    ManagedHttpClientConnection conn = coreContext
                            .getConnection(ManagedHttpClientConnection.class);
                    if (!conn.isOpen()) {
                        return;
                    }

                    SSLSession sslSession = conn.getSSLSession();

                    if (sslSession != null) {
                        final X509Certificate[] certChain = sslSession.getPeerCertificateChain();
                        if (certChain == null || certChain.length == 0) {
                            throw new SSLPeerUnverifiedException("No certificates found");
                        }

                        final X509Certificate cert = certChain[0];
                        dnHolder.set(cert.getSubjectDN().getName().trim());
                    }
                }
            });

            clientBuilder.disableAutomaticRetries();
            clientBuilder.disableContentCompression();

            final String username = context.getProperty(USERNAME).getValue();
            final String password = context.getProperty(PASSWORD).getValue();
            // set the credentials if appropriate
            if (username != null) {
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                if (password == null) {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username));
                } else {
                    credentialsProvider.setCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(username, password));
                }
                ;
                clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
            client = clientBuilder.build();

            // determine whether or not destination accepts flowfile/gzip
            destinationAccepts = config.getDestinationAccepts();
            if (destinationAccepts == null) {
                try {
                    if (sendAsFlowFile) {
                        destinationAccepts = getDestinationAcceptance(client, url, getLogger(), transactionId);
                    } else {
                        destinationAccepts = new DestinationAccepts(false, false, false, false, null);
                    }

                    config.setDestinationAccepts(destinationAccepts);
                } catch (IOException e) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                    logger.error(
                            "Unable to communicate with destination {} to determine whether or not it can accept flowfiles/gzip; routing {} to failure due to {}",
                            new Object[] { url, flowFile, e });
                    context.yield();
                    return;
                }
            }
        }

        // if we are not sending as flowfile, or if the destination doesn't accept V3 or V2 (streaming) format,
        // then only use a single FlowFile
        if (!sendAsFlowFile
                || (!destinationAccepts.isFlowFileV3Accepted() && !destinationAccepts.isFlowFileV2Accepted())) {
            break;
        }

        bytesToSend += flowFile.getSize();
        if (bytesToSend > maxBatchBytes.longValue()) {
            break;
        }
    }

    if (toSend.isEmpty()) {
        return;
    }

    final String url = lastUrl;
    final HttpPost post = new HttpPost(url);
    final List<FlowFile> flowFileList = toSend;
    final DestinationAccepts accepts = destinationAccepts;
    final boolean isDestinationLegacyNiFi = accepts.getProtocolVersion() == null;

    final EntityTemplate entity = new EntityTemplate(new ContentProducer() {
        @Override
        public void writeTo(final OutputStream rawOut) throws IOException {
            final OutputStream throttled = (throttler == null) ? rawOut
                    : throttler.newThrottledOutputStream(rawOut);
            OutputStream wrappedOut = new BufferedOutputStream(throttled);
            if (compressionLevel > 0 && accepts.isGzipAccepted()) {
                wrappedOut = new GZIPOutputStream(wrappedOut, compressionLevel);
            }

            try (final OutputStream out = wrappedOut) {
                for (final FlowFile flowFile : flowFileList) {
                    session.read(flowFile, new InputStreamCallback() {
                        @Override
                        public void process(final InputStream rawIn) throws IOException {
                            try (final InputStream in = new BufferedInputStream(rawIn)) {

                                FlowFilePackager packager = null;
                                if (!sendAsFlowFile) {
                                    packager = null;
                                } else if (accepts.isFlowFileV3Accepted()) {
                                    packager = new FlowFilePackagerV3();
                                } else if (accepts.isFlowFileV2Accepted()) {
                                    packager = new FlowFilePackagerV2();
                                } else if (accepts.isFlowFileV1Accepted()) {
                                    packager = new FlowFilePackagerV1();
                                }

                                // if none of the above conditions is met, we should never get here, because
                                // we will have already verified that at least 1 of the FlowFile packaging
                                // formats is acceptable if sending as FlowFile.
                                if (packager == null) {
                                    StreamUtils.copy(in, out);
                                } else {
                                    final Map<String, String> flowFileAttributes;
                                    if (isDestinationLegacyNiFi) {
                                        // Old versions of NiFi expect nf.file.name and nf.file.path to indicate filename & path;
                                        // in order to maintain backward compatibility, we copy the filename & path to those attribute keys.
                                        flowFileAttributes = new HashMap<>(flowFile.getAttributes());
                                        flowFileAttributes.put("nf.file.name",
                                                flowFile.getAttribute(CoreAttributes.FILENAME.key()));
                                        flowFileAttributes.put("nf.file.path",
                                                flowFile.getAttribute(CoreAttributes.PATH.key()));
                                    } else {
                                        flowFileAttributes = flowFile.getAttributes();
                                    }

                                    packager.packageFlowFile(in, out, flowFileAttributes, flowFile.getSize());
                                }
                            }
                        }
                    });
                }

                out.flush();
            }
        }
    });

    entity.setChunked(context.getProperty(CHUNKED_ENCODING).asBoolean());
    post.setEntity(entity);
    post.setConfig(requestConfig);

    final String contentType;
    if (sendAsFlowFile) {
        if (accepts.isFlowFileV3Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V3;
        } else if (accepts.isFlowFileV2Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V2;
        } else if (accepts.isFlowFileV1Accepted()) {
            contentType = APPLICATION_FLOW_FILE_V1;
        } else {
            logger.error(
                    "Cannot send data to {} because the destination does not accept FlowFiles and this processor is configured to deliver FlowFiles; rolling back session",
                    new Object[] { url });
            session.rollback();
            context.yield();
            return;
        }
    } else {
        final String attributeValue = toSend.get(0).getAttribute(CoreAttributes.MIME_TYPE.key());
        contentType = (attributeValue == null) ? DEFAULT_CONTENT_TYPE : attributeValue;
    }

    final String attributeHeaderRegex = context.getProperty(ATTRIBUTES_AS_HEADERS_REGEX).getValue();
    if (attributeHeaderRegex != null && !sendAsFlowFile && flowFileList.size() == 1) {
        final Pattern pattern = Pattern.compile(attributeHeaderRegex);

        final Map<String, String> attributes = flowFileList.get(0).getAttributes();
        for (final Map.Entry<String, String> entry : attributes.entrySet()) {
            final String key = entry.getKey();
            if (pattern.matcher(key).matches()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    post.setHeader(CONTENT_TYPE, contentType);
    post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true");
    post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION);
    post.setHeader(TRANSACTION_ID_HEADER, transactionId);
    if (compressionLevel > 0 && accepts.isGzipAccepted()) {
        post.setHeader(GZIPPED_HEADER, "true");
    }

    // Do the actual POST
    final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles";

    final String uploadDataRate;
    final long uploadMillis;
    String responseContent;

    CloseableHttpResponse response = null;
    try {
        final StopWatch stopWatch = new StopWatch(true);
        response = client.execute(post);
        responseContent = EntityUtils.toString(response.getEntity());
        stopWatch.stop();
        uploadDataRate = stopWatch.calculateDataRate(bytesToSend);
        uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS);
    } catch (final IOException e) {
        logger.error("Failed to Post {} due to {}; transferring to failure",
                new Object[] { flowFileDescription, e });
        context.yield();
        for (FlowFile flowFile : toSend) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
        return;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e });
            }
        }
    }

    // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent
    // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us
    // from posting to some other webservice and then attempting to delete some resource to which
    // we are redirected
    final int responseCode = response.getStatusLine().getStatusCode();
    final String responseReason = response.getStatusLine().getReasonPhrase();
    String holdUri = null;
    if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
        final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME);
        if (locationUriHeader != null) {
            if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) {
                final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME);
                if (holdUriHeader != null) {
                    holdUri = holdUriHeader.getValue();
                }
            }
        }

        if (holdUri == null) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }

    if (holdUri == null) {
        if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: response code was {}:{}; will yield processing, since the destination is temporarily unavailable",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            context.yield();
            return;
        }

        if (responseCode >= 300) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error("Failed to Post {} to {}: response code was {}:{}",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }

        logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription,
                url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate });

        for (FlowFile flowFile : toSend) {

            flowFile = this.setHttpPostResponse(context, session, responseContent, flowFile);

            session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis,
                    true);
            session.transfer(flowFile, REL_SUCCESS);
        }

        return;
    }

    //
    // the response indicated a Hold URI; delete the Hold.
    //
    // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have
    // changed over the past, so we have to take into account a few different possibilities.
    String fullHoldUri = holdUri;
    if (holdUri.startsWith("/contentListener")) {
        // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener,
        // as this really indicates that it should be whatever we posted to -- if posting directly to the
        // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may
        // be posting to some other URL.
        fullHoldUri = url + holdUri.substring(16);
    } else if (holdUri.startsWith("/")) {
        // URL indicates the full path but not hostname or port; use the same hostname & port that we posted
        // to but use the full path indicated by the response.
        int firstSlash = url.indexOf("/", 8);
        if (firstSlash < 0) {
            firstSlash = url.length();
        }
        final String beforeSlash = url.substring(0, firstSlash);
        fullHoldUri = beforeSlash + holdUri;
    } else if (!holdUri.startsWith("http")) {
        // Absolute URL
        fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri;
    }

    final HttpDelete delete = new HttpDelete(fullHoldUri);
    delete.setHeader(TRANSACTION_ID_HEADER, transactionId);

    while (true) {
        try {
            final HttpResponse holdResponse = client.execute(delete);
            responseContent = EntityUtils.toString(holdResponse.getEntity());
            final int holdStatusCode = holdResponse.getStatusLine().getStatusCode();
            final String holdReason = holdResponse.getStatusLine().getReasonPhrase();
            if (holdStatusCode >= 300) {
                logger.error(
                        "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure",
                        new Object[] { flowFileDescription, holdStatusCode, holdReason });

                for (FlowFile flowFile : toSend) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                }
                return;
            }

            logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}",
                    new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate });

            for (FlowFile flowFile : toSend) {
                flowFile = this.setHttpPostResponse(context, session, responseContent, flowFile);
                session.getProvenanceReporter().send(flowFile, url);
                session.transfer(flowFile, REL_SUCCESS);
            }
            return;
        } catch (final IOException e) {
            logger.warn("Failed to delete Hold that destination placed on {} due to {}",
                    new Object[] { flowFileDescription, e });
        }

        if (!isScheduled()) {
            context.yield();
            logger.warn(
                    "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure",
                    new Object[] { flowFileDescription });
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }
}

From source file:com.buffalokiwi.api.APIHttpClient.java

/**
 * Create a new HttpClient instance to use
 * @return/*  www.  j a v a  2 s.co m*/
 * @throws IllegalArgumentException
 * @throws APIException If there is a problem creating the client or strategy
 */
@Override
public CloseableHttpClient createNewClient() throws IllegalArgumentException, APIException {
    //..Build the client
    final HttpClientBuilder builder = HttpClients.custom()
            //..Set the request configuration
            .setDefaultRequestConfig(createRequestConfig())

            //..Set the client connection manager
            .setConnectionManager(POOL)

            //..Set the user agent
            .setUserAgent(getUserAgent())

            //..Enable support for things like 301/302 redirects
            .setRedirectStrategy(createRedirectAndRobotsStrategy())

            //..Keep the connection alive for some time
            .setKeepAliveStrategy(createConnectionKeepAliveStrategy())

            //..Add the user agent intercept for setting the user agent
            //..Don't know if this is still necessary
            .addInterceptorFirst(createUserAgentInterceptor())

            .setMaxConnTotal(DEFAULT_MAX_TOTAL).setMaxConnPerRoute(DEFAULT_MAX_PER_ROUTE)

            //..Add a few headers for what types of encoding to accept, etc.
            .addInterceptorFirst(createAcceptInterceptor());
    //..End builder chain 

    //..Check for gzip 
    if (allowgzip) {
        //..Add gzip interceptor
        builder.addInterceptorFirst(createGzipResponseInterceptor());
    }

    return getBuiltClient(builder);
}

From source file:org.rundeck.api.ApiCall.java

/**
 * Instantiate a new {@link HttpClient} instance, configured to accept all SSL certificates
 *
 * @return an {@link HttpClient} instance - won't be null
 *///  w  w  w  .j  a va 2s . c  o  m
private CloseableHttpClient instantiateHttpClient() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().useSystemProperties();

    // configure user-agent
    httpClientBuilder.setUserAgent("Rundeck API Java Client " + client.getApiVersion());

    if (client.isSslHostnameVerifyAllowAll()) {
        httpClientBuilder.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    if (client.isSslCertificateTrustAllowSelfSigned()) {
        // configure SSL
        try {
            httpClientBuilder.setSslcontext(
                    new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
        } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

    }
    if (client.isSystemProxyEnabled()) {
        // configure proxy (use system env : http.proxyHost / http.proxyPort)
        httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
    }
    // in case of token-based authentication, add the correct HTTP header to all requests via an interceptor
    httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {

        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            if (client.getToken() != null) {
                request.addHeader(AUTH_TOKEN_HEADER, client.getToken());
                //System.out.println("httpClient adding token header");
            } else if (client.getSessionID() != null) {
                request.addHeader(COOKIE_HEADER, "JSESSIONID=" + client.getSessionID());
                //System.out.println("httpClient adding session header, sessionID="+client.getSessionID());
            }
        }
    });

    return httpClientBuilder.build();
}

From source file:com.microsoft.windowsazure.core.pipeline.apache.ApacheConfigSettings.java

/**
 * Update the given {@link HttpClientBuilder} object with the appropriate
 * settings from configuration.//w w w  .j  a v  a 2  s .  c o m
 * 
 * @param httpClientBuilder
 *            The object to update.
 * @return The updates httpClientBuilder
 */
public HttpClientBuilder applyConfig(HttpClientBuilder httpClientBuilder) {
    if (properties
            .containsKey(profile + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY)) {
        httpClientBuilder.setSSLSocketFactory((LayeredConnectionSocketFactory) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_SSL_CONNECTION_SOCKET_FACTORY));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER)) {
        httpClientBuilder.setConnectionManager((HttpClientConnectionManager) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_CONNECTION_MANAGER));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_PROXY_URI)) {
        httpClientBuilder.setProxy(new HttpHost(
                (String) properties.get(profile + ApacheConfigurationProperties.PROPERTY_PROXY_URI)));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER)) {
        httpClientBuilder.setRetryHandler((HttpRequestRetryHandler) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_RETRY_HANDLER));
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER)) {
        return (HttpClientBuilder) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_HTTP_CLIENT_BUILDER);
    }

    if (properties.containsKey(profile + ApacheConfigurationProperties.PROPERTY_REDIRECT_STRATEGY)) {
        httpClientBuilder.setRedirectStrategy((DefaultRedirectStrategy) properties
                .get(profile + ApacheConfigurationProperties.PROPERTY_REDIRECT_STRATEGY));

        // Currently the redirect strategy, due to what seems to be a bug,
        // fails for post requests since it tries do double
        // add the content-length header. This workaround makes sure this header is always
        // removed before it is actually processed by apache
        httpClientBuilder.addInterceptorFirst(new HttpHeaderRemovalFilter());
    }

    if (properties.containsKey("AuthFilter")) {
        @SuppressWarnings("unchecked")
        ServiceRequestFilter filter = (ServiceRequestFilter) properties.get("AuthFilter");
        httpClientBuilder.addInterceptorFirst(new FilterInterceptor(filter));
    }

    if (properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_HOST)
            && properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_PORT)) {
        String proxyHost = (String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_HOST);
        int proxyPort = Integer
                .parseInt((String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_PORT));
        HttpHost proxy;
        if (properties.containsKey(profile + Configuration.PROPERTY_HTTP_PROXY_SCHEME)) {
            proxy = new HttpHost(proxyHost, proxyPort,
                    (String) properties.get(profile + Configuration.PROPERTY_HTTP_PROXY_SCHEME));
        } else {
            proxy = new HttpHost(proxyHost, proxyPort);
        }
        httpClientBuilder.setProxy(proxy);
    }

    return httpClientBuilder;
}