Example usage for org.apache.http.auth NTCredentials NTCredentials

List of usage examples for org.apache.http.auth NTCredentials NTCredentials

Introduction

In this page you can find the example usage for org.apache.http.auth NTCredentials NTCredentials.

Prototype

public NTCredentials(final String userName, final String password, final String workstation,
        final String domain) 

Source Link

Document

Constructor.

Usage

From source file:fi.laverca.util.CommonsHTTPSender.java

/**
 * Extracts info from message context./*from   ww  w .j ava 2s .c o  m*/
 *
 * @param method Post method
 * @param httpClient The client used for posting
 * @param msgContext the message context
 * @param tmpURL the url to post to.
 *
 * @throws Exception if any error occurred
 */
private void addContextInfo(final HttpPost method, final HttpClient httpClient, final MessageContext msgContext,
        final URL tmpURL) throws Exception {
    HttpParams params = method.getParams();

    if (msgContext.getTimeout() != 0) {
        // optionally set a timeout for response waits
        HttpConnectionParams.setSoTimeout(params, msgContext.getTimeout());
    }

    // Always set the 30 second timeout on establishing the connection
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);

    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants()));
    }

    if (msgContext.useSOAPAction()) {
        // define SOAPAction header
        String action = msgContext.getSOAPActionURI();
        if (action != null && !"".equals(action))
            method.setHeader(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"");
    }

    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials proxyCred = new UsernamePasswordCredentials(userID, passwd);
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf("\\");
        if (domainIndex > 0) {
            String domain = userID.substring(0, domainIndex);
            if (userID.length() > domainIndex + 1) {
                String user = userID.substring(domainIndex + 1);
                proxyCred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
            }
        }
        ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY, proxyCred);
    }

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator<?> i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            //HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set.
            //Let's not duplicate them.
            String headerName = mimeHeader.getName();
            if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE)
                    || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) {
                continue;
            }
            method.addHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable<?, ?> userHeaderTable = (Hashtable<?, ?>) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (Iterator<?> e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            Map.Entry<?, ?> me = (Map.Entry<?, ?>) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT)
                    && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
                HttpProtocolParams.setUseExpectContinue(params, true);
            } else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
                String val = me.getValue().toString();
                if (null != val) {
                    httpChunkStream = JavaUtils.isTrue(val);
                }
            } else {
                method.addHeader(key, value);
            }
        }
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.wiki.WikiConnector.java

