Example usage for org.apache.http.client.config AuthSchemes BASIC

List of usage examples for org.apache.http.client.config AuthSchemes BASIC

Introduction

In this page you can find the example usage for org.apache.http.client.config AuthSchemes BASIC.

Prototype

String BASIC

To view the source code for org.apache.http.client.config AuthSchemes BASIC.

Click Source Link

Document

Basic authentication scheme as defined in RFC2617 (considered inherently insecure, but most widely supported)

Usage

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagonFixed.java

private static CloseableHttpClient createClient() {
    return HttpClientBuilder.create() //
            .useSystemProperties() //
            .disableConnectionState() //
            .setConnectionManager(httpClientConnectionManager) //
            //Using Custom Default Schema Registry
            .setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                    .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                    .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
                    //Using Custom SPNEGO Factory & FORCE strip port
                    //Kerberos Error: Server not found in Kerberos database (7) - LOOKING_UP_SERVER
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true))
                    .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory(true)).build())
            .build();/* w  ww . j  a  v a 2s.c  o m*/
}

From source file:org.artifactory.util.HttpClientConfigurator.java

private void configureProxy(ProxyDescriptor proxy) {
    if (proxy != null) {
        config.setProxy(new HttpHost(proxy.getHost(), proxy.getPort()));
        if (proxy.getUsername() != null) {
            Credentials creds = null;/*  w ww . j  av  a 2  s .  c o  m*/
            if (proxy.getDomain() == null) {
                creds = new UsernamePasswordCredentials(proxy.getUsername(),
                        CryptoHelper.decryptIfNeeded(proxy.getPassword()));
                //This will demote the NTLM authentication scheme so that the proxy won't barf
                //when we try to give it traditional credentials. If the proxy doesn't do NTLM
                //then this won't hurt it (jcej at tragus dot org)
                List<String> authPrefs = Arrays.asList(AuthSchemes.DIGEST, AuthSchemes.BASIC, AuthSchemes.NTLM);
                config.setProxyPreferredAuthSchemes(authPrefs);
                // preemptive proxy authentication
                builder.addInterceptorFirst(new ProxyPreemptiveAuthInterceptor());
            } else {
                try {
                    String ntHost = StringUtils.isBlank(proxy.getNtHost())
                            ? InetAddress.getLocalHost().getHostName()
                            : proxy.getNtHost();
                    creds = new NTCredentials(proxy.getUsername(),
                            CryptoHelper.decryptIfNeeded(proxy.getPassword()), ntHost, proxy.getDomain());
                } catch (UnknownHostException e) {
                    log.error("Failed to determine required local hostname for NTLM credentials.", e);
                }
            }
            if (creds != null) {
                credsProvider.setCredentials(
                        new AuthScope(proxy.getHost(), proxy.getPort(), AuthScope.ANY_REALM), creds);
                if (proxy.getRedirectedToHostsList() != null) {
                    for (String hostName : proxy.getRedirectedToHostsList()) {
                        credsProvider.setCredentials(
                                new AuthScope(hostName, AuthScope.ANY_PORT, AuthScope.ANY_REALM), creds);
                    }
                }
            }
        }
    }
}

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 w ww . j  av  a 2 s .c  om
    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);
}

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 w  w .j ava  2s . c om
 * @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:net.yacy.cora.protocol.http.HTTPClient.java

/**
 * This method GETs a page from the server.
 *
 * @param uri the url to get//from  w  ww.j  a va2  s  . com
 * @param username user name for HTTP authentication : only sent requesting localhost
 * @param pass password for HTTP authentication : only sent when requesting localhost
 * @param maxBytes maximum response bytes to read
 * @param concurrent whether a new thread should be created to handle the request. 
 * Ignored when requesting localhost or when the authentication password is not null
 * @return content bytes
 * @throws IOException
 */
