Example usage for org.apache.http.impl.conn BasicHttpClientConnectionManager setSocketConfig

List of usage examples for org.apache.http.impl.conn BasicHttpClientConnectionManager setSocketConfig

Introduction

In this page you can find the example usage for org.apache.http.impl.conn BasicHttpClientConnectionManager setSocketConfig.

Prototype

public synchronized void setSocketConfig(final SocketConfig socketConfig) 

Source Link

Usage

From source file:com.mirth.connect.client.core.ConnectServiceUtil.java

private static CloseableHttpClient getClient(String[] protocols, String[] cipherSuites) {
    RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create();
    String[] enabledProtocols = MirthSSLUtil.getEnabledHttpsProtocols(protocols);
    String[] enabledCipherSuites = MirthSSLUtil.getEnabledHttpsCipherSuites(cipherSuites);
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            SSLContexts.createSystemDefault(), enabledProtocols, enabledCipherSuites,
            SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
    socketFactoryRegistry.register("https", sslConnectionSocketFactory);

    BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
            socketFactoryRegistry.build());
    httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(TIMEOUT).build());
    return HttpClients.custom().setConnectionManager(httpClientConnectionManager).build();
}

From source file:com.mirth.connect.plugins.httpauth.oauth2.OAuth2Authenticator.java

@Override
public AuthenticationResult authenticate(RequestInfo request) throws Exception {
    OAuth2HttpAuthProperties properties = getReplacedProperties(request);

    CloseableHttpClient client = null;/*from www .j  a v a  2s .  c  o  m*/
    CloseableHttpResponse response = null;

    try {
        // Create and configure the client and context 
        RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory());
        ConnectorPluginProperties pluginProperties = null;
        if (CollectionUtils.isNotEmpty(properties.getConnectorPluginProperties())) {
            pluginProperties = properties.getConnectorPluginProperties().iterator().next();
        }
        provider.getHttpConfiguration().configureSocketFactoryRegistry(pluginProperties, socketFactoryRegistry);
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(SOCKET_TIMEOUT).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        client = clientBuilder.build();

        HttpClientContext context = HttpClientContext.create();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(SOCKET_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        URIBuilder uriBuilder = new URIBuilder(properties.getVerificationURL());

        // Add query parameters
        if (properties.getTokenLocation() == TokenLocation.QUERY) {
            List<String> paramList = request.getQueryParameters().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(paramList)) {
                for (String value : paramList) {
                    uriBuilder.addParameter(properties.getLocationKey(), value);
                }
            }
        }

        // Build the final URI and create a GET request
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // Add headers
        if (properties.getTokenLocation() == TokenLocation.HEADER) {
            List<String> headerList = request.getHeaders().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(headerList)) {
                for (String value : headerList) {
                    httpGet.addHeader(properties.getLocationKey(), value);
                }
            }
        }

        // Execute the request
        response = client.execute(httpGet, context);

        // Determine authentication from the status code 
        if (response.getStatusLine().getStatusCode() < 400) {
            return AuthenticationResult.Success();
        } else {
            return AuthenticationResult.Failure();
        }
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:com.spotify.ffwd.signalfx.SignalFxOutputPlugin.java

@Override
public Module module(final Key<PluginSink> key, final String id) {
    return new OutputPluginModule(id) {
        @Provides//from ww  w .ja va2  s .c  o m
        Supplier<AggregateMetricSender> sender() {
            final Collection<OnSendErrorHandler> handlers = ImmutableList.of(metricError -> {
                log.error(metricError.toString());
            });

            return () -> {
                final SignalFxEndpoint endpoint = new SignalFxEndpoint();
                final HttpDataPointProtobufReceiverFactory dataPoints = new HttpDataPointProtobufReceiverFactory(
                        endpoint).setVersion(2);

                BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
                SocketConfig socketConfigWithSoTimeout = SocketConfig.copy(connectionManager.getSocketConfig())
                        .setSoTimeout(soTimeout).build();
                connectionManager.setSocketConfig(socketConfigWithSoTimeout);
                dataPoints.setHttpClientConnectionManager(connectionManager);

                final EventReceiverFactory events = new HttpEventProtobufReceiverFactory(endpoint);
                final AuthToken auth = new StaticAuthToken(authToken);

                return new AggregateMetricSender(sourceName, dataPoints, events, auth, handlers);
            };
        }

        @Override
        protected void configure() {
            final Key<SignalFxPluginSink> sinkKey = Key.get(SignalFxPluginSink.class,
                    Names.named("signalfxSink"));
            bind(sinkKey).to(SignalFxPluginSink.class).in(Scopes.SINGLETON);
            install(wrapPluginSink(sinkKey, key));
            expose(key);
        }
    };
}