protected void getSession() throws ManifoldCFException, ServiceInterruption {
    if (hasBeenSetup == false) {
        String emailAddress = params.getParameter(WikiConfig.PARAM_EMAIL);
        if (emailAddress != null)
            userAgent = "Mozilla/5.0 (ApacheManifoldCFWikiReader; "
                    + ((emailAddress == null) ? "" : emailAddress) + ")";
        else//from w w  w .  j  a v  a2s.c  o  m
            userAgent = null;

        String protocol = params.getParameter(WikiConfig.PARAM_PROTOCOL);
        if (protocol == null || protocol.length() == 0)
            protocol = "http";
        String portString = params.getParameter(WikiConfig.PARAM_PORT);
        if (portString == null || portString.length() == 0)
            portString = null;
        String path = params.getParameter(WikiConfig.PARAM_PATH);
        if (path == null)
            path = "/w";

        baseURL = protocol + "://" + server + ((portString != null) ? ":" + portString : "") + path
                + "/api.php?format=xml&";

        int socketTimeout = 900000;
        int connectionTimeout = 300000;

        javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory
                .getTrustingSecureSocketFactory();
        SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
                new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        // Set up connection manager
        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        if (accessUser != null && accessUser.length() > 0 && accessPassword != null) {
            Credentials credentials = new UsernamePasswordCredentials(accessUser, accessPassword);
            if (accessRealm != null && accessRealm.length() > 0)
                credentialsProvider.setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, accessRealm), credentials);
            else
                credentialsProvider.setCredentials(AuthScope.ANY, credentials);
        }

        RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        // If there's a proxy, set that too.
        if (proxyHost != null && proxyHost.length() > 0) {

            int proxyPortInt;
            if (proxyPort != null && proxyPort.length() > 0) {
                try {
                    proxyPortInt = Integer.parseInt(proxyPort);
                } catch (NumberFormatException e) {
                    throw new ManifoldCFException("Bad number: " + e.getMessage(), e);
                }
            } else
                proxyPortInt = 8080;

            // Configure proxy authentication
            if (proxyUsername != null && proxyUsername.length() > 0) {
                if (proxyPassword == null)
                    proxyPassword = "";
                if (proxyDomain == null)
                    proxyDomain = "";

                credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPortInt),
                        new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
            }

            HttpHost proxy = new HttpHost(proxyHost, proxyPortInt);
            requestBuilder.setProxy(proxy);
        }

        httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
                .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
                .setRequestExecutor(new HttpRequestExecutor(socketTimeout)).build();

        /*
        BasicHttpParams params = new BasicHttpParams();
        params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,true);
        params.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE,socketTimeout);
        params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,true);
        params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,true);
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,socketTimeout);
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,connectionTimeout);
        params.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,true);
        DefaultHttpClient localHttpClient = new DefaultHttpClient(connectionManager,params);
        // No retries
        localHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler()
          {
            public boolean retryRequest(
              IOException exception,
              int executionCount,
              HttpContext context)
            {
              return false;
            }
                 
          });
        */

        loginToAPI();

        hasBeenSetup = true;
    }
}

From source file:org.hyperic.plugin.vrealize.automation.DiscoveryVRAIaasWeb.java

private static String getVCO(ConfigResponse config) {
    String vcoFNQ = null;/*w ww  . j  av  a  2 s .  c o m*/
    String xml = null;

    String user = config.getValue("iaas.http.user", "");
    String pass = config.getValue("iaas.http.pass", "");
    String domain = config.getValue("iaas.http.domain", "");

    try {
        AgentKeystoreConfig ksCFG = new AgentKeystoreConfig();
        HQHttpClient client = new HQHttpClient(ksCFG, new HttpConfig(5000, 5000, null, 0),
                ksCFG.isAcceptUnverifiedCert());

        List<String> authpref = new ArrayList<String>();
        authpref.add(AuthPolicy.NTLM);
        authpref.add(AuthPolicy.BASIC);
        client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

        client.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthPolicy.NTLM),
                new NTCredentials(user, pass, "localhost", domain));

        HttpGet get = new HttpGet(
                "https://localhost/Repository/Data/ManagementModelEntities.svc/ManagementEndpoints");
        HttpResponse response = client.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            xml = readInputString(response.getEntity().getContent());
        } else {
            log.debug("[getVCOx] GET failed: " + response.getStatusLine().getReasonPhrase());
        }
    } catch (IOException ex) {
        log.debug("[getVCOx] " + ex, ex);
    }

    if (xml != null) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = (Document) builder.parse(new ByteArrayInputStream(xml.getBytes()));

            log.debug("[getVCOx] xml:" + xml);

            XPathFactory xFactory = XPathFactory.newInstance();
            XPath xpath = xFactory.newXPath();

            String xPath = "//properties[InterfaceType[text()='vCO']]/ManagementEndpointName/text()";

            log.debug("[getVCOx] evaluating XPath:" + xPath);

            vcoFNQ = xpath.evaluate(xPath, doc);

            log.debug("[getVCOx] vcoFNQ:" + vcoFNQ);

        } catch (Exception ex) {
            log.debug("[getVCOx] " + ex, ex);
        }
    }

    return VRAUtils.getFqdn(vcoFNQ);
}

From source file:org.apache.manifoldcf.crawler.connectors.sharepoint.SharePointRepository.java