public byte[] GETbytes(final MultiProtocolURL url, final String username, final String pass, final int maxBytes,
        final boolean concurrent) throws IOException {
    final boolean localhost = Domains.isLocalhost(url.getHost());
    final String urix = url.toNormalform(true);
    HttpGet httpGet = null;
    try {
        httpGet = new HttpGet(urix);
    } catch (IllegalArgumentException e) {
        throw new IOException(e.getMessage()); // can be caused  at java.net.URI.create()
    }
    if (!localhost)
        setHost(url.getHost()); // overwrite resolved IP, needed for shared web hosting DO NOT REMOVE, see http://en.wikipedia.org/wiki/Shared_web_hosting_service
    if (!localhost || pass == null) {
        return getContentBytes(httpGet, maxBytes, concurrent);
    }

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", url.getPort()),
            new UsernamePasswordCredentials(username, pass));

    /* Use the custom YaCyDigestScheme for HTTP Digest Authentication */
    final Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new YaCyDigestSchemeFactory()).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .setDefaultAuthSchemeRegistry(authSchemeRegistry).build();
    byte[] content = null;
    try {
        this.httpResponse = httpclient.execute(httpGet);
        try {
            HttpEntity httpEntity = this.httpResponse.getEntity();
            if (httpEntity != null) {
                if (getStatusCode() == HttpStatus.SC_OK) {
                    if (maxBytes >= 0 && httpEntity.getContentLength() > maxBytes) {
                        /* When anticipated content length is already known and exceed the specified limit : 
                         * throw an exception and abort the connection, consistently with getByteArray() implementation 
                         * Otherwise returning null and consuming fully the entity can be very long on large resources */
                        throw new IOException("Content to download exceed maximum value of "
                                + Formatter.bytesToString(maxBytes));
                    }
                    content = getByteArray(httpEntity, maxBytes);
                }
                // Ensures that the entity content is fully consumed and the content stream, if exists, is closed.
                EntityUtils.consume(httpEntity);
            }
        } catch (final IOException e) {
            httpGet.abort();
            throw e;
        } finally {
            this.httpResponse.close();
        }
    } finally {
        httpclient.close();
    }
    return content;
}

From source file:org.bonitasoft.connectors.rest.RESTConnector.java

/**
 * Set the request builder based on the request
 * // w w w .j ava  2  s .  c  o  m
 * @param proxy The request Proxy options
 * @param httpClientBuilder The request builder
 * @throws Exception
 */
private void setProxy(final Proxy proxy, final HttpClientBuilder httpClientBuilder,
        final Builder requestConfigurationBuilder) {
    if (proxy != null) {
        final HttpHost httpHost = new HttpHost(proxy.getHost(), proxy.getPort());

        httpClientBuilder.setProxy(httpHost);
        httpClientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

        requestConfigurationBuilder.setProxy(httpHost);
        final ArrayList<String> authPrefs = new ArrayList<>();
        authPrefs.add(AuthSchemes.BASIC);
        requestConfigurationBuilder.setProxyPreferredAuthSchemes(authPrefs);
    }
}

From source file:nl.nn.adapterframework.http.HttpSenderBase.java