From source file:org.duracloud.common.web.RestHttpHelper.java

private HttpResponse executeRequest(String url, Method method, HttpEntity requestEntity,
        Map<String, String> headers) throws IOException {
    if (url == null || url.length() == 0) {
        throw new IllegalArgumentException("URL must be a non-empty value");
    }// w w w  .j a  va 2s.c om

    HttpRequestBase httpRequest = method.getMethod(url, requestEntity);

    if (headers != null && headers.size() > 0) {
        addHeaders(httpRequest, headers);
    }

    if (log.isDebugEnabled()) {
        log.debug(loggingRequestText(url, method, requestEntity, headers));
    }

    org.apache.http.HttpResponse response;
    if (null != credsProvider) {

        HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);

        if (socketTimeoutMs > -1) {
            BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
            cm.setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeoutMs).build());
            builder.setConnectionManager(cm);
        }

        CloseableHttpClient httpClient = buildClient(builder, method);

        // Use preemptive basic auth
        URI requestUri = httpRequest.getURI();
        HttpHost target = new HttpHost(requestUri.getHost(), requestUri.getPort(), requestUri.getScheme());
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);
        response = httpClient.execute(httpRequest, localContext);
    } else {
        CloseableHttpClient httpClient = buildClient(HttpClients.custom(), method);
        response = httpClient.execute(httpRequest);
    }

    HttpResponse httpResponse = new HttpResponse(response);

    if (log.isDebugEnabled()) {
        log.debug(loggingResponseText(httpResponse));
    }

    return httpResponse;
}

From source file:org.iipg.hurricane.jmx.client.JMXClientBuilder.java

private BasicHttpClientConnectionManager createBasicConnectionManager() {
    BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
            getSocketFactoryRegistry(), getConnectionFactory());
    connManager.setSocketConfig(createSocketConfig());
    connManager.setConnectionConfig(createConnectionConfig());
    return connManager;
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

/**
 * Returns the URL for the passed in String. If the URL requires authentication, then the WSDL
 * is saved as a temp file and the URL for that file is returned.
 * /*  w  ww. j a v a2  s  . co m*/
 * @param wsdlUrl
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private URL getWsdlUrl(DispatchContainer dispatchContainer) throws Exception {
    URI uri = new URI(dispatchContainer.getCurrentWsdlUrl());

    // If the URL points to file, just return it
    if (!uri.getScheme().equalsIgnoreCase("file")) {
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        CloseableHttpClient client = clientBuilder.build();

        try {
            clients.add(client);
            HttpClientContext context = HttpClientContext.create();

            if (dispatchContainer.getCurrentUsername() != null
                    && dispatchContainer.getCurrentPassword() != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,
                        AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(
                        dispatchContainer.getCurrentUsername(), dispatchContainer.getCurrentPassword());
                credsProvider.setCredentials(authScope, credentials);
                AuthCache authCache = new BasicAuthCache();
                RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder
                        .<AuthSchemeProvider>create();
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());

                context.setCredentialsProvider(credsProvider);
                context.setAuthSchemeRegistry(registryBuilder.build());
                context.setAuthCache(authCache);
            }

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setSocketTimeout(timeout).setStaleConnectionCheckEnabled(true).build();
            context.setRequestConfig(requestConfig);

            return getWsdl(client, context, dispatchContainer, new HashMap<String, File>(),
                    dispatchContainer.getCurrentWsdlUrl()).toURI().toURL();
        } finally {
            HttpClientUtils.closeQuietly(client);
            clients.remove(client);
        }
    }

    return uri.toURL();
}

