Example usage for org.apache.commons.httpclient.auth AuthPolicy BASIC

List of usage examples for org.apache.commons.httpclient.auth AuthPolicy BASIC

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.auth AuthPolicy BASIC.

Prototype

String BASIC

To view the source code for org.apache.commons.httpclient.auth AuthPolicy BASIC.

Click Source Link

Usage

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

public HttpImpl() {

    // Override the default protocol socket factory because it uses
    // reflection for JDK 1.4 compatibility, which we do not need. It also
    // attemps to create a new socket in a different thread so that we
    // cannot track which class loader initiated the call.

    Protocol protocol = new Protocol("http", new FastProtocolSocketFactory(), 80);

    Protocol.registerProtocol("http", protocol);

    // Mimic behavior found in
    // http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html

    if (Validator.isNotNull(_NON_PROXY_HOSTS)) {
        String nonProxyHostsRegEx = _NON_PROXY_HOSTS;

        nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\.", "\\\\.");
        nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\*", ".*?");
        nonProxyHostsRegEx = nonProxyHostsRegEx.replaceAll("\\|", ")|(");

        nonProxyHostsRegEx = "(" + nonProxyHostsRegEx + ")";

        _nonProxyHostsPattern = Pattern.compile(nonProxyHostsRegEx);
    }/*w ww  .ja  va 2  s .  c  o  m*/

    MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();

    HttpConnectionManagerParams httpConnectionManagerParams = httpConnectionManager.getParams();

    httpConnectionManagerParams.setConnectionTimeout(_TIMEOUT);
    httpConnectionManagerParams.setDefaultMaxConnectionsPerHost(new Integer(_MAX_CONNECTIONS_PER_HOST));
    httpConnectionManagerParams.setMaxTotalConnections(new Integer(_MAX_TOTAL_CONNECTIONS));
    httpConnectionManagerParams.setSoTimeout(_TIMEOUT);

    _httpClient.setHttpConnectionManager(httpConnectionManager);
    _proxyHttpClient.setHttpConnectionManager(httpConnectionManager);

    if (!hasProxyConfig() || Validator.isNull(_PROXY_USERNAME)) {
        return;
    }

    List<String> authPrefs = new ArrayList<String>();

    if (_PROXY_AUTH_TYPE.equals("username-password")) {
        _proxyCredentials = new UsernamePasswordCredentials(_PROXY_USERNAME, _PROXY_PASSWORD);

        authPrefs.add(AuthPolicy.BASIC);
        authPrefs.add(AuthPolicy.DIGEST);
        authPrefs.add(AuthPolicy.NTLM);
    } else if (_PROXY_AUTH_TYPE.equals("ntlm")) {
        _proxyCredentials = new NTCredentials(_PROXY_USERNAME, _PROXY_PASSWORD, _PROXY_NTLM_HOST,
                _PROXY_NTLM_DOMAIN);

        authPrefs.add(AuthPolicy.NTLM);
        authPrefs.add(AuthPolicy.BASIC);
        authPrefs.add(AuthPolicy.DIGEST);
    }

    HttpClientParams httpClientParams = _proxyHttpClient.getParams();

    httpClientParams.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
}

From source file:com.hp.alm.ali.rest.client.AliRestClient.java

