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

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

Introduction

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

Prototype

String DIGEST

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

Click Source Link

Document

Digest authentication scheme as defined in RFC2617.

Usage

From source file:com.github.lpezet.antiope.dao.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient(APIConfiguration pConfiguration) {

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory(
            new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory());

    SSLContext oSslContext = null;
    X509HostnameVerifier oHostnameVerifier = null;
    if (pConfiguration.isCheckSSLCertificates()) {
        oSslContext = SSLContexts.createSystemDefault();
        oHostnameVerifier = new BrowserCompatHostnameVerifier();
    } else {/*from   ww w  .j  a v  a2s. c  o  m*/
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        // Install the all-trusting trust manager
        try {
            final SSLContext sslContext = SSLContext.getInstance(SSL);
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            //final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            oSslContext = sslContext;
        } catch (NoSuchAlgorithmException e) {
            throw new APIClientException(e);
        } catch (KeyManagementException e) {
            throw new APIClientException(e);
        }
        oHostnameVerifier = new AllowAllHostnameVerifier();
    }

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HTTP, PlainConnectionSocketFactory.INSTANCE)
            .register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver oDnsResolver = new SystemDefaultDnsResolver(); /* {
                                                               @Override
                                                               public InetAddress[] resolve(final String host) throws UnknownHostException {
                                                               if (host.equalsIgnoreCase("myhost")) {
                                                               return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
                                                               } else {
                                                               return super.resolve(host);
                                                               }
                                                               }
                                                               };*/

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager(
            oSocketFactoryRegistry, oConnFactory, oDnsResolver);

    // Create socket configuration
    SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true)
            .setSoTimeout(pConfiguration.getSocketTimeout()).build();

    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    oConnManager.setDefaultSocketConfig(oSocketConfig);
    // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig);

    // Create message constraints
    MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig oConnectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(oMessageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    oConnManager.setDefaultConnectionConfig(oConnectionConfig);
    // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    oConnManager.setMaxTotal(100);
    oConnManager.setDefaultMaxPerRoute(10);
    //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore oCookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    //
    // Create global request configuration
    RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            //.setExpectContinueEnabled(true)         // WARNING: setting it to true slows things down by 4s!!!!
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setConnectTimeout(pConfiguration.getConnectionTimeout()).build();

    CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider();
    HttpHost oProxy = null;

    if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) {
        String proxyHost = pConfiguration.getProxyHost();
        int proxyPort = pConfiguration.getProxyPort();
        String proxyUsername = pConfiguration.getProxyUsername();
        String proxyPassword = pConfiguration.getProxyPassword();
        String proxyDomain = pConfiguration.getProxyDomain();
        String proxyWorkstation = pConfiguration.getProxyWorkstation();

        oProxy = new HttpHost(proxyHost, proxyPort);

        if (proxyUsername != null && proxyPassword != null) {
            oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager)
            .setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider)
            .setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build();

    return oHttpClient;
    /*
    RequestConfig oRequestConfig = RequestConfig.custom()
    .setConnectTimeout(pConfiguration.getConnectionTimeout())
    .setSocketTimeout(pConfiguration.getSocketTimeout())
    .setStaleConnectionCheckEnabled(true)
    .build();
    */
}

From source file:ch.cyberduck.core.http.HttpConnectionPoolBuilder.java