/** Set up a session */
protected void getSession() throws ManifoldCFException {
    if (proxy == null) {
        String serverVersion = params.getParameter(SharePointConfig.PARAM_SERVERVERSION);
        if (serverVersion == null)
            serverVersion = "4.0";
        supportsItemSecurity = !serverVersion.equals("2.0");
        dspStsWorks = serverVersion.equals("2.0") || serverVersion.equals("3.0");
        attachmentsSupported = !serverVersion.equals("2.0");

        String authorityType = params.getParameter(SharePointConfig.PARAM_AUTHORITYTYPE);
        if (authorityType == null)
            authorityType = "ActiveDirectory";

        activeDirectoryAuthority = authorityType.equals("ActiveDirectory");

        serverProtocol = params.getParameter(SharePointConfig.PARAM_SERVERPROTOCOL);
        if (serverProtocol == null)
            serverProtocol = "http";
        try {//from w ww .ja  va  2s  .  c om
            String serverPort = params.getParameter(SharePointConfig.PARAM_SERVERPORT);
            if (serverPort == null || serverPort.length() == 0) {
                if (serverProtocol.equals("https"))
                    this.serverPort = 443;
                else
                    this.serverPort = 80;
            } else
                this.serverPort = Integer.parseInt(serverPort);
        } catch (NumberFormatException e) {
            throw new ManifoldCFException(e.getMessage(), e);
        }
        serverLocation = params.getParameter(SharePointConfig.PARAM_SERVERLOCATION);
        if (serverLocation == null)
            serverLocation = "";
        if (serverLocation.endsWith("/"))
            serverLocation = serverLocation.substring(0, serverLocation.length() - 1);
        if (serverLocation.length() > 0 && !serverLocation.startsWith("/"))
            serverLocation = "/" + serverLocation;
        encodedServerLocation = serverLocation;
        serverLocation = decodePath(serverLocation);

        userName = params.getParameter(SharePointConfig.PARAM_SERVERUSERNAME);
        password = params.getObfuscatedParameter(SharePointConfig.PARAM_SERVERPASSWORD);
        int index = userName.indexOf("\\");
        if (index != -1) {
            strippedUserName = userName.substring(index + 1);
            ntlmDomain = userName.substring(0, index);
        } else {
            strippedUserName = null;
            ntlmDomain = null;
        }

        String proxyHost = params.getParameter(SharePointConfig.PARAM_PROXYHOST);
        String proxyPortString = params.getParameter(SharePointConfig.PARAM_PROXYPORT);
        int proxyPort = 8080;
        if (proxyPortString != null && proxyPortString.length() > 0) {
            try {
                proxyPort = Integer.parseInt(proxyPortString);
            } catch (NumberFormatException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
        String proxyUsername = params.getParameter(SharePointConfig.PARAM_PROXYUSER);
        String proxyPassword = params.getParameter(SharePointConfig.PARAM_PROXYPASSWORD);
        String proxyDomain = params.getParameter(SharePointConfig.PARAM_PROXYDOMAIN);

        serverUrl = serverProtocol + "://" + serverName;
        if (serverProtocol.equals("https")) {
            if (serverPort != 443)
                serverUrl += ":" + Integer.toString(serverPort);
        } else {
            if (serverPort != 80)
                serverUrl += ":" + Integer.toString(serverPort);
        }

        fileBaseUrl = serverUrl + encodedServerLocation;

        // Set up ssl if indicated
        keystoreData = params.getParameter(SharePointConfig.PARAM_SERVERKEYSTORE);

        int connectionTimeout = 60000;
        int socketTimeout = 900000;

        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        SSLConnectionSocketFactory myFactory = null;
        if (keystoreData != null) {
            keystoreManager = KeystoreManagerFactory.make("", keystoreData);
            myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(),
                    new BrowserCompatHostnameVerifier());
        }

        if (strippedUserName != null) {
            credentialsProvider.setCredentials(new AuthScope(serverName, serverPort),
                    new NTCredentials(strippedUserName, password, currentHost, ntlmDomain));
        }

        RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        // If there's a proxy, set that too.
        if (proxyHost != null && proxyHost.length() > 0) {

            // Configure proxy authentication
            if (proxyUsername != null && proxyUsername.length() > 0) {
                if (proxyPassword == null)
                    proxyPassword = "";
                if (proxyDomain == null)
                    proxyDomain = "";

                credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
            }

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);

            requestBuilder.setProxy(proxy);
        }

        HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
                .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(credentialsProvider);
        if (myFactory != null)
            builder.setSSLSocketFactory(myFactory);
        builder.setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy());
        httpClient = builder.build();

        proxy = new SPSProxyHelper(serverUrl, encodedServerLocation, serverLocation, userName, password,
                org.apache.manifoldcf.connectorcommon.common.CommonsHTTPSender.class, "client-config.wsdd",
                httpClient);

    }
    sessionTimeout = System.currentTimeMillis() + sessionExpirationInterval;
}