@Override
public synchronized void login() {
    // exclude the NTLM authentication scheme (requires NTCredentials we don't supply)
    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.DIGEST);/*from w  w w . jav a2s . c o  m*/
    authPrefs.add(AuthPolicy.BASIC);
    httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    // first try Apollo style login
    String authPoint = pathJoin("/", location, "/authentication-point/alm-authenticate");
    String authXml = createAuthXml();
    PostMethod post = initPostMethod(authPoint, authXml);
    ResultInfo resultInfo = ResultInfo.create(null);
    executeAndWriteResponse(post, resultInfo, Collections.<Integer>emptySet());

    if (resultInfo.getHttpStatus() == HttpStatus.SC_NOT_FOUND) {
        // try Maya style login
        Credentials cred = new UsernamePasswordCredentials(userName, password);
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
        httpClient.getParams().setParameter(HttpMethodParams.CREDENTIAL_CHARSET, "UTF-8");
        httpClient.getState().setCredentials(scope, cred);

        authPoint = pathJoin("/", location, "/authentication-point/authenticate");
        GetMethod get = new GetMethod(authPoint);
        resultInfo = ResultInfo.create(null);
        executeAndWriteResponse(get, resultInfo, Collections.<Integer>emptySet());
    }
    HttpStatusBasedException.throwForError(resultInfo);
    if (resultInfo.getHttpStatus() != 200) {
        // during login we only accept 200 status (to avoid redirects and such as seemingly correct login)
        throw new AuthenticationFailureException(resultInfo);
    }

    Cookie[] cookies = httpClient.getState().getCookies();
    Cookie ssoCookie = getSessionCookieByName(cookies, COOKIE_SSO_NAME);
    addTenantCookie(ssoCookie);

    //Since ALM 12.00 it is required explicitly ask for QCSession calling "/rest/site-session"
    //For all the rest of HP ALM / AGM versions it is optional
    String siteSessionPoint = pathJoin("/", location, "/rest/site-session");
    String sessionParamXml = createRestSessionXml();
    post = initPostMethod(siteSessionPoint, sessionParamXml);
    resultInfo = ResultInfo.create(null);
    executeAndWriteResponse(post, resultInfo, Collections.<Integer>emptySet());
    //AGM throws 403
    if (resultInfo.getHttpStatus() != HttpStatus.SC_FORBIDDEN) {
        HttpStatusBasedException.throwForError(resultInfo);
    }

    cookies = httpClient.getState().getCookies();
    Cookie qcCookie = getSessionCookieByName(cookies, COOKIE_SESSION_NAME);
    sessionContext = new SessionContext(location, ssoCookie, qcCookie);
}

From source file:com.fluxit.camel.component.n4.N4Producer.java

private HttpClient createHttpClient() {

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(endpoint.getN4User(),
            endpoint.getN4Pass());/*from  w  w w . j av  a2  s .  com*/

    HttpClient client = new HttpClient();
    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.BASIC);
    // This will exclude the NTLM authentication scheme
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    client.getParams().setParameter("http.connection.timeout", new Integer(2000));
    client.getParams().setParameter("http.socket.timeout", new Integer(2000));
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, creds);

    return client;
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

public void setCredential(String user, String pass) {
    mUsername = user;/*from  w  w w  .  jav  a  2s . c  o  m*/
    mPassword = pass;
    HttpState state = new HttpState();
    Credentials cred = new UsernamePasswordCredentials(mUsername, mPassword);
    state.setCredentials(AuthScope.ANY, cred);
    mClient.setState(state);
    ArrayList<String> authPrefs = new ArrayList<String>();
    authPrefs.add(AuthPolicy.BASIC);
    mClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    mClient.getParams().setAuthenticationPreemptive(true);
}

From source file:com.zimbra.cs.fb.ExchangeFreeBusyProvider.java

