Example usage for org.apache.http.auth AuthScope ANY_PORT

List of usage examples for org.apache.http.auth AuthScope ANY_PORT

Introduction

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

Prototype

int ANY_PORT

To view the source code for org.apache.http.auth AuthScope ANY_PORT.

Click Source Link

Document

The -1 value represents any port.

Usage

From source file:github.madmarty.madsonic.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    SharedPreferences prefs = Util.getPreferences(context);
    int networkTimeout = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT, "15000"));
    HttpParams newParams = httpClient.getParams();
    HttpConnectionParams.setSoTimeout(newParams, networkTimeout);
    httpClient.setParams(newParams);//  ww  w.  j ava 2s  . c o  m

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Set credentials to get through apache proxies that require authentication.
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:net.sourceforge.kalimbaradio.androidapp.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    LOG.info("Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;//  w w  w .ja  v  a  2 s.c o  m
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            LOG.debug("Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Set credentials to get through apache proxies that require authentication.
        ServerSettingsManager.ServerSettings server = Util.getActiveServer(context);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(server.getUsername(), server.getPassword()));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            LOG.warn("Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:org.webservice.fotolia.FotoliaApi.java

/**
 * Construct and returns a usuable http client
 *
 * @param  auto_refresh_token// w w w .j a  v  a  2 s  .  com
 * @return DefaultHttpClient
 */
private DefaultHttpClient _getHttpClient(final boolean auto_refresh_token) {
    DefaultHttpClient client;

    client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(this._api_key, this._getSessionId(auto_refresh_token)));

    HttpConnectionParams.setConnectionTimeout(client.getParams(), FotoliaApi.API_CONNECT_TIMEOUT * 1000);
    HttpConnectionParams.setSoTimeout(client.getParams(), FotoliaApi.API_PROCESS_TIMEOUT * 1000);

    return client;
}

From source file:de.escidoc.core.common.business.fedora.FedoraUtility.java

/**
 * Returns a HttpClient object configured with credentials to access Fedora URLs.
 * //from w w w.ja  v a  2s. co  m
 * @return A HttpClient object configured with credentials to access Fedora URLs.
 * @throws de.escidoc.core.common.exceptions.system.WebserverSystemException
 */
DefaultHttpClient getHttpClient() throws WebserverSystemException {
    try {
        if (this.httpClient == null) {
            final HttpParams params = new BasicHttpParams();
            ConnManagerParams.setMaxTotalConnections(params, HTTP_MAX_TOTAL_CONNECTIONS);

            final ConnPerRoute connPerRoute = new ConnPerRouteBean(HTTP_MAX_CONNECTIONS_PER_HOST);
            ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

            final Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
            final SchemeRegistry sr = new SchemeRegistry();
            sr.register(http);
            final ClientConnectionManager cm = new ThreadSafeClientConnManager(params, sr);

            this.httpClient = new DefaultHttpClient(cm, params);
            final URL url = new URL(this.fedoraUrl);
            final CredentialsProvider credsProvider = new BasicCredentialsProvider();

            final AuthScope authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            final Credentials creds = new UsernamePasswordCredentials(this.fedoraUser, this.fedoraPassword);
            credsProvider.setCredentials(authScope, creds);

            httpClient.setCredentialsProvider(credsProvider);
        }

        // don't wait for auth request
        final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

            @Override
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {

                final AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                final CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                final HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                // If not auth scheme has been initialized yet
                if (authState.getAuthScheme() == null) {
                    final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    // Obtain credentials matching the target host
                    final Credentials creds = credsProvider.getCredentials(authScope);
                    // If found, generate BasicScheme preemptively
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }

        };

        httpClient.addRequestInterceptor(preemptiveAuth, 0);

        // try only BASIC auth; skip to test NTLM and DIGEST

        return this.httpClient;
    } catch (final MalformedURLException e) {
        throw new WebserverSystemException("Fedora URL from configuration malformed.", e);
    }
}

From source file:github.daneren2005.dsub.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    // Strip out sensitive information from log
    Log.i(TAG, "Using URL " + url.substring(0, url.indexOf("?u=") + 1) + url.substring(url.indexOf("&v=") + 1));

    SharedPreferences prefs = Util.getPreferences(context);
    int networkTimeout = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT, "15000"));
    HttpParams newParams = httpClient.getParams();
    HttpConnectionParams.setSoTimeout(newParams, networkTimeout);
    httpClient.setParams(newParams);/*from   ww  w  . j ava2 s.  co m*/

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                cancelled.set(true);
                                request.abort();
                            } catch (Exception e) {
                                Log.e(TAG, "Failed to stop http task");
                            }
                        }
                    }).start();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Set credentials to get through apache proxies that require authentication.
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:com.knowgate.dfs.FileSystem.java