public void configure() throws ConfigurationException {
    super.configure();

    if (!getMethodType().equals("POST")) {
        if (!isParamsInUrl()) {
            throw new ConfigurationException(
                    getLogPrefix() + "paramsInUrl can only be set to false for methodType POST");
        }//from  w  ww  .  ja v  a2 s  . c  o  m
        if (StringUtils.isNotEmpty(getInputMessageParam())) {
            throw new ConfigurationException(
                    getLogPrefix() + "inputMessageParam can only be set for methodType POST");
        }
    }

    /**
     * TODO find out if this really breaks proxy authentication or not.
     */
    //      httpClientBuilder.disableAuthCaching();
    httpClientBuilder.disableAutomaticRetries();

    Builder requestConfig = RequestConfig.custom();
    requestConfig.setConnectTimeout(getTimeout());
    requestConfig.setConnectionRequestTimeout(getTimeout());
    requestConfig.setSocketTimeout(getTimeout());

    if (paramList != null) {
        paramList.configure();
        if (StringUtils.isNotEmpty(getUrlParam())) {
            urlParameter = paramList.findParameter(getUrlParam());
            addParameterToSkip(urlParameter);
        }
    }
    if (getMaxConnections() <= 0) {
        throw new ConfigurationException(getLogPrefix() + "maxConnections is set to [" + getMaxConnections()
                + "], which is not enough for adequate operation");
    }
    try {
        if (urlParameter == null) {
            if (StringUtils.isEmpty(getUrl())) {
                throw new ConfigurationException(
                        getLogPrefix() + "url must be specified, either as attribute, or as parameter");
            }
            staticUri = getURI(getUrl());
        }

        URL certificateUrl = null;
        URL truststoreUrl = null;

        if (!StringUtils.isEmpty(getCertificate())) {
            certificateUrl = ClassUtils.getResourceURL(getClassLoader(), getCertificate());
            if (certificateUrl == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find URL for certificate resource [" + getCertificate() + "]");
            }
            log.info(getLogPrefix() + "resolved certificate-URL to [" + certificateUrl.toString() + "]");
        }
        if (!StringUtils.isEmpty(getTruststore())) {
            truststoreUrl = ClassUtils.getResourceURL(getClassLoader(), getTruststore());
            if (truststoreUrl == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find URL for truststore resource [" + getTruststore() + "]");
            }
            log.info(getLogPrefix() + "resolved truststore-URL to [" + truststoreUrl.toString() + "]");
        }

        HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
        if (!isVerifyHostname())
            hostnameVerifier = new NoopHostnameVerifier();

        // Add javax.net.ssl.SSLSocketFactory.getDefault() SSLSocketFactory if non has been set.
        // See: http://httpcomponents.10934.n7.nabble.com/Upgrading-commons-httpclient-3-x-to-HttpClient4-x-td19333.html
        // 
        // The first time this method is called, the security property "ssl.SocketFactory.provider" is examined. 
        // If it is non-null, a class by that name is loaded and instantiated. If that is successful and the 
        // object is an instance of SSLSocketFactory, it is made the default SSL socket factory.
        // Otherwise, this method returns SSLContext.getDefault().getSocketFactory(). If that call fails, an inoperative factory is returned.
        javax.net.ssl.SSLSocketFactory socketfactory = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory
                .getDefault();
        sslSocketFactory = new SSLConnectionSocketFactory(socketfactory, hostnameVerifier);

        if (certificateUrl != null || truststoreUrl != null || isAllowSelfSignedCertificates()) {
            try {
                CredentialFactory certificateCf = new CredentialFactory(getCertificateAuthAlias(), null,
                        getCertificatePassword());
                CredentialFactory truststoreCf = new CredentialFactory(getTruststoreAuthAlias(), null,
                        getTruststorePassword());

                SSLContext sslContext = AuthSSLConnectionSocket.createSSLContext(certificateUrl,
                        certificateCf.getPassword(), getKeystoreType(), getKeyManagerAlgorithm(), truststoreUrl,
                        truststoreCf.getPassword(), getTruststoreType(), getTrustManagerAlgorithm(),
                        isAllowSelfSignedCertificates(), isVerifyHostname(),
                        isIgnoreCertificateExpiredException(), getProtocol());

                sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
                log.debug(getLogPrefix() + "created custom SSLConnectionSocketFactory");

            } catch (Throwable t) {
                throw new ConfigurationException(getLogPrefix() + "cannot create or initialize SocketFactory",
                        t);
            }
        }

        // This method will be overwritten by the connectionManager when connectionPooling is enabled!
        // Can still be null when no default or an invalid system sslSocketFactory has been defined
        if (sslSocketFactory != null)
            httpClientBuilder.setSSLSocketFactory(sslSocketFactory);

        credentials = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (!StringUtils.isEmpty(credentials.getUsername())) {
            String uname;
            if (StringUtils.isNotEmpty(getAuthDomain())) {
                uname = getAuthDomain() + "\\" + credentials.getUsername();
            } else {
                uname = credentials.getUsername();
            }

            credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(uname, credentials.getPassword()));

            requestConfig.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));
            requestConfig.setAuthenticationEnabled(true);
        }
        if (StringUtils.isNotEmpty(getProxyHost())) {
            HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
            AuthScope scope = new AuthScope(proxy, getProxyRealm(), AuthScope.ANY_SCHEME);

            CredentialFactory pcf = new CredentialFactory(getProxyAuthAlias(), getProxyUserName(),
                    getProxyPassword());

            if (StringUtils.isNotEmpty(pcf.getUsername())) {
                Credentials credentials = new UsernamePasswordCredentials(pcf.getUsername(), pcf.getPassword());
                credentialsProvider.setCredentials(scope, credentials);
            }
            log.trace("setting credentialProvider [" + credentialsProvider.toString() + "]");

            if (prefillProxyAuthCache()) {
                requestConfig.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));

                AuthCache authCache = httpClientContext.getAuthCache();
                if (authCache == null)
                    authCache = new BasicAuthCache();

                authCache.put(proxy, new BasicScheme());
                httpClientContext.setAuthCache(authCache);
            }

            requestConfig.setProxy(proxy);
            httpClientBuilder.setProxy(proxy);
        }

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    } catch (URISyntaxException e) {
        throw new ConfigurationException(getLogPrefix() + "cannot interpret uri [" + getUrl() + "]");
    }

    if (StringUtils.isNotEmpty(getStyleSheetName())) {
        try {
            URL stylesheetURL = ClassUtils.getResourceURL(getClassLoader(), getStyleSheetName());
            if (stylesheetURL == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find stylesheet [" + getStyleSheetName() + "]");
            }
            transformerPool = TransformerPool.getInstance(stylesheetURL);
        } catch (IOException e) {
            throw new ConfigurationException(getLogPrefix() + "cannot retrieve [" + getStyleSheetName() + "]",
                    e);
        } catch (TransformerConfigurationException te) {
            throw new ConfigurationException(
                    getLogPrefix() + "got error creating transformer from file [" + getStyleSheetName() + "]",
                    te);
        }
    }

    httpClientBuilder.setDefaultRequestConfig(requestConfig.build());

    // The redirect strategy used to only redirect GET, DELETE and HEAD.
    httpClientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        protected boolean isRedirectable(String method) {
            return isFollowRedirects();
        }
    });
}