private boolean basicAuth(HttpClient client, ServerInfo info) {
    HttpState state = new HttpState();
    Credentials cred = new UsernamePasswordCredentials(info.authUsername, info.authPassword);
    state.setCredentials(AuthScope.ANY, cred);
    client.setState(state);//w ww.j a v  a2  s  .  co  m
    ArrayList<String> authPrefs = new ArrayList<String>();
    authPrefs.add(AuthPolicy.BASIC);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    return true;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Enable NTLM authentication on http client
 *
 * @param httpClient HttpClient instance
 */// www . j  a v  a  2 s .  c  om
public static void addNTLM(HttpClient httpClient) {
    // disable preemptive authentication
    httpClient.getParams().setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, false);

    // register the jcifs based NTLMv2 implementation
    AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, NTLMv2Scheme.class);

    ArrayList<String> authPrefs = new ArrayList<String>();
    authPrefs.add(AuthPolicy.NTLM);
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    // separate domain from username in credentials
    AuthScope authScope = new AuthScope(null, -1);
    NTCredentials credentials = (NTCredentials) httpClient.getState().getCredentials(authScope);
    String userName = credentials.getUserName();
    int backSlashIndex = userName.indexOf('\\');
    if (backSlashIndex >= 0) {
        String domain = userName.substring(0, backSlashIndex);
        userName = userName.substring(backSlashIndex + 1);
        credentials = new NTCredentials(userName, credentials.getPassword(), "UNKNOWN", domain);
        httpClient.getState().setCredentials(authScope, credentials);
    }

    // make sure NTLM is always active
    needNTLM = true;
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an HTTP connection to a provided website and returns the data back
 * to the requestor.//w  w  w .j  ava  2 s  .c  o m
 *
 * @param hostName - The fully qualified URL for the host desired. MUST be
 *     prefixed with http/https:// as necessary
 * @param methodType - GET or POST, depending on what is necessary
 * @return A object containing the response data
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeHttpConnection(final URL hostName, final String methodType)
        throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeHttpConnection(final URL hostName, final String methodType) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", hostName);
        DEBUGGER.debug("Value: {}", methodType);
    }

    RequestConfig requestConfig = null;
    CloseableHttpClient httpClient = null;
    CredentialsProvider credsProvider = null;
    CloseableHttpResponse httpResponse = null;

    final HttpClientParams httpParams = new HttpClientParams();
    final HTTPConfig httpConfig = appBean.getConfigData().getHttpConfig();
    final ProxyConfig proxyConfig = appBean.getConfigData().getProxyConfig();

    if (DEBUG) {
        DEBUGGER.debug("HttpClient: {}", httpClient);
        DEBUGGER.debug("HttpClientParams: {}", httpParams);
        DEBUGGER.debug("HTTPConfig: {}", httpConfig);
        DEBUGGER.debug("ProxyConfig: {}", proxyConfig);
    }
    try {
        final URI requestURI = new URIBuilder().setScheme(hostName.getProtocol()).setHost(hostName.getHost())
                .setPort(hostName.getPort()).build();

        if (StringUtils.isNotEmpty(httpConfig.getTrustStoreFile())) {
            System.setProperty("javax.net.ssl.trustStoreType",
                    (StringUtils.isNotEmpty(httpConfig.getTrustStoreType()) ? httpConfig.getTrustStoreType()
                            : "jks"));
            System.setProperty("javax.net.ssl.trustStore", httpConfig.getTrustStoreFile());
            System.setProperty("javax.net.ssl.trustStorePassword",
                    PasswordUtils.decryptText(httpConfig.getTrustStorePass(), httpConfig.getTrustStoreSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        }

        if (StringUtils.isNotEmpty(httpConfig.getKeyStoreFile())) {
            System.setProperty("javax.net.ssl.keyStoreType",
                    (StringUtils.isNotEmpty(httpConfig.getKeyStoreType()) ? httpConfig.getKeyStoreType()
                            : "jks"));
            System.setProperty("javax.net.ssl.keyStore", httpConfig.getKeyStoreFile());
            System.setProperty("javax.net.ssl.keyStorePassword",
                    PasswordUtils.decryptText(httpConfig.getKeyStorePass(), httpConfig.getKeyStoreSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        }

        if (proxyConfig.isProxyServiceRequired()) {
            if (DEBUG) {
                DEBUGGER.debug("ProxyConfig: {}", proxyConfig);
            }

            if (StringUtils.isEmpty(proxyConfig.getProxyServerName())) {
                throw new UtilityException(
                        "Configuration states proxy usage is required, but no proxy is configured.");
            }

            if (proxyConfig.isProxyAuthRequired()) {
                List<String> authList = new ArrayList<String>();
                authList.add(AuthPolicy.BASIC);
                authList.add(AuthPolicy.DIGEST);
                authList.add(AuthPolicy.NTLM);

                if (DEBUG) {
                    DEBUGGER.debug("authList: {}", authList);
                }

                requestConfig = RequestConfig.custom()
                        .setConnectionRequestTimeout(
                                (int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout()))
                        .setConnectTimeout((int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout()))
                        .setContentCompressionEnabled(Boolean.TRUE)
                        .setProxy(new HttpHost(proxyConfig.getProxyServerName(),
                                proxyConfig.getProxyServerPort()))
                        .setProxyPreferredAuthSchemes(authList).build();

                if (DEBUG) {
                    DEBUGGER.debug("requestConfig: {}", requestConfig);
                }

                String proxyPwd = PasswordUtils.decryptText(proxyConfig.getProxyPassword(),
                        proxyConfig.getProxyPwdSalt(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                        secBean.getConfigData().getSecurityConfig().getIterations(),
                        secBean.getConfigData().getSecurityConfig().getKeyBits(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                        appBean.getConfigData().getSystemConfig().getEncoding());

                if (DEBUG) {
                    DEBUGGER.debug("proxyPwd: {}", proxyPwd);
                }

                if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_BASIC, proxyConfig.getProxyAuthType())) {
                    credsProvider = new SystemDefaultCredentialsProvider();
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()),
                            new UsernamePasswordCredentials(proxyConfig.getProxyUserId(), proxyPwd));
                } else if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_NTLM,
                        proxyConfig.getProxyAuthType())) {
                    credsProvider = new SystemDefaultCredentialsProvider();
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()),
                            new NTCredentials(proxyConfig.getProxyUserId(), proxyPwd,
                                    InetAddress.getLocalHost().getHostName(),
                                    proxyConfig.getProxyAuthDomain()));
                }

                if (DEBUG) {
                    DEBUGGER.debug("httpClient: {}", httpClient);
                }
            }
        }

        synchronized (new Object()) {
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

            if (StringUtils.equalsIgnoreCase(methodType, "POST")) {
                HttpPost httpMethod = new HttpPost(requestURI);
                httpMethod.setConfig(requestConfig);

                httpResponse = httpClient.execute(httpMethod);
            } else {
                HttpGet httpMethod = new HttpGet(requestURI);
                httpMethod.setConfig(requestConfig);

                httpResponse = httpClient.execute(httpMethod);
            }

            int responseCode = httpResponse.getStatusLine().getStatusCode();

            if (DEBUG) {
                DEBUGGER.debug("responseCode: {}", responseCode);
            }

            if (responseCode != 200) {
                ERROR_RECORDER.error("HTTP Response Code received NOT 200: " + responseCode);

                throw new UtilityException("HTTP Response Code received NOT 200: " + responseCode);
            }

            return httpResponse.getEntity().toString();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (URISyntaxException usx) {
        throw new UtilityException(usx.getMessage(), usx);
    } finally {
        if (httpResponse != null) {
            try {
                httpResponse.close();
            } catch (IOException iox) {
            } // dont do anything with it
        }
    }
}

