Example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider.

Prototype

public synchronized final CredentialsProvider getCredentialsProvider() 

Source Link

Usage

From source file:pt.aptoide.backupapps.data.webservices.ManagerDownloads.java

private void download(ViewDownload download, boolean overwriteCache) {
    ViewCache localCache = download.getCache();
    ViewNotification notification = download.getNotification();

    boolean resuming = false;

    String localPath = localCache.getLocalPath();
    String remotePath = download.getRemotePath();
    int targetBytes;

    FileOutputStream fileOutputStream = null;

    try {/*from  www .  j a va2 s.c o  m*/
        fileOutputStream = new FileOutputStream(localPath, !overwriteCache);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used. 
        int timeoutConnection = Constants.SERVER_CONNECTION_TIMEOUT;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = Constants.SERVER_READ_TIMEOUT;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        httpClient.setParams(httpParameters);

        HttpGet httpGet = new HttpGet(remotePath);
        Log.d("Aptoide-download", "downloading from: " + remotePath + " to: " + localPath);
        Log.d("Aptoide-download",
                "downloading with: " + getUserAgentString() + "    private: " + download.isLoginRequired());

        httpGet.setHeader("User-Agent", getUserAgentString());

        String resumeLength = Long.toString(download.getCache().getFile().length());
        int resumeLengthInt = Integer.parseInt(resumeLength);
        if (!overwriteCache) {
            if (resumeLengthInt > 0) {
                resuming = true;
            }
            Log.d("Aptoide-download", "downloading from [bytes]: " + resumeLength);
            httpGet.setHeader("Range", "bytes=" + resumeLength + "-");
            notification.incrementProgress(resumeLengthInt);
        }

        if (download.isLoginRequired()) {
            URL url = new URL(remotePath);
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                    new UsernamePasswordCredentials(download.getLogin().getUsername(),
                            download.getLogin().getPassword()));
        }

        HttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse == null) {
            Log.d("Aptoide-ManagerDownloads", "Problem in network... retry...");
            httpResponse = httpClient.execute(httpGet);
            if (httpResponse == null) {
                Log.d("Aptoide-ManagerDownloads", "Major network exception... Exiting!");
                /*msg_al.arg1= 1;
                    download_error_handler.sendMessage(msg_al);*/
                if (!resuming) {
                    managerCache.clearCache(download.getCache());
                }
                throw new TimeoutException();
            }
        }

        int httpStatusCode = httpResponse.getStatusLine().getStatusCode();
        Log.d("Aptoide-download", "Server Response Status Code: " + httpStatusCode);

        switch (httpStatusCode) {
        case 401:
            fileOutputStream.close();
            if (!resuming) {
                managerCache.clearCache(download.getCache());
            }
            //                download.setFailReason(EnumDownloadFailReason.TIMEOUT);
            throw new TimeoutException(httpStatusCode + " " + httpResponse.getStatusLine().getReasonPhrase());
        case 403:
            fileOutputStream.close();
            if (!resuming) {
                managerCache.clearCache(download.getCache());
            }
            //                download.setFailReason(EnumDownloadFailReason.IP_BLACKLISTED);
            throw new AptoideExceptionDownload(
                    httpStatusCode + " " + httpResponse.getStatusLine().getReasonPhrase());
        case 404:
            fileOutputStream.close();
            if (!resuming) {
                managerCache.clearCache(download.getCache());
            }
            //                download.setFailReason(EnumDownloadFailReason.NOT_FOUND);
            throw new AptoideExceptionNotFound(
                    httpStatusCode + " " + httpResponse.getStatusLine().getReasonPhrase());
        case 416:
            fileOutputStream.close();
            if (!resuming) {
                managerCache.clearCache(download.getCache());
            }
            notification.setCompleted(true);
            //                try {
            //                  downloadStatusClient.updateDownloadStatus(cache.hashCode(), download);
            //               } catch (RemoteException e4) {
            //                  e4.printStackTrace();
            //               }
            return;

        default:

            Log.d("Aptoide-ManagerDownloads",
                    "Download target size: " + notification.getProgressCompletionTarget());

            //            if(download.isSizeKnown()){
            //               targetBytes = download.getSize()*Constants.KBYTES_TO_BYTES;   //TODO check if server sends kbytes or bytes
            //               notification.setProgressCompletionTarget(targetBytes);
            //            }else{

            if (httpResponse.containsHeader("Content-Length") && resumeLengthInt != 0) {
                targetBytes = Integer.parseInt(httpResponse.getFirstHeader("Content-Length").getValue());
                Log.d("Aptoide-ManagerDownloads", "targetBytes: " + targetBytes);
                //               notification.setProgressCompletionTarget(targetBytes);
            }
            //            }

            InputStream inputStream = null;

            if ((httpResponse.getEntity().getContentEncoding() != null)
                    && (httpResponse.getEntity().getContentEncoding().getValue().equalsIgnoreCase("gzip"))) {

                Log.d("Aptoide-ManagerDownloads", "with gzip");
                inputStream = new GZIPInputStream(httpResponse.getEntity().getContent());

            } else {

                //               Log.d("Aptoide-ManagerDownloads","No gzip");
                inputStream = httpResponse.getEntity().getContent();

            }

            byte data[] = new byte[8096];
            int bytesRead;

            while ((bytesRead = inputStream.read(data, 0, 8096)) > 0) {
                notification.incrementProgress(bytesRead);
                fileOutputStream.write(data, 0, bytesRead);
            }
            Log.d("Aptoide-ManagerDownloads",
                    "Download done! Name: " + notification.getActionsTargetName() + " localPath: " + localPath);
            notification.setCompleted(true);
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();

            if (localCache.hasMd5Sum()) {
                if (!getManagerCache().md5CheckOk(localCache)) {
                    managerCache.clearCache(download.getCache());
                    throw new AptoideExceptionDownload("md5 check failed!");
                }
            }
            return;
        }
    } catch (Exception e) {
        try {
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e1) {
        }
        e.printStackTrace();
        if (notification.getNotificationType().equals(EnumNotificationTypes.GET_APP)
                && download.getCache().getFile().length() > 0) {
            notification.setCompleted(true);
            serviceData.scheduleInstallApp(notification.getTargetsHashid());
        }
        throw new AptoideExceptionDownload(e);
    }
}

