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

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

Introduction

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

Prototype

String AUTH_SCHEME_PRIORITY

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

Click Source Link

Usage

From source file:eu.alefzero.webdav.WebdavClient.java

public void setBasicCredentials(String username, String password) {
    List<String> authPrefs = new ArrayList<String>(1);
    authPrefs.add(AuthPolicy.BASIC);//from  w  w  w .j  a va 2s. c om
    getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    getParams().setAuthenticationPreemptive(true);
    mCredentials = new UsernamePasswordCredentials(username, password);
    getState().setCredentials(AuthScope.ANY, mCredentials);
    mSsoSessionCookie = null;
    mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
}

From source file:jeeves.utils.XmlRequest.java

public XmlRequest(String host, int port, String protocol) {
    this.host = host;
    this.port = port;
    this.protocol = protocol;

    setMethod(Method.GET);//from  w ww .j a  v  a2 s  .co  m
    state.addCookie(cookie);
    client.setState(state);
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setHostConfiguration(config);
    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    // This will exclude the NTLM authentication scheme 
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
}

From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java

private void submitHttpRequest(String address, MessageObject mo) throws Exception {
    HttpMethod httpMethod = null;//from   w  w  w  .ja  v a  2 s.c o  m

    try {
        httpMethod = buildHttpRequest(replacer.replaceValues(address, mo), mo);

        // authentication

        if (connector.isDispatcherUseAuthentication()) {
            List<String> authenticationPreferences = new ArrayList<String>();

            if ("Digest".equalsIgnoreCase(connector.getDispatcherAuthenticationType())) {
                authenticationPreferences.add(AuthPolicy.DIGEST);
                logger.debug("using Digest authentication");
            } else {
                authenticationPreferences.add(AuthPolicy.BASIC);
                logger.debug("using Basic authentication");
            }

            client.getParams().setAuthenticationPreemptive(true);
            client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authenticationPreferences);
            Credentials credentials = new UsernamePasswordCredentials(
                    replacer.replaceValues(connector.getDispatcherUsername(), mo),
                    replacer.replaceValues(connector.getDispatcherPassword(), mo));
            client.getState().setCredentials(
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);
            logger.debug("using authentication with credentials: " + credentials);
        }

        client.getParams().setSoTimeout(
                NumberUtils.toInt(replacer.replaceValues(connector.getDispatcherSocketTimeout()), 30000));

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getName() + ", uri=" + httpMethod.getURI().toString());
        int statusCode = client.executeMethod(httpMethod);
        logger.debug("received status code: " + statusCode);

        String response = null;

        if (connector.isDispatcherIncludeHeadersInResponse()) {
            HttpMessageConverter converter = new HttpMessageConverter();
            response = converter.httpResponseToXml(httpMethod.getStatusLine().toString(),
                    httpMethod.getResponseHeaders(), httpMethod.getResponseBodyAsString());
        } else {
            response = httpMethod.getResponseBodyAsString();
        }

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            messageObjectController.setSuccess(mo, response, null);

            // send to reply channel
            if ((connector.getDispatcherReplyChannelId() != null)
                    && !connector.getDispatcherReplyChannelId().equals("sink")) {
                new VMRouter().routeMessageByChannelId(connector.getDispatcherReplyChannelId(), response, true);
            }
        } else {
            alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_404,
                    "Received error response from HTTP server.", null);
            messageObjectController.setError(mo, Constants.ERROR_404, response, null, null);
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Update http client configuration (proxy)
 *
 * @param httpClient current Http client
 * @param url        target url/*  w ww .  java 2s.c om*/
 * @throws DavMailException on error
 */
