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:org.opensaml.util.http.HttpClientBuilder.java

/**
 * Constructs an {@link HttpClient} using the settings of this builder.
 * /*from   w  w  w. j  a va2s.c  om*/
 * @return the constructed client
 */
public HttpClient buildClient() {
    final DefaultHttpClient client = new DefaultHttpClient(buildConnectionManager());
    client.addRequestInterceptor(new RequestAcceptEncoding());
    client.addResponseInterceptor(new ResponseContentEncoding());

    final HttpParams httpParams = client.getParams();

    if (socketLocalAddress != null) {
        httpParams.setParameter(AllClientPNames.LOCAL_ADDRESS, socketLocalAddress);
    }

    if (socketTimeout > 0) {
        httpParams.setIntParameter(AllClientPNames.SO_TIMEOUT, socketTimeout);
    }

    httpParams.setIntParameter(AllClientPNames.SOCKET_BUFFER_SIZE, socketBufferSize);

    if (connectionTimeout > 0) {
        httpParams.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, connectionTimeout);
    }

    httpParams.setBooleanParameter(AllClientPNames.STALE_CONNECTION_CHECK, connectionStalecheck);

    if (connectionProxyHost != null) {
        final HttpHost proxyHost = new HttpHost(connectionProxyHost, connectionProxyPort);
        httpParams.setParameter(AllClientPNames.DEFAULT_PROXY, proxyHost);

        if (connectionProxyUsername != null && connectionProxyPassword != null) {
            final CredentialsProvider credProvider = client.getCredentialsProvider();
            credProvider.setCredentials(new AuthScope(connectionProxyHost, connectionProxyPort),
                    new UsernamePasswordCredentials(connectionProxyUsername, connectionProxyPassword));
        }
    }

    httpParams.setBooleanParameter(AllClientPNames.HANDLE_REDIRECTS, httpFollowRedirects);

    httpParams.setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, httpContentCharSet);

    return client;
}

From source file:com.naryx.tagfusion.cfm.document.cfDOCUMENT.java

private String retrieveHttp(cfSession _Session, String _src, DocumentSection _section,
        DocumentSettings _defaultSettings) throws dataNotSupportedException, cfmRunTimeException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet method = new HttpGet();

    try {/*from   w w w .  j ava2  s  .c  o  m*/
        method.setURI(new URI(_src));
        if (_section.getUserAgent() != null) {
            method.setHeader("User-Agent", _section.getUserAgent());
        } else {
            method.setHeader("User-Agent", _defaultSettings.getUserAgent());
        }

        // HTTP basic authentication
        if (_section.getAuthPassword() != null) {
            httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(_section.getAuthUser(), _section.getAuthPassword()));
        }

        // proxy support
        if (_defaultSettings.getProxyHost() != null) {
            HttpHost proxy = new HttpHost(_defaultSettings.getProxyHost(), _defaultSettings.getProxyPort());
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (_defaultSettings.getProxyUser() != null) {
                httpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(_defaultSettings.getProxyHost(), _defaultSettings.getProxyPort()),
                        new UsernamePasswordCredentials(_defaultSettings.getProxyUser(),
                                _defaultSettings.getProxyPassword()));
            }
        }

        HttpResponse response;
        response = httpClient.execute(method);

        if (response.getStatusLine().getStatusCode() == 200) {
            String charset = null;
            Header contentType = response.getFirstHeader("Content-type");
            if (contentType != null) {
                String value = contentType.getValue();
                int indx = value.indexOf("charset=");
                if (indx > 0) {
                    charset = value.substring(indx + 8).trim();
                }
            }
            return handleDocument(_Session, response.getEntity().getContent(), charset);
        } else {
            throw newRunTimeException("Failed to retrieve document from source. HTTP status code "
                    + response.getStatusLine().getStatusCode() + " was returned");
        }

        //   throw newRunTimeException( "Failed to retrieve document from " + _src + " due to HttpException: " + e.getMessage() );
    } catch (URISyntaxException e) {
        throw newRunTimeException("Error retrieving document via http: " + e.getMessage());

    } catch (IOException e) {
        throw newRunTimeException("Error retrieving document via http: " + e.getMessage());
    }

}