From source file:org.archive.modules.fetcher.FetchHTTPRequest.java

protected HttpClientConnectionManager buildConnectionManager() {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE).register("https",
                    new SSLConnectionSocketFactory(fetcher.sslContext(), new AllowAllHostnameVerifier()) {

                        @Override
                        public Socket createLayeredSocket(final Socket socket, final String target,
                                final int port, final HttpContext context) throws IOException {

                            return super.createLayeredSocket(socket, isDisableSNI() ? "" : target, port,
                                    context);
                        }/*from   w  w w.java 2 s.  c  om*/
                    })
            .build();

    DnsResolver dnsResolver = new ServerCacheResolver(fetcher.getServerCache());

    ManagedHttpClientConnectionFactory connFactory = new ManagedHttpClientConnectionFactory() {
        private static final int DEFAULT_BUFSIZE = 8 * 1024;

        @Override
        public ManagedHttpClientConnection create(HttpRoute route, ConnectionConfig config) {
            final ConnectionConfig cconfig = config != null ? config : ConnectionConfig.DEFAULT;
            CharsetDecoder chardecoder = null;
            CharsetEncoder charencoder = null;
            final Charset charset = cconfig.getCharset();
            final CodingErrorAction malformedInputAction = cconfig.getMalformedInputAction() != null
                    ? cconfig.getMalformedInputAction()
                    : CodingErrorAction.REPORT;
            final CodingErrorAction unmappableInputAction = cconfig.getUnmappableInputAction() != null
                    ? cconfig.getUnmappableInputAction()
                    : CodingErrorAction.REPORT;
            if (charset != null) {
                chardecoder = charset.newDecoder();
                chardecoder.onMalformedInput(malformedInputAction);
                chardecoder.onUnmappableCharacter(unmappableInputAction);
                charencoder = charset.newEncoder();
                charencoder.onMalformedInput(malformedInputAction);
                charencoder.onUnmappableCharacter(unmappableInputAction);
            }
            return new RecordingHttpClientConnection(DEFAULT_BUFSIZE, DEFAULT_BUFSIZE, chardecoder, charencoder,
                    cconfig.getMessageConstraints(), null, null, DefaultHttpRequestWriterFactory.INSTANCE,
                    DefaultHttpResponseParserFactory.INSTANCE);
        }
    };
    BasicHttpClientConnectionManager connMan = new BasicHttpClientConnectionManager(socketFactoryRegistry,
            connFactory, null, dnsResolver);

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoTimeout(fetcher.getSoTimeoutMs());
    connMan.setSocketConfig(socketConfigBuilder.build());

    return connMan;
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties;
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING));

    String responseData = null;//from ww  w . j a v a 2  s .  c  o m
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    CloseableHttpClient client = null;
    HttpRequestBase httpMethod = null;
    CloseableHttpResponse httpResponse = null;
    File tempFile = null;
    int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000);

    try {
        configuration.configureDispatcher(this, httpDispatcherProperties);

        long dispatcherId = getDispatcherId();
        client = clients.get(dispatcherId);
        if (client == null) {
            BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                    socketFactoryRegistry.build());
            httpClientConnectionManager
                    .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
            HttpClientBuilder clientBuilder = HttpClients.custom()
                    .setConnectionManager(httpClientConnectionManager);
            HttpUtil.configureClientBuilder(clientBuilder);

            if (httpDispatcherProperties.isUseProxyServer()) {
                clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner());
            }

            client = clientBuilder.build();
            clients.put(dispatcherId, client);
        }

        URI hostURI = new URI(httpDispatcherProperties.getHost());
        String host = hostURI.getHost();
        String scheme = hostURI.getScheme();
        int port = hostURI.getPort();
        if (port == -1) {
            if (scheme.equalsIgnoreCase("https")) {
                port = 443;
            } else {
                port = 80;
            }
        }

        // Parse the content type field first, and then add the charset if needed
        ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType());
        Charset charset = null;
        if (contentType.getCharset() == null) {
            charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset()));
        } else {
            charset = contentType.getCharset();
        }

        if (httpDispatcherProperties.isMultipart()) {
            tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
        }

        HttpHost target = new HttpHost(host, port, scheme);

        httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile,
                contentType, charset);

        HttpClientContext context = HttpClientContext.create();

        // authentication
        if (httpDispatcherProperties.isUseAuthentication()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(),
                    httpDispatcherProperties.getPassword());
            credsProvider.setCredentials(authScope, credentials);
            AuthCache authCache = new BasicAuthCache();
            RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create();

            if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) {
                logger.debug("using Digest authentication");
                registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    processDigestChallenge(authCache, target, credentials, httpMethod, context);
                }
            } else {
                logger.debug("using Basic authentication");
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    authCache.put(target, new BasicScheme());
                }
            }

            context.setCredentialsProvider(credsProvider);
            context.setAuthSchemeRegistry(registryBuilder.build());
            context.setAuthCache(authCache);

            logger.debug("using authentication with credentials: " + credentials);
        }

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(socketTimeout)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        // Set proxy information
        if (httpDispatcherProperties.isUseProxyServer()) {
            context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(),
                    Integer.parseInt(httpDispatcherProperties.getProxyPort())));
        }

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString());
        httpResponse = client.execute(target, httpMethod, context);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        logger.debug("received status code: " + statusCode);

        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        for (Header header : httpResponse.getAllHeaders()) {
            List<String> list = headers.get(header.getName());

            if (list == null) {
                list = new ArrayList<String>();
                headers.put(header.getName(), list);
            }

            list.add(header.getValue());
        }

        connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString());
        connectorMessage.getConnectorMap().put("responseHeaders",
                new MessageHeaders(new CaseInsensitiveMap(headers)));

        ContentType responseContentType = ContentType.get(httpResponse.getEntity());
        if (responseContentType == null) {
            responseContentType = ContentType.TEXT_PLAIN;
        }

        Charset responseCharset = charset;
        if (responseContentType.getCharset() != null) {
            responseCharset = responseContentType.getCharset();
        }

        final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes();
        BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() {
            @Override
            public boolean isBinaryContentType(ContentType contentType) {
                return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType);
            }
        };

        /*
         * First parse out the body of the HTTP response. Depending on the connector settings,
         * this could end up being a string encoded with the response charset, a byte array
         * representing the raw response payload, or a MimeMultipart object.
         */
        Object responseBody = "";

        // The entity could be null in certain cases such as 204 responses
        if (httpResponse.getEntity() != null) {
            // Only parse multipart if XML Body is selected and Parse Multipart is enabled
            if (httpDispatcherProperties.isResponseXmlBody()
                    && httpDispatcherProperties.isResponseParseMultipart()
                    && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
                responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(),
                        responseContentType.toString()));
            } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) {
                responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent());
            } else {
                responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset);
            }
        }

        /*
         * Now that we have the response body, we need to create the actual Response message
         * data. Depending on the connector settings this could be our custom serialized XML, a
         * Base64 string encoded from the raw response payload, or a string encoded from the
         * payload with the request charset.
         */
        if (httpDispatcherProperties.isResponseXmlBody()) {
            responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody,
                    responseContentType, httpDispatcherProperties.isResponseParseMultipart(),
                    httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver);
        } else if (responseBody instanceof byte[]) {
            responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII");
        } else {
            responseData = (String) responseBody;
        }

        validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse();

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            responseStatus = Status.SENT;
        } else {
            eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                    connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                    connectorProperties.getName(), "Received error response from HTTP server.", null));
            responseStatusMessage = ErrorMessageBuilder
                    .buildErrorResponse("Received error response from HTTP server.", null);
            responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData,
                    null);
        }
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error connecting to HTTP server.", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error connecting to HTTP server", e);
    } finally {
        try {
            HttpClientUtils.closeQuietly(httpResponse);

            // Delete temp files if we created them
            if (tempFile != null) {
                tempFile.delete();
                tempFile = null;
            }
        } finally {
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.IDLE));
        }
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}