From source file:org.codelibs.fess.es.config.exentity.DataConfig.java

private Credentials getCredentials(final String webAuthName, final String scheme,
        final Map<String, String> paramMap) {
    final String username = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".username");
    if (StringUtil.isEmpty(username)) {
        throw new CrawlerSystemException("username is empty. webAuth:" + webAuthName);
    }//from   w ww .java 2 s .com
    final String password = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".password");
    Credentials credentials;
    if (Constants.NTLM.equals(scheme)) {
        final String workstation = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".workstation");
        final String domain = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".domain");
        credentials = new NTCredentials(username, password == null ? StringUtil.EMPTY : password,
                workstation == null ? StringUtil.EMPTY : workstation,
                domain == null ? StringUtil.EMPTY : domain);
    } else {
        credentials = new UsernamePasswordCredentials(username, password == null ? StringUtil.EMPTY : password);
    }
    return credentials;
}

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;// ww  w  .j a  v a  2 s .  com
            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.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java

public void openConnectionInternal() {
    repository.setUrl(getURL(repository));

    localContext = HttpClientContext.create();
    credentialsProvider = new BasicCredentialsProvider();
    authCache = new BasicAuthCache();
    localContext.setCredentialsProvider(credentialsProvider);
    localContext.setAuthCache(authCache);

    if (authenticationInfo != null) {

        String username = authenticationInfo.getUserName();
        String password = authenticationInfo.getPassword();

        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
            Credentials creds = new UsernamePasswordCredentials(username, password);

            String host = getRepository().getHost();
            int port = getRepository().getPort();

            credentialsProvider.setCredentials(getBasicAuthScope().getScope(host, port), creds);
        }//from w w  w . j  a  v  a2  s .  c  o  m
    }

    ProxyInfo proxyInfo = getProxyInfo(getRepository().getProtocol(), getRepository().getHost());
    if (proxyInfo != null) {
        String proxyUsername = proxyInfo.getUserName();
        String proxyPassword = proxyInfo.getPassword();
        String proxyHost = proxyInfo.getHost();
        String proxyNtlmHost = proxyInfo.getNtlmHost();
        String proxyNtlmDomain = proxyInfo.getNtlmDomain();
        if (proxyHost != null) {
            if (proxyUsername != null && proxyPassword != null) {
                Credentials creds;
                if (proxyNtlmHost != null || proxyNtlmDomain != null) {
                    creds = new NTCredentials(proxyUsername, proxyPassword, proxyNtlmHost, proxyNtlmDomain);
                } else {
                    creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
                }

                int port = proxyInfo.getPort();

                AuthScope authScope = getProxyBasicAuthScope().getScope(proxyHost, port);
                credentialsProvider.setCredentials(authScope, creds);
            }
        }
    }
}

From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java