From source file:com.mediaexplorer.remote.MexRemoteActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//from   ww  w .j a  v  a  2 s  .  c om

    this.setTitle(R.string.app_name);
    dbg = "MexWebremote";

    text_view = (TextView) findViewById(R.id.text);

    web_view = (WebView) findViewById(R.id.link_view);
    web_view.getSettings().setJavaScriptEnabled(true);/*
                                                      /* Future: setOverScrollMode is API level >8
                                                      * web_view.setOverScrollMode (OVER_SCROLL_NEVER);
                                                      */

    web_view.setBackgroundColor(0);

    web_view.setWebViewClient(new WebViewClient() {
        /* for some reason we only get critical errors so an auth error
         * is not handled here which is why there is some crack that test
         * the connection with a special httpclient
         */
        @Override
        public void onReceivedHttpAuthRequest(final WebView view, final HttpAuthHandler handler,
                final String host, final String realm) {
            String[] userpass = new String[2];

            userpass = view.getHttpAuthUsernamePassword(host, realm);

            HttpResponse response = null;
            HttpGet httpget;
            DefaultHttpClient httpclient;
            String target_host;
            int target_port;

            target_host = MexRemoteActivity.this.target_host;
            target_port = MexRemoteActivity.this.target_port;

            /* We may get null from getHttpAuthUsernamePassword which will
             * break the setCredentials so junk used instead to keep
             * it happy.
             */

            Log.d(dbg, "using the set httpauth, testing auth using client");
            try {
                if (userpass == null) {
                    userpass = new String[2];
                    userpass[0] = "none";
                    userpass[1] = "none";
                }
            } catch (Exception e) {
                userpass = new String[2];
                userpass[0] = "none";
                userpass[1] = "none";
            }

            /* Log.d ("debug",
             *  "trying: GET http://"+userpass[0]+":"+userpass[1]+"@"+target_host+":"+target_port+"/");
             */
            /* We're going to test the authentication credentials that we
             * have before using them so that we can act on the response.
             */

            httpclient = new DefaultHttpClient();

            httpget = new HttpGet("http://" + target_host + ":" + target_port + "/");

            httpclient.getCredentialsProvider().setCredentials(new AuthScope(target_host, target_port),
                    new UsernamePasswordCredentials(userpass[0], userpass[1]));

            try {
                response = httpclient.execute(httpget);
            } catch (IOException e) {
                Log.d(dbg, "Problem executing the http get");
                e.printStackTrace();
            }

            Log.d(dbg, "HTTP reponse:" + Integer.toString(response.getStatusLine().getStatusCode()));
            if (response.getStatusLine().getStatusCode() == 401) {
                /* We got Authentication failed (401) so ask user for u/p */

                /* login dialog box */
                final AlertDialog.Builder logindialog;
                final EditText user;
                final EditText pass;

                LinearLayout layout;
                LayoutParams params;

                TextView label_username;
                TextView label_password;

                logindialog = new AlertDialog.Builder(MexRemoteActivity.this);

                logindialog.setTitle("Mex Webremote login");

                user = new EditText(MexRemoteActivity.this);
                pass = new EditText(MexRemoteActivity.this);

                layout = new LinearLayout(MexRemoteActivity.this);

                pass.setTransformationMethod(new PasswordTransformationMethod());

                layout.setOrientation(LinearLayout.VERTICAL);

                params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

                layout.setLayoutParams(params);
                user.setLayoutParams(params);
                pass.setLayoutParams(params);

                label_username = new TextView(MexRemoteActivity.this);
                label_password = new TextView(MexRemoteActivity.this);

                label_username.setText("Username:");
                label_password.setText("Password:");

                layout.addView(label_username);
                layout.addView(user);
                layout.addView(label_password);
                layout.addView(pass);
                logindialog.setView(layout);

                logindialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });

                logindialog.setPositiveButton("Login", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String uvalue = user.getText().toString().trim();
                        String pvalue = pass.getText().toString().trim();
                        view.setHttpAuthUsernamePassword(host, realm, uvalue, pvalue);

                        handler.proceed(uvalue, pvalue);
                    }
                });
                logindialog.show();
                /* End login dialog box */
            } else /* We didn't get a 401 */
            {
                handler.proceed(userpass[0], userpass[1]);
            }
        } /* End onReceivedHttpAuthRequest */
    }); /* End Override */

    /* Run mdns to check for service in a "runnable" (async) */
    handler.post(new Runnable() {
        public void run() {
            startMdns();
        }
    });

    dialog = ProgressDialog.show(MexRemoteActivity.this, "", "Searching...", true);

    /* Let's put something in the webview while we're waiting */
    String summary = "<html><head><style>body { background-color: #000000; color: #ffffff; }></style></head><body><p>Searching for the media explorer webservice</p><p>More infomation on <a href=\"http://media-explorer.github.com\" >Media Explorer's home page</a></p></body></html>";
    web_view.loadData(summary, "text/html", "utf-8");

}