From source file:org.lightcouch.CouchDbClientBase.java

/**
 * @return {@link DefaultHttpClient} instance.
 *//*from w w  w .ja v  a2s  . c o  m*/
private HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
        SchemeSocketFactory ssf = null;
        if (props.getProtocol().equals("https")) {
            TrustManager trustManager = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { trustManager }, null);
            ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            SSLSocket socket = (SSLSocket) ssf.createSocket(null);
            socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });
        } else {
            ssf = PlainSocketFactory.getSocketFactory();
        }
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf));
        PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
        httpclient = new DefaultHttpClient(ccm);
        host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol());
        context = new BasicHttpContext();
        // Http params
        httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                props.getConnectionTimeout());
        int maxConnections = props.getMaxConnections();
        if (maxConnections != 0) {
            ccm.setMaxTotal(maxConnections);
            ccm.setDefaultMaxPerRoute(maxConnections);
        }
        if (props.getProxyHost() != null) {
            HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        // basic authentication
        if (props.getUsername() != null && props.getPassword() != null) {
            httpclient.getCredentialsProvider().setCredentials(new AuthScope(props.getHost(), props.getPort()),
                    new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
            props.clearPassword();
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(host, basicAuth);
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }
        // request interceptor
        httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context) throws IOException {
                if (log.isInfoEnabled())
                    log.info(">> " + request.getRequestLine());
            }
        });
        // response interceptor
        httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context) throws IOException {
                validate(response);
                if (log.isInfoEnabled())
                    log.info("<< Status: " + response.getStatusLine().getStatusCode());
            }
        });
    } catch (Exception e) {
        log.error("Error Creating HTTP client. " + e.getMessage());
        throw new IllegalStateException(e);
    }
    return httpclient;
}