From source file:no.sws.client.SwsClient.java

/**
 * Initialize a new HttpClient, storing the credentials for the client
 *
 * @param username The username to log on to SendRegning Web Services
 * @param password The password to log on to SendRegning Web Services
 * @return//from  www  .j  a  va2  s.  com
 */
private HttpClient initHttpClient(final String username, final String password) {

    HttpClient result = new HttpClient();

    List<String> authPrefs = new ArrayList<String>(1);
    authPrefs.add(AuthPolicy.BASIC);
    // This will exclude the NTLM and DIGEST authentication scheme
    result.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    // Preemptive authentication can be enabled within HttpClient. In this mode HttpClient will send the basic authentication response even before the
    // server gives an unauthorized response in certain situations, thus reducing the overhead of making the connection.
    result.getParams().setAuthenticationPreemptive(true);

    // set credentials
    result.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    return result;
}

From source file:org.abstracthorizon.proximity.storage.remote.CommonsHttpClientRemotePeer.java

/**
 * Gets the http client.// w  w w . j  a  v a 2s .  co m
 * 
 * @return the http client
 */
public HttpClient getHttpClient() {
    if (httpClient == null) {
        logger.info("Creating CommonsHttpClient instance");
        httpRetryHandler = new DefaultHttpMethodRetryHandler(retrievalRetryCount, true);
        httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
        httpClient.getParams().setConnectionManagerTimeout(getConnectionTimeout());

        httpConfiguration = httpClient.getHostConfiguration();

        // BASIC and DIGEST auth only
        if (getUsername() != null) {

            List authPrefs = new ArrayList(2);
            authPrefs.add(AuthPolicy.DIGEST);
            authPrefs.add(AuthPolicy.BASIC);

            if (getNtlmDomain() != null) {
                // Using NTLM auth, adding it as first in policies
                authPrefs.add(0, AuthPolicy.NTLM);

                logger.info("... authentication setup for NTLM domain {}, username {}", getNtlmDomain(),
                        getUsername());
                httpConfiguration.setHost(getNtlmHost());

                httpClient.getState().setCredentials(AuthScope.ANY,
                        new NTCredentials(getUsername(), getPassword(), getNtlmHost(), getNtlmDomain()));
            } else {

                // Using Username/Pwd auth, will not add NTLM
                logger.info("... setting authentication setup for remote peer {}, with username {}",
                        getRemoteUrl(), getUsername());

                httpClient.getState().setCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(getUsername(), getPassword()));

            }
            httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
        }

        if (getProxyHost() != null) {
            logger.info("... proxy setup with host {}", getProxyHost());
            httpConfiguration.setProxy(getProxyHost(), getProxyPort());

            if (getProxyUsername() != null) {

                List authPrefs = new ArrayList(2);
                authPrefs.add(AuthPolicy.DIGEST);
                authPrefs.add(AuthPolicy.BASIC);

                if (getProxyNtlmDomain() != null) {

                    // Using NTLM auth, adding it as first in policies
                    authPrefs.add(0, AuthPolicy.NTLM);

                    if (getNtlmHost() != null) {
                        logger.warn("... CommonsHttpClient is unable to use NTLM auth scheme\n"
                                + " for BOTH server side and proxy side authentication!\n"
                                + " You MUST reconfigure server side auth and use BASIC/DIGEST scheme\n"
                                + " if you have to use NTLM proxy, since otherwise it will not work!\n"
                                + " *** SERVER SIDE AUTH OVERRIDDEN");
                    }
                    logger.info("... proxy authentication setup for NTLM domain {}, username {}",
                            getProxyNtlmDomain(), getProxyUsername());
                    httpConfiguration.setHost(getProxyNtlmHost());

                    httpClient.getState().setProxyCredentials(AuthScope.ANY, new NTCredentials(
                            getProxyUsername(), getProxyPassword(), getProxyNtlmHost(), getProxyNtlmDomain()));
                } else {

                    // Using Username/Pwd auth, will not add NTLM
                    logger.info("... proxy authentication setup for http proxy {}, username {}", getProxyHost(),
                            getProxyUsername());

                    httpClient.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));

                }
                httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
            }

        }
    }
    return httpClient;
}

From source file:org.anhonesteffort.flock.webdav.DavClient.java

protected void initClient() {
    HttpClientParams params = new HttpClientParams();
    List<String> authPrefs = new ArrayList<String>(2);

    authPrefs.add(AuthPolicy.DIGEST);//from w w w.ja  va 2 s .  co  m
    authPrefs.add(AuthPolicy.BASIC);
    params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    params.setAuthenticationPreemptive(true);

    client = new HttpClient(params);
    hostConfiguration = client.getHostConfiguration();
    connectionManager = client.getHttpConnectionManager();

    hostConfiguration.setHost(davHost.getHost(), davHost.getPort(),
            Protocol.getProtocol(davHost.getProtocol()));

    Credentials credentials = new UsernamePasswordCredentials(davUsername, davPassword);
    client.getState().setCredentials(AuthScope.ANY, credentials);
}