From source file:jetbrains.buildServer.commitPublisher.github.api.impl.HttpClientWrapperImpl.java

private void setupProxy(DefaultHttpClient httpclient) {
    final String httpProxy = TeamCityProperties.getProperty("teamcity.github.http.proxy.host");
    if (StringUtil.isEmptyOrSpaces(httpProxy))
        return;/*from w w w .  j a  v  a  2s.  co m*/

    final int httpProxyPort = TeamCityProperties.getInteger("teamcity.github.http.proxy.port", -1);
    if (httpProxyPort <= 0)
        return;

    LOG.info("TeamCity.GitHub will use proxy: " + httpProxy + ", port " + httpProxyPort);
    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(httpProxy, httpProxyPort));

    final String httpProxyUser = TeamCityProperties.getProperty("teamcity.github.http.proxy.user");
    final String httpProxyPassword = TeamCityProperties.getProperty("teamcity.github.http.proxy.password");
    final String httpProxyDomain = TeamCityProperties.getProperty("teamcity.github.http.proxy.domain");
    final String httpProxyWorkstation = TeamCityProperties
            .getProperty("teamcity.github.http.proxy.workstation");

    if (StringUtil.isEmptyOrSpaces(httpProxyUser) || StringUtil.isEmptyOrSpaces(httpProxyPassword))
        return;

    final Credentials creds;
    if (StringUtil.isEmptyOrSpaces(httpProxyDomain) || StringUtil.isEmptyOrSpaces(httpProxyWorkstation)) {
        LOG.info("TeamCity.GitHub will use proxy credentials: " + httpProxyUser);
        creds = new UsernamePasswordCredentials(httpProxyUser, httpProxyPassword);
    } else {
        LOG.info("TeamCity.GitHub will use proxy NT credentials: " + httpProxyDomain + "/" + httpProxyUser);
        creds = new NTCredentials(httpProxyUser, httpProxyPassword, httpProxyWorkstation, httpProxyDomain);
    }

    httpclient.getCredentialsProvider().setCredentials(new AuthScope(httpProxy, httpProxyPort), creds);
}

From source file:org.apache.cloudstack.storage.datastore.util.SolidFireUtil.java