/**
 * <p>Read a binary file into a byte array</p>
 * @param sFilePath Full path of file to be readed. Like "file:///tmp/myfile.txt" or "ftp://myhost:21/dir/myfile.txt"
 * @return byte array with full contents of file
 * @throws FileNotFoundException/*from  w  w w . j  a  v  a2s. c o m*/
 * @throws IOException
 * @throws OutOfMemoryError
 * @throws MalformedURLException
 * @throws FTPException
 */
public byte[] readfilebin(String sFilePath)
        throws MalformedURLException, FTPException, FileNotFoundException, IOException, OutOfMemoryError {

    if (DebugFile.trace) {
        DebugFile.writeln("Begin FileSystem.readfilebin(" + sFilePath + ")");
        DebugFile.incIdent();
    }

    byte[] aRetVal;
    String sLower = sFilePath.toLowerCase();

    if (sLower.startsWith("file://"))
        sFilePath = sFilePath.substring(7);

    if (sLower.startsWith("http://") || sLower.startsWith("https://")) {

        URL oUrl = new URL(sFilePath);

        if (user().equals("anonymous") || user().length() == 0) {
            ByteArrayOutputStream oStrm = new ByteArrayOutputStream();
            if (DebugFile.trace)
                DebugFile.writeln("new DataHandler(" + oUrl.toString() + ")");
            DataHandler oHndlr = new DataHandler(oUrl);
            oHndlr.writeTo(oStrm);
            aRetVal = oStrm.toByteArray();
            oStrm.close();
        } else {
            if (null == oHttpCli) {
                oHttpCli = new DefaultHttpClient();
            } // fi (oHttpCli)

            oHttpCli.getCredentialsProvider().setCredentials(
                    new AuthScope(oUrl.getHost(), AuthScope.ANY_PORT, realm()),
                    new UsernamePasswordCredentials(user(), password()));
            HttpGet oGet = null;
            try {
                oGet = new HttpGet(sFilePath);
                HttpResponse oResp = oHttpCli.execute(oGet);
                HttpEntity oEnty = oResp.getEntity();
                int nLen = (int) oEnty.getContentLength();
                if (nLen > 0) {
                    aRetVal = new byte[nLen];
                    InputStream oBody = oEnty.getContent();
                    oBody.read(aRetVal, 0, nLen);
                    oBody.close();
                } else {
                    aRetVal = null;
                } // fi         
            } finally {
                oHttpCli.getConnectionManager().shutdown();
                oHttpCli = null;
            }
        } // fi (user is anonymous)
    } else if (sLower.startsWith("ftp://")) {

        FTPClient oFTPC = null;
        boolean bFTPSession = false;

        splitURI(sFilePath);

        try {

            if (DebugFile.trace)
                DebugFile.writeln("new FTPClient(" + sHost + ")");
            oFTPC = new FTPClient(sHost);

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")");
            oFTPC.login(sUsr, sPwd);

            bFTPSession = true;

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
            oFTPC.chdir(sPath);

            ByteArrayOutputStream oStrm = new ByteArrayOutputStream();

            oFTPC.setType(FTPTransferType.BINARY);

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.get(" + sPath + sFile + "," + sFile + ",false)");
            oFTPC.get(oStrm, sFile);

            aRetVal = oStrm.toByteArray();

            oStrm.close();
        } catch (FTPException ftpe) {
            throw new FTPException(ftpe.getMessage());
        } finally {
            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.quit()");
            if (bFTPSession)
                oFTPC.quit();
        }

    } else {

        File oFile = new File(sFilePath);
        int iFLen = (int) oFile.length();

        BufferedInputStream oBfStrm;
        FileInputStream oInStrm;

        if (iFLen > 0) {
            aRetVal = new byte[iFLen];
            oInStrm = new FileInputStream(oFile);
            oBfStrm = new BufferedInputStream(oInStrm, iFLen);

            int iReaded = oBfStrm.read(aRetVal, 0, iFLen);

            oBfStrm.close();
            oInStrm.close();

            oInStrm = null;
            oFile = null;

        } else
            aRetVal = null;
    }

    if (DebugFile.trace) {
        DebugFile.decIdent();
        DebugFile.writeln("End FileSystem.readfilebin()");
    }

    return aRetVal;
}

