Example usage for org.apache.http.client CredentialsProvider toString

List of usage examples for org.apache.http.client CredentialsProvider toString

Introduction

In this page you can find the example usage for org.apache.http.client CredentialsProvider toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

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 w  w  . j av a 2 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();
        }
    });
}