private static String executeJsonRpc(SolidFireConnection sfConnection, String strJsonToExecute) {
    DefaultHttpClient httpClient = null;
    StringBuilder sb = new StringBuilder();

    try {/*  w  w w.  java2  s. co  m*/
        StringEntity input = new StringEntity(strJsonToExecute);

        input.setContentType("application/json");

        httpClient = getHttpClient(sfConnection.getManagementPort());

        URI uri = new URI("https://" + sfConnection.getManagementVip() + ":" + sfConnection.getManagementPort()
                + "/json-rpc/6.0");
        AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_SCHEME);
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                sfConnection.getClusterAdminUsername(), sfConnection.getClusterAdminPassword());

        httpClient.getCredentialsProvider().setCredentials(authScope, credentials);

        HttpPost postRequest = new HttpPost(uri);

        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (!isSuccess(response.getStatusLine().getStatusCode())) {
            throw new CloudRuntimeException("Failed on JSON-RPC API call. HTTP error code = "
                    + response.getStatusLine().getStatusCode());
        }

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));) {
            String strOutput;
            while ((strOutput = br.readLine()) != null) {
                sb.append(strOutput);
            }
        } catch (IOException ex) {
            throw new CloudRuntimeException(ex.getMessage());
        }
    } catch (UnsupportedEncodingException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (ClientProtocolException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (IOException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (URISyntaxException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } finally {
        if (httpClient != null) {
            try {
                httpClient.getConnectionManager().shutdown();
            } catch (Exception t) {
                s_logger.info("[ignored]" + "error shutting down http client: " + t.getLocalizedMessage());
            }
        }
    }

    return sb.toString();
}

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

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

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

    FileOutputStream fileOutputStream = null;

    try {// w w w  . j  a va  2  s.  co m
        fileOutputStream = new FileOutputStream(localPath, !overwriteCache);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(remotePath);
        Log.d("Aptoide-download", "downloading from: " + remotePath + " to: " + localPath);
        //         Log.d("Aptoide-download","downloading with: "+getUserAgentString()+" login: "+download.isLoginRequired());

        //         httpGet.setHeader("User-Agent", getUserAgentString());   //TODO is consistently getting 404 from server

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

        if (download.isLoginRequired()) { //TODO refactor using username/password args when using webservices (only exception left is when getting hard-disk files)
            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);*/
                throw new TimeoutException();
            }
        }

        if (httpResponse.getStatusLine().getStatusCode() == 401) {
            Log.d("Aptoide-ManagerDownloads", "401 Time out!");
            fileOutputStream.close();
            managerCache.clearCache(download.getCache());
            throw new TimeoutException();
        } else if (httpResponse.getStatusLine().getStatusCode() == 404) {
            fileOutputStream.close();
            managerCache.clearCache(download.getCache());
            throw new AptoideExceptionNotFound("404 Not found!");
        } else {

            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()) {
                getManagerCache().md5CheckOk(localCache);
                //TODO md5check boolean return handle  by  raising exception
            }

        }
    } 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.apache.maven.plugin.javadoc.JavadocUtil.java

/**
 * Creates a new {@code HttpClient} instance.
 *
 * @param settings The settings to use for setting up the client or {@code null}.
 * @param url The {@code URL} to use for setting up the client or {@code null}.
 *
 * @return A new {@code HttpClient} instance.
 *
 * @see #DEFAULT_TIMEOUT/*w ww . j  av a 2  s  .  c om*/
 * @since 2.8
 */
private static HttpClient createHttpClient(Settings settings, URL url) {
    DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_TIMEOUT);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_TIMEOUT);
    httpClient.getParams().setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // Some web servers don't allow the default user-agent sent by httpClient
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");

    if (settings != null && settings.getActiveProxy() != null) {
        Proxy activeProxy = settings.getActiveProxy();

        ProxyInfo proxyInfo = new ProxyInfo();
        proxyInfo.setNonProxyHosts(activeProxy.getNonProxyHosts());

        if (StringUtils.isNotEmpty(activeProxy.getHost())
                && (url == null || !ProxyUtils.validateNonProxyHosts(proxyInfo, url.getHost()))) {
            HttpHost proxy = new HttpHost(activeProxy.getHost(), activeProxy.getPort());
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (StringUtils.isNotEmpty(activeProxy.getUsername()) && activeProxy.getPassword() != null) {
                Credentials credentials = new UsernamePasswordCredentials(activeProxy.getUsername(),
                        activeProxy.getPassword());

                httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
            }
        }
    }

    return httpClient;
}