From source file:com.knowgate.dfs.FileSystem.java

/**
 * <p>Read a text file into a String</p>
 * @param sFilePath Full path of file to be readed. Like "file:///tmp/myfile.txt" or "ftp://myhost:21/dir/myfile.txt"
 * @param sEncoding Text Encoding for file {UTF-8, ISO-8859-1, ...}<BR>
 * if <b>null</b> then if first two bytes of file are FF FE then UTF-8 will be assumed<BR>
 * else ISO-8859-1 will be assumed./*  w w  w  . java2s. c  o  m*/
 * @return String with full contents of file
 * @throws FileNotFoundException
 * @throws IOException
 * @throws OutOfMemoryError
 * @throws MalformedURLException
 * @throws FTPException
 */
public String readfilestr(String sFilePath, String sEncoding)
        throws MalformedURLException, FTPException, FileNotFoundException, IOException, OutOfMemoryError {

    if (DebugFile.trace) {
        DebugFile.writeln("Begin FileSystem.readfilestr(" + sFilePath + "," + sEncoding + ")");
        DebugFile.incIdent();
    }

    String sRetVal;
    String sLower = sFilePath.toLowerCase();

    if (sLower.startsWith("file://"))
        sFilePath = sFilePath.substring(7);

    if (sLower.startsWith("http://") || sLower.startsWith("https://")) {

        URL oUrl = new URL(sFilePath);
        if (user().equals("anonymous") || user().length() == 0) {
            ByteArrayOutputStream oStrm = new ByteArrayOutputStream();
            DataHandler oHndlr = new DataHandler(oUrl);
            oHndlr.writeTo(oStrm);
            sRetVal = oStrm.toString(sEncoding);
            oStrm.close();
        } else {
            if (null == oHttpCli) {
                oHttpCli = new DefaultHttpClient();
            } // fi (oHttpCli)
            oHttpCli.getCredentialsProvider().setCredentials(
                    new AuthScope(oUrl.getHost(), AuthScope.ANY_PORT, realm()),
                    new UsernamePasswordCredentials(user(), password()));
            HttpGet oGet = null;
            try {

                oGet = new HttpGet(sFilePath);
                HttpResponse oResp = oHttpCli.execute(oGet);
                HttpEntity oEnty = oResp.getEntity();
                int nLen = (int) oEnty.getContentLength();
                if (nLen > 0) {
                    byte[] aRetVal = new byte[nLen];
                    InputStream oBody = oEnty.getContent();
                    oBody.read(aRetVal, 0, nLen);
                    oBody.close();
                    sRetVal = new String(aRetVal, sEncoding);
                } else {
                    sRetVal = "";
                } // fi         
            } finally {
                oHttpCli.getConnectionManager().shutdown();
                oHttpCli = null;
            }
        } // fi
    } else if (sLower.startsWith("ftp://")) {

        FTPClient oFTPC = null;
        boolean bFTPSession = false;

        splitURI(sFilePath);

        try {

            if (DebugFile.trace)
                DebugFile.writeln("new FTPClient(" + sHost + ")");
            oFTPC = new FTPClient(sHost);

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")");
            oFTPC.login(sUsr, sPwd);

            bFTPSession = true;

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
            oFTPC.chdir(sPath);

            ByteArrayOutputStream oStrm = new ByteArrayOutputStream();

            oFTPC.setType(FTPTransferType.BINARY);

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.get(" + sPath + sFile + "," + sFile + ",false)");
            oFTPC.get(oStrm, sFile);

            sRetVal = oStrm.toString(sEncoding);

            oStrm.close();
        } catch (FTPException ftpe) {
            throw new FTPException(ftpe.getMessage());
        } finally {
            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.quit()");
            try {
                if (bFTPSession)
                    oFTPC.quit();
            } catch (Exception ignore) {
            }
        }
    } else {

        File oFile = new File(sFilePath);
        int iFLen = (int) oFile.length();
        if (iFLen > 0) {
            byte byBuffer[] = new byte[3];
            char aBuffer[] = new char[iFLen];
            BufferedInputStream oBfStrm;
            FileInputStream oInStrm;
            InputStreamReader oReader;

            if (sEncoding == null) {
                oInStrm = new FileInputStream(oFile);
                oBfStrm = new BufferedInputStream(oInStrm, iFLen);

                sEncoding = new CharacterSetDetector().detect(oBfStrm, "ISO-8859-1");

                if (DebugFile.trace)
                    DebugFile.writeln("encoding is " + sEncoding);

                oBfStrm.close();
                oInStrm.close();
            } // fi

            oInStrm = new FileInputStream(oFile);
            oBfStrm = new BufferedInputStream(oInStrm, iFLen);

            oReader = new InputStreamReader(oBfStrm, sEncoding);

            int iReaded = oReader.read(aBuffer, 0, iFLen);

            // Skip FF FE character mark for Unidode files
            int iSkip = ((int) aBuffer[0] == 65279 || (int) aBuffer[0] == 65533 || (int) aBuffer[0] == 65534 ? 1
                    : 0);

            oReader.close();
            oBfStrm.close();
            oInStrm.close();

            oReader = null;
            oInStrm = null;
            oFile = null;

            sRetVal = new String(aBuffer, iSkip, iReaded - iSkip);
        } else
            sRetVal = "";
    } // fi (iFLen>0)

    if (DebugFile.trace) {
        DebugFile.decIdent();
        DebugFile.writeln("End FileSystem.readfilestr() : " + String.valueOf(sRetVal.length()));
    }

    return sRetVal;
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