From source file:org.bonitasoft.connectors.rest.RESTConnector.java

/**
 * Set the builder based on the request elements
 * /*from   w w w .  ja v  a2s .c  o  m*/
 * @param requestConfigurationBuilder The builder to be set
 * @param authorization The authentication element of the request
 * @param proxy The proxy element of the request
 * @param urlHost The URL host of the request
 * @param urlPort The URL post of the request
 * @param urlProtocol The URL protocol of the request
 * @param httpClientBuilder The builder to be set
 * @return HTTPContext The HTTP context to be set
 */
private HttpContext setAuthorizations(final Builder requestConfigurationBuilder,
        final Authorization authorization, final Proxy proxy, final String urlHost, final int urlPort,
        final String urlProtocol, final HttpClientBuilder httpClientBuilder) {
    HttpContext httpContext = HttpClientContext.create();
    if (authorization != null) {
        if (authorization instanceof BasicDigestAuthorization) {
            final BasicDigestAuthorization castAuthorization = (BasicDigestAuthorization) authorization;

            final List<String> authPrefs = new ArrayList<>();
            if (castAuthorization.isBasic()) {
                authPrefs.add(AuthSchemes.BASIC);
            } else {
                authPrefs.add(AuthSchemes.DIGEST);
            }
            requestConfigurationBuilder.setTargetPreferredAuthSchemes(authPrefs);

            final String username = castAuthorization.getUsername();
            final String password = new String(castAuthorization.getPassword());
            String host = urlHost;
            if (isStringInputValid(castAuthorization.getHost())) {
                host = castAuthorization.getHost();
            }

            int port = urlPort;
            if (castAuthorization.getPort() != null) {
                port = castAuthorization.getPort();
            }

            String realm = AuthScope.ANY_REALM;
            if (isStringInputValid(castAuthorization.getRealm())) {
                realm = castAuthorization.getRealm();
            }

            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(host, port, realm),
                    new UsernamePasswordCredentials(username, password));
            setProxyCrendentials(proxy, credentialsProvider);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

            if (castAuthorization.isPreemptive() || proxy != null) {
                final AuthCache authoriationCache = new BasicAuthCache();
                if (castAuthorization.isPreemptive()) {
                    AuthSchemeBase authorizationScheme = null;
                    if (castAuthorization.isBasic()) {
                        authorizationScheme = new BasicScheme(ChallengeState.TARGET);
                    } else {
                        authorizationScheme = new DigestScheme(ChallengeState.TARGET);
                    }
                    authoriationCache.put(new HttpHost(host, port, urlProtocol), authorizationScheme);
                }
                if (proxy != null) {
                    final BasicScheme basicScheme = new BasicScheme(ChallengeState.PROXY);
                    authoriationCache.put(new HttpHost(proxy.getHost(), proxy.getPort()), basicScheme);
                }
                final HttpClientContext localContext = HttpClientContext.create();
                localContext.setAuthCache(authoriationCache);
                httpContext = localContext;
            }
        }
    } else if (proxy != null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        setProxyCrendentials(proxy, credentialsProvider);
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

        // Make it preemptive
        if (proxy.hasCredentials()) {
            final AuthCache authoriationCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme(ChallengeState.PROXY);
            authoriationCache.put(new HttpHost(proxy.getHost(), proxy.getPort()), basicScheme);
            final HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authoriationCache);
            httpContext = localContext;
        }
    }

    return httpContext;
}