@NonNull
private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url,
        @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException {
    UserCredentials result = null;/*from  www .  ja  va 2 s .  c o m*/
    String realm = null;

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs);

    // use the simple one
    final DefaultHttpClient httpClient = new DefaultHttpClient(params);

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    final HttpGet httpGet = new HttpGet(url);
    if (inHeaders != null) {
        for (Header header : inHeaders) {
            httpGet.addHeader(header);
        }
    }

    // retrieve local java configured network in case there is the need to
    // authenticate a proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Set preference order for authentication options.
    // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in
    // servers that support both, as it is more secure. However, we don't seem to handle it
    // very well, so we leave it off the list.
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for
    // more info.
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.NTLM);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    if (DEBUG) {
        try {
            URI uri = new URI(url);
            ProxySelector sel = routePlanner.getProxySelector();
            if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$
                List<Proxy> list = sel.select(uri);
                System.out.printf("SdkLib.UrlOpener:\n  Connect to: %s\n  Proxy List: %s\n", //$NON-NLS-1$
                        url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$
            }
        } catch (Exception e) {
            System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$
                    url, e.toString());
        }
    }

    boolean trying = true;
    // loop while the response is being fetched
    while (trying) {
        // connect and get status code
        HttpResponse response = httpClient.execute(httpGet, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        if (DEBUG) {
            System.out.printf("  Status: %d\n", statusCode); //$NON-NLS-1$
        }

        // check whether any authentication is required
        AuthState authenticationState = null;
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // in case the status is OK and there is a realm and result,
            // cache it
            if (realm != null && result != null) {
                sRealmCache.put(realm, result);
            }
        }

        // there is the need for authentication
        if (authenticationState != null) {

            // get scope and realm
            AuthScope authScope = authenticationState.getAuthScope();

            // If the current realm is different from the last one it means
            // a pass was performed successfully to the last URL, therefore
            // cache the last realm
            if (realm != null && !realm.equals(authScope.getRealm())) {
                sRealmCache.put(realm, result);
            }

            realm = authScope.getRealm();

            // in case there is cache for this Realm, use it to authenticate
            if (sRealmCache.containsKey(realm)) {
                result = sRealmCache.get(realm);
            } else {
                // since there is no cache, request for login and password
                result = monitor.displayLoginCredentialsPrompt("Site Authentication",
                        "Please login to the following domain: " + realm
                                + "\n\nServer requiring authentication:\n" + authScope.getHost());
                if (result == null) {
                    throw new CanceledByUserException("User canceled login dialog.");
                }
            }

            // retrieve authentication data
            String user = result.getUserName();
            String password = result.getPassword();
            String workstation = result.getWorkstation();
            String domain = result.getDomain();

            // proceed in case there is indeed a user
            if (user != null && user.length() > 0) {
                Credentials credentials = new NTCredentials(user, password, workstation, domain);
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (trying) {
                // in case another pass to the Http Client will be performed, close the entity.
                entity.getContent().close();
            } else {
                // since no pass to the Http Client is needed, retrieve the
                // entity's content.

                // Note: don't use something like a BufferedHttpEntity since it would consume
                // all content and store it in memory, resulting in an OutOfMemory exception
                // on a large download.
                InputStream is = new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        // Since Http Client is no longer needed, close it.

                        // Bug #21167: we need to tell http client to shutdown
                        // first, otherwise the super.close() would continue
                        // downloading and not return till complete.

                        httpClient.getConnectionManager().shutdown();
                        super.close();
                    }
                };

                HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
                outResponse.setHeaders(response.getAllHeaders());
                outResponse.setLocale(response.getLocale());

                return Pair.of(is, outResponse);
            }
        } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // It's ok to not have an entity (e.g. nothing to download) for a 304
            HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
            outResponse.setHeaders(response.getAllHeaders());
            outResponse.setLocale(response.getLocale());

            return Pair.of(null, outResponse);
        }
    }

    // We get here if we did not succeed. Callers do not expect a null result.
    httpClient.getConnectionManager().shutdown();
    throw new FileNotFoundException(url);
}