private HttpClient getClient(boolean followRedirects, boolean auth) {
    DefaultHttpClient result = s_client.getHttpClient(followRedirects, auth);
    if (auth) {//from   w w  w  .ja  v  a2 s  .  c  o  m
        String host = getHost();
        LOGGER.debug("credentials set for scope of {}:[ANY PORT]", host);
        result.getCredentialsProvider().setCredentials(
                new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(getUsername(), getPassword()));
    } else {
        result.getCredentialsProvider().clear();
    }
    return result;
}

From source file:org.apache.tomcat.maven.common.deployer.TomcatManager.java

/**
 * Creates a Tomcat manager wrapper for the specified URL, username, password and URL encoding.
 *
 * @param url      the full URL of the Tomcat manager instance to use
 * @param username the username to use when authenticating with Tomcat manager
 * @param password the password to use when authenticating with Tomcat manager
 * @param charset  the URL encoding charset to use when communicating with Tomcat manager
 * @param verbose  if the build is in verbose mode (quiet mode otherwise)
 * @since 2.2//from w  ww.ja v  a 2  s  .com
 */
public TomcatManager(URL url, String username, String password, String charset, boolean verbose) {
    this.url = url;
    this.username = username;
    this.password = password;
    this.charset = charset;
    this.verbose = verbose;

    PoolingClientConnectionManager poolingClientConnectionManager = new PoolingClientConnectionManager();
    poolingClientConnectionManager.setMaxTotal(5);
    this.httpClient = new DefaultHttpClient(poolingClientConnectionManager);
    if (StringUtils.isNotEmpty(username)) {
        Credentials creds = new UsernamePasswordCredentials(username, password);

        String host = url.getHost();
        int port = url.getPort() > -1 ? url.getPort() : AuthScope.ANY_PORT;

        httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), creds);

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        authCache.put(targetHost, basicAuth);

        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }
}

From source file:org.datacleaner.user.UserPreferencesImplTest.java

public void testCreateHttpClientWithoutNtCredentials() throws Exception {
    UserPreferencesImpl up = new UserPreferencesImpl(null);
    up.setProxyHostname("host");
    up.setProxyPort(1234);//from  w w w .j av  a2 s  . co  m
    up.setProxyUsername("bar");
    up.setProxyPassword("baz");
    up.setProxyEnabled(true);
    up.setProxyAuthenticationEnabled(true);

    CloseableHttpClient httpClient = up.createHttpClient();

    String computername = InetAddress.getLocalHost().getHostName();
    assertNotNull(computername);
    assertTrue(computername.length() > 1);

    AuthScope authScope;
    Credentials credentials;

    authScope = new AuthScope("host", 1234, AuthScope.ANY_REALM, "ntlm");
    credentials = getCredentialsProvider(httpClient).getCredentials(authScope);
    assertEquals("[principal: bar][workstation: " + computername.toUpperCase() + "]", credentials.toString());

    authScope = new AuthScope("host", 1234);
    credentials = getCredentialsProvider(httpClient).getCredentials(authScope);
    assertEquals("[principal: bar]", credentials.toString());

    authScope = new AuthScope("anotherhost", AuthScope.ANY_PORT);
    credentials = getCredentialsProvider(httpClient).getCredentials(authScope);
    assertNull(credentials);
}