From source file:com.cloudbees.eclipse.core.util.Utils.java

/**
 * @param url/*  www . java  2 s.  co m*/
 *          url to connec. Required to determine proxy settings if available. If <code>null</code> then proxy is not
 *          configured for the client returned.
 * @return
 * @throws CloudBeesException
 */
public final static DefaultHttpClient getAPIClient(String url) throws CloudBeesException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpClientParams.setCookiePolicy(httpclient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);

        String version = null;
        if (CloudBeesCorePlugin.getDefault() != null) {
            version = CloudBeesCorePlugin.getDefault().getBundle().getVersion().toString();
        } else {
            version = "n/a";
        }
        HttpProtocolParams.setUserAgent(httpclient.getParams(), "CBEclipseToolkit/" + version);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

        CloudBeesCorePlugin plugin = CloudBeesCorePlugin.getDefault();

        URL truststore;

        if (plugin == null) {
            //Outside the OSGI environment, try to open the stream from the current dir.
            truststore = new File("truststore").toURI().toURL();
        } else {
            truststore = plugin.getBundle().getResource("truststore");
        }

        InputStream instream = truststore.openStream();

        try {
            trustStore.load(instream, "123456".toCharArray());
        } finally {
            instream.close();
        }

        TrustStrategy trustAllStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
                return true;
            }
        };

        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustStore,
                null, trustAllStrategy, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        // Override https handling to use provided truststore
        @SuppressWarnings("deprecation")
        Scheme sch = new Scheme("https", socketFactory, 443);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

        HttpParams params = httpclient.getParams();

        //TODO Make configurable from the UI?
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        if (CloudBeesCorePlugin.getDefault() != null) { // exclude proxy support when running outside eclipse
            IProxyService ps = CloudBeesCorePlugin.getDefault().getProxyService();
            if (ps.isProxiesEnabled()) {

                IProxyData[] pr = ps.select(new URI(url));

                //NOTE! For now we use just the first proxy settings with type HTTP or HTTPS to try out the connection. If configuration has more than 1 conf then for now this likely won't work!
                if (pr != null) {
                    for (int i = 0; i < pr.length; i++) {

                        IProxyData prd = pr[i];

                        if (IProxyData.HTTP_PROXY_TYPE.equals(prd.getType())
                                || IProxyData.HTTPS_PROXY_TYPE.equals(prd.getType())) {

                            String proxyHost = prd.getHost();
                            int proxyPort = prd.getPort();
                            String proxyUser = prd.getUserId();
                            String proxyPass = prd.getPassword();

                            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                            if (prd.isRequiresAuthentication()) {
                                List authpref = new ArrayList();
                                authpref.add(AuthPolicy.BASIC);
                                AuthScope authScope = new AuthScope(proxyHost, proxyPort);
                                httpclient.getCredentialsProvider().setCredentials(authScope,
                                        new UsernamePasswordCredentials(proxyUser, proxyPass));
                            }

                            break;

                        }

                    }
                }
            }
        }

        /*      httpclient.getHostConfiguration().setProxy(proxyHost,proxyPort);      
              //if there are proxy credentials available, set those too
              Credentials proxyCredentials = null;
              String proxyUser = beesClientConfiguration.getProxyUser();
              String proxyPassword = beesClientConfiguration.getProxyPassword();
              if(proxyUser != null || proxyPassword != null)
        proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
              if(proxyCredentials != null)
        client.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials);
                
        */

        return httpclient;

    } catch (Exception e) {
        throw new CloudBeesException("Error while initiating access to JSON APIs!", e);
    }
}

From source file:com.android.sdklib.internal.repository.UrlOpener.java

private static InputStream openWithHttpClient(String url, ITaskMonitor monitor)
        throws IOException, ClientProtocolException, CanceledByUserException {
    UserCredentials result = null;/*from ww w.  ja  v a2  s  .  c o  m*/
    String realm = null;

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

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpget = new HttpGet(url);

    // 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);

    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();

        // 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) {
            // 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.

                return new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        super.close();

                        // since Http Client is no longer needed, close it
                        httpClient.getConnectionManager().shutdown();
                    }
                };
            }
        }
    }

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