public static void configureClient(HttpClient httpClient, String url) throws DavMailException {
    setClientHost(httpClient, url);

    /*if (Settings.getBooleanProperty("davmail.enableKerberos", false)) {
    AuthPolicy.registerAuthScheme("Negotiate", NegotiateScheme.class);
    ArrayList<String> authPrefs = new ArrayList<String>();
    authPrefs.add("Negotiate");
    httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    } else */if (!needNTLM) {
        ArrayList<String> authPrefs = new ArrayList<String>();
        authPrefs.add(AuthPolicy.DIGEST);
        authPrefs.add(AuthPolicy.BASIC);
        // exclude NTLM authentication scheme
        httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    }

    boolean enableProxy = Settings.getBooleanProperty("davmail.enableProxy");
    boolean useSystemProxies = Settings.getBooleanProperty("davmail.useSystemProxies", Boolean.FALSE);
    String proxyHost = null;
    int proxyPort = 0;
    String proxyUser = null;
    String proxyPassword = null;

    try {
        java.net.URI uri = new java.net.URI(url);
        if (isNoProxyFor(uri)) {
            LOGGER.debug("no proxy for " + uri.getHost());
        } else if (useSystemProxies) {
            // get proxy for url from system settings
            System.setProperty("java.net.useSystemProxies", "true");
            List<Proxy> proxyList = getProxyForURI(uri);
            if (!proxyList.isEmpty() && proxyList.get(0).address() != null) {
                InetSocketAddress inetSocketAddress = (InetSocketAddress) proxyList.get(0).address();
                proxyHost = inetSocketAddress.getHostName();
                proxyPort = inetSocketAddress.getPort();

                // we may still need authentication credentials
                proxyUser = Settings.getProperty("davmail.proxyUser");
                proxyPassword = Settings.getProperty("davmail.proxyPassword");
            }
        } else if (enableProxy) {
            proxyHost = Settings.getProperty("davmail.proxyHost");
            proxyPort = Settings.getIntProperty("davmail.proxyPort");
            proxyUser = Settings.getProperty("davmail.proxyUser");
            proxyPassword = Settings.getProperty("davmail.proxyPassword");
        }
    } catch (URISyntaxException e) {
        throw new DavMailException("LOG_INVALID_URL", url);
    }

    // configure proxy
    if (proxyHost != null && proxyHost.length() > 0) {
        httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (proxyUser != null && proxyUser.length() > 0) {

            AuthScope authScope = new AuthScope(proxyHost, proxyPort, AuthScope.ANY_REALM);

            // detect ntlm authentication (windows domain name in user name)
            int backslashindex = proxyUser.indexOf('\\');
            if (backslashindex > 0) {
                httpClient.getState().setProxyCredentials(authScope,
                        new NTCredentials(proxyUser.substring(backslashindex + 1), proxyPassword, "UNKNOWN",
                                proxyUser.substring(0, backslashindex)));
            } else {
                httpClient.getState().setProxyCredentials(authScope,
                        new NTCredentials(proxyUser, proxyPassword, "UNKNOWN", ""));
            }
        }
    }

}

From source file:com.liferay.portal.util.HttpImpl.java

public HttpImpl() {

    // 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 w w  . j ava2 s .  c om*/

    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.isNotNull(_PROXY_USERNAME)) {
        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:fr.jayasoft.ivy.url.HttpClientHandler.java

private HttpClient getClient(URL url) {
    HttpClient client = new HttpClient();

    List authPrefs = new ArrayList(2);
    authPrefs.add(AuthPolicy.DIGEST);/* w  w  w.  ja  v a2 s  .co m*/
    authPrefs.add(AuthPolicy.BASIC);
    // Exclude the NTLM authentication scheme because it is not supported by this class
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    if (useProxy()) {
        client.getHostConfiguration().setProxy(_proxyHost, _proxyPort);
        if (useProxyAuthentication()) {
            client.getState().setProxyCredentials(_proxyRealm, _proxyHost,
                    new UsernamePasswordCredentials(_proxyUserName, _proxyPasswd));
        }
    }
    Credentials c = getCredentials(url);
    if (c != null) {
        Message.debug("found credentials for " + url + ": " + c);
        client.getState().setCredentials(c.getRealm(), c.getHost(),
                new UsernamePasswordCredentials(c.getUserName(), c.getPasswd()));
    }
    return client;
}

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);
    }//from  w  w w .  j av a2s.co  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);/*  www .j  a  va2 s .c om*/
    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 a  v a  2s. c o  m

    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;/*  w  w  w  . j  a v  a2s  .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);
}