public HttpClientBuilder build(final TranscriptListener listener) {
    // Use HTTP Connect proxy implementation provided here instead of
    // relying on internal proxy support in socket factory
    final Proxy proxy = proxyFinder.find(host);
    if (proxy.getType() == Proxy.Type.HTTP) {
        final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.http.name());
        if (log.isInfoEnabled()) {
            log.info(String.format("Setup proxy %s", h));
        }//  w  ww.  jav  a2 s.  co  m
        builder.setProxy(h);
    }
    if (proxy.getType() == Proxy.Type.HTTPS) {
        final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.https.name());
        if (log.isInfoEnabled()) {
            log.info(String.format("Setup proxy %s", h));
        }
        builder.setProxy(h);
    }
    builder.setUserAgent(new PreferencesUseragentProvider().get());
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(timeout).build());
    builder.setDefaultRequestConfig(RequestConfig.custom().setRedirectsEnabled(true)
            // Disable use of Expect: Continue by default for all methods
            .setExpectContinueEnabled(false).setAuthenticationEnabled(true).setConnectTimeout(timeout)
            // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager
            .setConnectionRequestTimeout(preferences.getInteger("http.manager.timeout"))
            .setSocketTimeout(timeout).build());
    final String encoding;
    if (null == host.getEncoding()) {
        encoding = preferences.getProperty("browser.charset.encoding");
    } else {
        encoding = host.getEncoding();
    }
    builder.setDefaultConnectionConfig(
            ConnectionConfig.custom().setBufferSize(preferences.getInteger("http.socket.buffer"))
                    .setCharset(Charset.forName(encoding)).build());
    if (preferences.getBoolean("http.connections.reuse")) {
        builder.setConnectionReuseStrategy(new DefaultConnectionReuseStrategy());
    } else {
        builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    }
    builder.setRetryHandler(
            new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry")));
    if (!preferences.getBoolean("http.compression.enable")) {
        builder.disableContentCompression();
    }
    builder.setRequestExecutor(new LoggingHttpRequestExecutor(listener));
    // Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the
    // default port and the socket factory to be used to create the java.net.Socket instances for the given protocol
    builder.setConnectionManager(this.pool(this.registry().build()));
    builder.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC,
                    new BasicSchemeFactory(
                            Charset.forName(preferences.getProperty("http.credentials.charset"))))
            .register(AuthSchemes.DIGEST,
                    new DigestSchemeFactory(
                            Charset.forName(preferences.getProperty("http.credentials.charset"))))
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build());
    return builder;
}

From source file:org.jboss.as.test.integration.management.http.HttpGenericOperationUnitTestCase.java

private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
    try {//from  w  ww .  j  a  va  2  s . co m
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                new UsernamePasswordCredentials(username, password));
        PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry);
        HttpClientBuilder.create().setConnectionManager(connectionPool).build();
        return HttpClientBuilder.create().setConnectionManager(connectionPool)
                .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                .setDefaultCredentialsProvider(credsProvider).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.sdr.webrec.core.WebRec.java

private void initParameters() {

    // initialize HTTP parameters
    params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    httpclient = new DefaultHttpClient(cm, params);

    //TODO: CloseableHttpClient httpclient = HttpClients.createDefault();

    //set proxy if available in settings
    if (settings.getProxyHost() != null && settings.getProxyHost().length() > 0) {
        HttpHost proxy = new HttpHost(settings.getProxyHost(), settings.getProxyPort());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        //set authentication to proxy is available is settings
        if (settings.getProxyUserName() != null && settings.getProxyUserName().length() > 0
                && settings.getProxyPasswd() != null) {
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(settings.getProxyHost(), settings.getProxyPort()),
                    new UsernamePasswordCredentials(settings.getProxyUserName(), settings.getProxyPasswd()));
            LOGGER.debug("autentication for proxy on");
        }/*from  w  w w .  ja  v a  2 s.com*/

    }

    // initialize scheme registry 
    schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    // Create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    httpclient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {

        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            // Honor 'keep-alive' header
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    try {
                        return Long.parseLong(value);
                    } catch (NumberFormatException ignore) {

                    }
                }
            }
            //otherwise keep alive for 30 seconds
            return 30 * 1000;
        }

    });

    httpget = null;

    httpclient = new DefaultHttpClient(cm, params);

    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(settings.isKeepConnectionAlive())
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();

    requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(timeout)
            .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();

}

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  w  w  .  j a  va 2  s . co  m*/
}

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

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;/*from   w w  w .j a va2  s .  co 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:org.jboss.as.test.integration.domain.suites.ResponseStreamTestCase.java

private HttpClient getHttpClient(URL url) {
    shutdownHttpClient();/*  www.  ja  v  a2 s .co  m*/
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(url.getHost(), url.getPort(), "ManagementRealm", AuthSchemes.DIGEST),
            new UsernamePasswordCredentials(DomainLifecycleUtil.SLAVE_HOST_USERNAME,
                    DomainLifecycleUtil.SLAVE_HOST_PASSWORD));

    httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build();

    return httpClient;
}

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  .  java 2 s.  c o  m
 * @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;
}