From source file:org.dasein.cloud.vcloud.vCloudMethod.java

protected @Nonnull HttpClient getClient(boolean forAuthentication) throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new CloudException("No context was defined for this request");
    }/*from w  w w .j  av  a  2 s .  c o  m*/
    String endpoint = ctx.getCloud().getEndpoint();

    if (endpoint == null) {
        throw new CloudException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");
    int targetPort;
    URI uri;

    try {
        uri = new URI(endpoint);
        targetPort = uri.getPort();
        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new CloudException(e);
    }
    HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme());
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");

    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (provider.isInsecure()) {
        try {
            client.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {

                        public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                                throws CertificateException {
                            return true;
                        }
                    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    if (forAuthentication) {
        String accessPublic = null;
        String accessPrivate = null;
        try {
            List<ContextRequirements.Field> fields = provider.getContextRequirements().getConfigurableValues();
            for (ContextRequirements.Field f : fields) {
                if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                    byte[][] keyPair = (byte[][]) provider.getContext().getConfigurationValue(f);
                    accessPublic = new String(keyPair[0], "utf-8");
                    accessPrivate = new String(keyPair[1], "utf-8");
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
        String password = accessPrivate;
        String userName;

        if (matches(getAPIVersion(), "0.8", "0.8")) {
            userName = accessPublic;
        } else {
            userName = accessPublic + "@" + ctx.getAccountNumber();
        }

        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));
    }
    return client;
}

From source file:de.betterform.connector.http.AbstractHTTPConnector.java

protected void execute(HttpRequestBase httpRequestBase) throws Exception {
    //      (new HttpClient()).executeMethod(httpMethod);
    //HttpClient client = new HttpClient();
    HttpParams httpParams = new BasicHttpParams();

    DefaultHttpClient client = ConnectorFactory.getFactory().getHttpClient(httpParams);

    if (!getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) {
        LOGGER.debug("SSL_CUSTOM_SCHEME");
        LOGGER.debug("SSL_CUSTOM_SCHEME: Factory: "
                + Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT));
        String contextPath = Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT);
        if (contextPath != null) {
            initSSLScheme(contextPath);//w  w  w  . ja  va 2 s .c o m
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("context params>>>");
        Map map = getContext();
        Iterator keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next().toString();
            Object value = map.get(key);
            if (value != null)
                LOGGER.debug(key + "=" + value.toString());
        }
        LOGGER.debug("<<<end params");
    }
    String username = null;
    String password = null;
    String realm = null;

    //add custom header to signal XFormsFilter to not process this internal request
    //httpMethod.setRequestHeader(BetterFORMConstants.BETTERFORM_INTERNAL,"true");
    httpRequestBase.addHeader(BetterFORMConstants.BETTERFORM_INTERNAL, "true");

    /// *** copy all keys in map HTTP_REQUEST_HEADERS as http-submissionHeaders
    if (getContext().containsKey(HTTP_REQUEST_HEADERS)) {
        RequestHeaders httpRequestHeaders = (RequestHeaders) getContext().get(HTTP_REQUEST_HEADERS);

        // Iterator it =
        Map headersToAdd = new HashMap();
        for (RequestHeader header : httpRequestHeaders.getAllHeaders()) {
            String headername = header.getName();
            String headervalue = header.getValue();

            if (headername.equals("username")) {
                username = headervalue;
            } else if (headername.equals("password")) {
                password = headervalue;
            } else if (headername.equals("realm")) {
                realm = headervalue;
            } else {
                if (headersToAdd.containsKey(headername)) {
                    String formerValue = (String) headersToAdd.get(headername);
                    headersToAdd.put(headername, formerValue + "," + headervalue);
                } else {
                    if (headername.equals("accept-encoding")) {
                        // do nothing
                        LOGGER.debug("do not add accept-encoding:" + headervalue + " for request");
                    } else {
                        headersToAdd.put(headername, headervalue);
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug("setting header: " + headername + " value: " + headervalue);
                        }
                    }
                }
            }
        }
        Iterator keyIterator = headersToAdd.keySet().iterator();
        while (keyIterator.hasNext()) {
            String key = (String) keyIterator.next();
            //httpMethod.setRequestHeader(new Header(key,(String) headersToAdd.get(key)));
            httpRequestBase.setHeader(key, (String) headersToAdd.get(key));
            //httpRequestBase.addHeader(key, (String) headersToAdd.get(key));
        }
    }
    if (httpRequestBase.containsHeader("Content-Length")) {
        //remove content-length if present httpclient will recalucalte the value.
        httpRequestBase.removeHeaders("Content-Length");
    }
    if (username != null && password != null) {
        URI targetURI = null;
        //targetURI = httpMethod.getURI();
        targetURI = httpRequestBase.getURI();
        //client.getParams().setAuthenticationPreemptive(true);

        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        if (realm == null) {
            realm = AuthScope.ANY_REALM;
        }
        //client.getState().setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds);
        client.getCredentialsProvider()
                .setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds);
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();

        authCache.put(new HttpHost(targetURI.getHost()), basicAuth);
        BasicHttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        //Needed? httpMethod.setDoAuthentication(true);

    }
    //alternative method for non-tomcat servers
    if (getContext().containsKey(REQUEST_COOKIE)) {
        //HttpState state = client.getState();
        HttpParams state = client.getParams();

        //state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
        state.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        if (getContext().get(REQUEST_COOKIE) instanceof Cookie[]) {
            Cookie[] cookiesIn = (Cookie[]) getContext().get(REQUEST_COOKIE);
            if (cookiesIn[0] != null) {
                for (int i = 0; i < cookiesIn.length; i++) {
                    Cookie cookie = cookiesIn[i];
                    //state.addCookie(cookie);
                    client.getCookieStore().addCookie(cookie);
                }
                /*
                  Cookie[] cookies = state.getCookies();
                        
                Header cookieOut = new CookieSpecBase().formatCookieHeader(cookies);
                httpMethod.setRequestHeader(cookieOut);
                client.setState(state);
                  */
                List<Cookie> cookies = client.getCookieStore().getCookies();
                List<Header> cookieHeaders = new BrowserCompatSpec().formatCookies(cookies);
                Header[] headers = cookieHeaders.toArray(new Header[0]);

                for (int i = 0; i < headers.length; i++) {
                    httpRequestBase.addHeader(headers[i]);
                }

                client.setParams(state);
            }
        } else {
            throw new MalformedCookieException(
                    "Cookies must be passed as org.apache.commons.httpclient.Cookie objects.");
        }
    }

    if (getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) {
        LOGGER.debug("Using customSSL-Protocol-Handler");
        Iterator<Scheme> schemes = ((Vector<Scheme>) getContext().get(AbstractHTTPConnector.SSL_CUSTOM_SCHEME))
                .iterator();

        while (schemes.hasNext()) {
            client.getConnectionManager().getSchemeRegistry().register(schemes.next());
        }
    }

    if (httpRequestBase.getURI().isAbsolute()) {
        httpRequestBase.setHeader("host", httpRequestBase.getURI().getHost());
    }

    HttpResponse httpResponse = client.execute(httpRequestBase);
    statusCode = httpResponse.getStatusLine().getStatusCode();
    reasonPhrase = httpResponse.getStatusLine().getReasonPhrase();
    try {
        if (statusCode >= 300) {
            // Allow 302 only
            if (statusCode != 302) {
                throw new XFormsInternalSubmitException(statusCode, reasonPhrase,
                        EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR);
            }
        }
        this.handleHttpMethod(httpResponse);
    } catch (Exception e) {

        LOGGER.trace("AbstractHTTPConnector Exception: ", e);
        try {
            throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase(),
                    EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR);
        } catch (IOException e1) {
            throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase(), XFormsConstants.RESOURCE_ERROR);
        }
    }

}

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;// ww  w  . ja v a 2 s.  c  om
    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);
}