Example usage for org.apache.commons.httpclient HttpMethod getHostAuthState

List of usage examples for org.apache.commons.httpclient HttpMethod getHostAuthState

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getHostAuthState.

Prototype

public abstract AuthState getHostAuthState();

Source Link

Usage

From source file:davmail.http.DavGatewayHttpClientFacade.java

private static void resetMethod(HttpMethod method) {
    // reset method state
    method.releaseConnection();// w  w  w .java  2  s .  com
    method.getHostAuthState().invalidate();
    method.getProxyAuthState().invalidate();
}

From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java

/**
 * ?log./*  w  w  w. j  a  v  a2 s .  co  m*/
 * 
 * @param httpMethod
 *            the http method
 * @return the http method attribute map for log
 */
private static Map<String, Object> getHttpMethodRequestAttributeMapForLog(HttpMethod httpMethod) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    try {
        map.put("httpMethod.getName()", httpMethod.getName());
        map.put("httpMethod.getURI()", httpMethod.getURI().toString());
        map.put("httpMethod.getPath()", httpMethod.getPath());
        map.put("httpMethod.getQueryString()", httpMethod.getQueryString());

        map.put("httpMethod.getRequestHeaders()", httpMethod.getRequestHeaders());

        map.put("httpMethod.getDoAuthentication()", httpMethod.getDoAuthentication());
        map.put("httpMethod.getFollowRedirects()", httpMethod.getFollowRedirects());
        map.put("httpMethod.getHostAuthState()", httpMethod.getHostAuthState().toString());

        // HttpMethodParams httpMethodParams = httpMethod.getParams();
        // map.put("httpMethod.getParams()", httpMethodParams);
        map.put("httpMethod.getProxyAuthState()", httpMethod.getProxyAuthState().toString());

    } catch (Exception e) {
        log.error(e.getClass().getName(), e);
    }
    return map;
}

From source file:org.apache.jetspeed.portlets.sso.SSOWebContentPortlet.java

protected byte[] doPreemptiveAuthentication(HttpClient client, HttpMethod method, RenderRequest request,
        RenderResponse response) {/*ww  w .j a  va  2  s  .  c  o m*/
    byte[] result = super.doPreemptiveAuthentication(client, method, request, response);
    if (result != null) {
        // already handled
        return result;
    }

    // System.out.println("SSOWebContentPortlet.doPreemptiveAuthentication...");

    PortletPreferences prefs = request.getPreferences();
    String type = getSingleSignOnAuthType(prefs);

    if (type.equalsIgnoreCase(SSO_TYPE_BASIC_PREEMPTIVE)) {
        // Preemptive, basic authentication
        String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME);
        if (userName == null)
            userName = "";
        String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD);
        if (password == null)
            password = "";

        // System.out.println("...performing preemptive basic authentication with userName: "+userName+", and password: "+password);
        method.setDoAuthentication(true);
        method.getHostAuthState().setPreemptive();
        client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

        // handled!
        return result;

    } else if (type.startsWith(SSO_TYPE_FORM)) {
        try {
            Boolean formAuth = (Boolean) PortletMessaging.receive(request, FORM_AUTH_STATE);
            if (formAuth != null) {
                // already been here, done that
                return (formAuth.booleanValue() ? result : null);
            } else {
                // stop recursion, but assume failure, ...for now
                PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.FALSE);
            }

            String formAction = prefs.getValue(SSO_TYPE_FORM_ACTION_URL, "");
            if (formAction == null || formAction.length() == 0) {
                log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_ACTION_URL
                        + ", action was specified - unable to preemptively authenticate by form.");
                return null;
            }
            String userNameField = prefs.getValue(SSO_TYPE_FORM_USERNAME_FIELD, "");
            if (userNameField == null || userNameField.length() == 0) {
                log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_USERNAME_FIELD
                        + ", username field was specified - unable to preemptively authenticate by form.");
                return null;
            }
            String passwordField = prefs.getValue(SSO_TYPE_FORM_PASSWORD_FIELD, "password");
            if (passwordField == null || passwordField.length() == 0) {
                log.warn("sso.type specified as 'form', but no: " + SSO_TYPE_FORM_PASSWORD_FIELD
                        + ", password field was specified - unable to preemptively authenticate by form.");
                return null;
            }

            String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME);
            if (userName == null)
                userName = "";
            String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD);
            if (password == null)
                password = "";

            // get submit method
            int i = type.indexOf('.');
            boolean isPost = i > 0 ? type.substring(i + 1).equalsIgnoreCase("post") : true; // default to post, since it is a form 

            // get parameter map
            HashMap formParams = new HashMap();
            formParams.put(userNameField, new String[] { userName });
            formParams.put(passwordField, new String[] { password });
            String formArgs = prefs.getValue(SSO_TYPE_FORM_ACTION_ARGS, "");
            if (formArgs != null && formArgs.length() > 0) {
                StringTokenizer iter = new StringTokenizer(formArgs, ";");
                while (iter.hasMoreTokens()) {
                    String pair = iter.nextToken();
                    i = pair.indexOf('=');
                    if (i > 0)
                        formParams.put(pair.substring(0, i), new String[] { pair.substring(i + 1) });
                }
            }

            // resuse client - in case new cookies get set - but create a new method (for the formAction)
            String formMethod = (isPost) ? FORM_POST_METHOD : FORM_GET_METHOD;
            method = getHttpMethod(client, getURLSource(formAction, formParams, request, response), formParams,
                    formMethod, request);
            // System.out.println("...posting credentials");
            result = doHttpWebContent(client, method, 0, request, response);
            // System.out.println("Result of attempted authorization: "+success);
            PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.valueOf(result != null));
            return result;
        } catch (Exception ex) {
            // bad
            log.error("Form-based authentication failed", ex);
        }
    } else if (type.equalsIgnoreCase(SSO_TYPE_URL) || type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) {
        // set user name and password parameters in the HttpMethod
        String userNameParam = prefs.getValue(SSO_TYPE_URL_USERNAME_PARAM, "");
        if (userNameParam == null || userNameParam.length() == 0) {
            log.warn("sso.type specified as 'url', but no: " + SSO_TYPE_URL_USERNAME_PARAM
                    + ", username parameter was specified - unable to preemptively authenticate by URL.");
            return null;
        }
        String passwordParam = prefs.getValue(SSO_TYPE_URL_PASSWORD_PARAM, "");
        if (passwordParam == null || passwordParam.length() == 0) {
            log.warn("sso.type specified as 'url', but no: " + SSO_TYPE_URL_PASSWORD_PARAM
                    + ", password parameter was specified - unable to preemptively authenticate by URL.");
            return null;
        }
        String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME);
        if (userName == null)
            userName = "";
        String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD);
        if (password == null)
            password = "";
        if (type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) {
            Base64 encoder = new Base64();
            userName = new String(encoder.encode(userName.getBytes()));
            password = new String(encoder.encode(password.getBytes()));
        }

        // GET and POST accept args differently
        if (method instanceof PostMethod) {
            // add POST data
            PostMethod postMethod = (PostMethod) method;
            postMethod.addParameter(userNameParam, userName);
            postMethod.addParameter(passwordParam, password);
        } else {
            // augment GET query string
            NameValuePair[] authPairs = new NameValuePair[] { new NameValuePair(userNameParam, userName),
                    new NameValuePair(passwordParam, password) };
            String existingQuery = method.getQueryString();
            method.setQueryString(authPairs);
            if (existingQuery != null && existingQuery.length() > 0) {
                // augment existing query with new auth query
                existingQuery = existingQuery + '&' + method.getQueryString();
                method.setQueryString(existingQuery);
            }
        }

        return result;
    }
    // else System.out.println("...sso.type: "+type+", no pre-emptive authentication");

    // not handled
    return null;
}

From source file:org.apache.jetspeed.portlets.sso.SSOWebContentPortlet.java

protected boolean doRequestedAuthentication(HttpClient client, HttpMethod method, RenderRequest request,
        RenderResponse response) {//from   www. j a v a  2 s . co  m
    if (super.doRequestedAuthentication(client, method, request, response)) {
        // already handled
        return true;
    }

    // System.out.println("SSOWebContentPortlet.doRequestedAuthentication...");

    if (method.getHostAuthState().getAuthScheme().getSchemeName().equals(BASIC_AUTH_SCHEME_NAME)) {
        // Basic authentication being requested
        String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME);
        if (userName == null)
            userName = "";
        String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD);
        if (password == null)
            password = "";

        // System.out.println("...providing basic authentication with userName: "+userName+", and password: "+password);
        method.setDoAuthentication(true);
        AuthState state = method.getHostAuthState();
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, state.getRealm(),
                state.getAuthScheme().getSchemeName());
        client.getState().setCredentials(scope, new UsernamePasswordCredentials(userName, password));

        // handled!
        return true;
    } else {
        log.warn("SSOWebContentPortlent.doAuthenticate() - unexpected authentication scheme: "
                + method.getHostAuthState().getAuthScheme().getSchemeName());
    }

    // only know how to handle Basic authentication, in this context
    return false;
}

From source file:org.archive.modules.credential.HttpAuthenticationCredential.java

@Override
public boolean populate(CrawlURI curi, HttpClient http, HttpMethod method,
        Map<String, String> httpAuthChallenges) {
    boolean result = false;

    AuthChallengeProcessor authChallengeProcessor = new AuthChallengeProcessor(http.getParams());
    try {/*from w ww . jav  a  2 s.c om*/
        AuthScheme authScheme = authChallengeProcessor.processChallenge(method.getHostAuthState(),
                httpAuthChallenges);
        method.getHostAuthState().setAuthScheme(authScheme);
    } catch (MalformedChallengeException e) {
        return result;
    } catch (AuthenticationException e) {
        return result;
    }

    // Always add the credential to HttpState. Doing this because no way of
    // removing the credential once added AND there is a bug in the
    // credentials management system in that it always sets URI root to
    // null: it means the key used to find a credential is NOT realm + root
    // URI but just the realm. Unless I set it everytime, there is
    // possibility that as this thread progresses, it might come across a
    // realm already loaded but the login and password are from another
    // server. We'll get a failed authentication that'd be difficult to
    // explain.
    //
    // Have to make a UsernamePasswordCredentials. The httpclient auth code
    // does an instanceof down in its guts.
    UsernamePasswordCredentials upc = null;
    try {
        upc = new UsernamePasswordCredentials(getLogin(), getPassword());
        http.getState().setCredentials(
                new AuthScope(curi.getUURI().getHost(), curi.getUURI().getPort(), getRealm()), upc);
        logger.fine("Credentials for realm " + getRealm() + " for CrawlURI " + curi.toString()
                + " added to request: " + result);

        http.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY,
                Arrays.asList(AuthPolicy.DIGEST, AuthPolicy.BASIC));

        result = true;
    } catch (URIException e) {
        logger.severe("Failed to parse host from " + curi + ": " + e.getMessage());
    }

    return result;
}

From source file:org.eclipse.mylyn.internal.commons.xmlrpc.CommonXmlRpcClient.java

protected void createXmlRpcClient() {
    config = new XmlRpcClientConfigImpl();
    config.setEncoding(DEFAULT_CHARSET);
    config.setTimeZone(TimeZone.getTimeZone(DEFAULT_TIME_ZONE));
    config.setContentLengthOptional(false);
    config.setConnectionTimeout(WebUtil.getConnectionTimeout());
    config.setReplyTimeout(WebUtil.getSocketTimeout());

    xmlrpc = new XmlRpcClient();
    xmlrpc.setConfig(config);//from w w w .  j a  v  a 2s.c  om
    // bug 307200: force factory that supports proper UTF-8 encoding
    xmlrpc.setXmlWriterFactory(new CharSetXmlWriterFactory());

    factory = new HttpClientTransportFactory(xmlrpc, httpClient);
    factory.setLocation(location);
    factory.setInterceptor(new HttpMethodInterceptor() {
        public void processRequest(HttpMethod method) {
            DigestScheme scheme = digestScheme;
            if (scheme != null) {
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": Digest scheme is present"); //$NON-NLS-1$ 
                }
                Credentials creds = httpClient.getState().getCredentials(authScope);
                if (creds != null) {
                    if (DEBUG_AUTH) {
                        System.err.println(location.getUrl() + ": Setting digest scheme for request"); //$NON-NLS-1$ 
                    }
                    method.getHostAuthState().setAuthScheme(digestScheme);
                    method.getHostAuthState().setAuthRequested(true);
                }
            }
        }

        @SuppressWarnings("null")
        public void processResponse(HttpMethod method) throws XmlRpcException {
            if (isContentTypeCheckingEnabled()) {
                Header contentTypeHeader = method.getResponseHeader("Content-Type"); //$NON-NLS-1$
                if (contentTypeHeader == null || !DEFAULT_CONTENT_TYPE.equals(contentTypeHeader.getValue())) {
                    throw new XmlRpcIllegalContentTypeException(
                            NLS.bind("The server returned an unexpected content type: ''{0}''", //$NON-NLS-1$
                                    contentTypeHeader.getValue()),
                            contentTypeHeader.getValue());
                }
            }
            AuthScheme authScheme = method.getHostAuthState().getAuthScheme();
            if (authScheme instanceof DigestScheme) {
                digestScheme = (DigestScheme) authScheme;
                if (DEBUG_AUTH) {
                    System.err.println(location.getUrl() + ": Received digest scheme"); //$NON-NLS-1$ 
                }
            }
        }
    });
    xmlrpc.setTransportFactory(factory);

    try {
        config.setServerURL(new URL(location.getUrl()));
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.mylyn.internal.phabricator.core.client.TracXmlRpcClient.java

public synchronized XmlRpcClient getClient() throws PhabricatorException {
    if (xmlrpc == null) {
        config = new XmlRpcClientConfigImpl();
        config.setEncoding(ITracClient.CHARSET);
        config.setTimeZone(TimeZone.getTimeZone(ITracClient.TIME_ZONE));
        config.setContentLengthOptional(false);
        config.setConnectionTimeout(WebUtil.getConnectionTimeout());
        config.setReplyTimeout(WebUtil.getSocketTimeout());

        xmlrpc = new XmlRpcClient();
        xmlrpc.setConfig(config);//from   w w  w.j av  a2s.  c o  m
        // bug 307200: force factory that supports proper UTF-8 encoding
        xmlrpc.setXmlWriterFactory(new CharSetXmlWriterFactory());

        factory = new TracHttpClientTransportFactory(xmlrpc, httpClient);
        factory.setLocation(location);
        factory.setInterceptor(new HttpMethodInterceptor() {
            public void processRequest(HttpMethod method) {
                DigestScheme scheme = digestScheme;
                if (scheme != null) {
                    if (DEBUG_AUTH) {
                        System.err.println(location.getUrl() + ": Digest scheme is present"); //$NON-NLS-1$
                    }
                    Credentials creds = httpClient.getState().getCredentials(authScope);
                    if (creds != null) {
                        if (DEBUG_AUTH) {
                            System.err.println(location.getUrl() + ": Setting digest scheme for request"); //$NON-NLS-1$
                        }
                        method.getHostAuthState().setAuthScheme(digestScheme);
                        method.getHostAuthState().setAuthRequested(true);
                    }
                }
            }

            public void processResponse(HttpMethod method) {
                AuthScheme authScheme = method.getHostAuthState().getAuthScheme();
                if (authScheme instanceof DigestScheme) {
                    digestScheme = (DigestScheme) authScheme;
                    if (DEBUG_AUTH) {
                        System.err.println(location.getUrl() + ": Received digest scheme"); //$NON-NLS-1$
                    }
                }
            }
        });
        xmlrpc.setTransportFactory(factory);

        // update configuration with latest values
        AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
        config.setServerURL(getXmlRpcUrl(credentials));
        if (credentialsValid(credentials)) {
            Credentials httpCredentials = WebUtil.getHttpClientCredentials(credentials,
                    WebUtil.getHost(location.getUrl()));
            httpClient.getState().setCredentials(authScope, httpCredentials);
            //            if (CoreUtil.TEST_MODE) {
            //               System.err.println(" Setting credentials: " + httpCredentials); //$NON-NLS-1$
            //            }
            httpClient.getState().setCredentials(authScope, httpCredentials);
        } else {
            httpClient.getState().clearCredentials();
        }
    }

    return xmlrpc;
}

From source file:org.eclipse.mylyn.internal.trac.core.client.TracXmlRpcClient.java

public synchronized XmlRpcClient getClient() throws TracException {
    if (xmlrpc == null) {
        config = new XmlRpcClientConfigImpl();
        config.setEncoding(ITracClient.CHARSET);
        config.setTimeZone(TimeZone.getTimeZone(ITracClient.TIME_ZONE));
        config.setContentLengthOptional(false);
        config.setConnectionTimeout(WebUtil.getConnectionTimeout());
        config.setReplyTimeout(WebUtil.getSocketTimeout());

        xmlrpc = new XmlRpcClient();
        xmlrpc.setConfig(config);/*from w  w  w  .ja v a 2 s .  co  m*/
        // bug 307200: force factory that supports proper UTF-8 encoding
        xmlrpc.setXmlWriterFactory(new CharSetXmlWriterFactory());

        factory = new TracHttpClientTransportFactory(xmlrpc, httpClient);
        factory.setLocation(location);
        factory.setInterceptor(new HttpMethodInterceptor() {
            public void processRequest(HttpMethod method) {
                DigestScheme scheme = digestScheme;
                if (scheme != null) {
                    if (DEBUG_AUTH) {
                        System.err.println(location.getUrl() + ": Digest scheme is present"); //$NON-NLS-1$ 
                    }
                    Credentials creds = httpClient.getState().getCredentials(authScope);
                    if (creds != null) {
                        if (DEBUG_AUTH) {
                            System.err.println(location.getUrl() + ": Setting digest scheme for request"); //$NON-NLS-1$ 
                        }
                        method.getHostAuthState().setAuthScheme(digestScheme);
                        method.getHostAuthState().setAuthRequested(true);
                    }
                }
            }

            public void processResponse(HttpMethod method) {
                AuthScheme authScheme = method.getHostAuthState().getAuthScheme();
                if (authScheme instanceof DigestScheme) {
                    digestScheme = (DigestScheme) authScheme;
                    if (DEBUG_AUTH) {
                        System.err.println(location.getUrl() + ": Received digest scheme"); //$NON-NLS-1$ 
                    }
                }
            }
        });
        xmlrpc.setTransportFactory(factory);

        // update configuration with latest values
        AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
        config.setServerURL(getXmlRpcUrl(credentials));
        if (credentialsValid(credentials)) {
            Credentials httpCredentials = WebUtil.getHttpClientCredentials(credentials,
                    WebUtil.getHost(location.getUrl()));
            httpClient.getState().setCredentials(authScope, httpCredentials);
            //            if (CoreUtil.TEST_MODE) {
            //               System.err.println(" Setting credentials: " + httpCredentials); //$NON-NLS-1$
            //            }
            httpClient.getState().setCredentials(authScope, httpCredentials);
        } else {
            httpClient.getState().clearCredentials();
        }
    }

    return xmlrpc;
}

From source file:org.obm.caldav.client.AbstractPushTest.java

private synchronized Document doRequest(HttpMethod hm) {
    Document xml = null;//from   w  w  w .j  av  a  2  s.c o m
    try {
        int ret = hc.executeMethod(hm);
        Header[] hs = hm.getResponseHeaders();
        for (Header h : hs) {
            System.err.println("head[" + h.getName() + "] => " + h.getValue());
        }
        if (ret == HttpStatus.SC_UNAUTHORIZED) {
            UsernamePasswordCredentials upc = new UsernamePasswordCredentials(login, password);
            authenticate = hm.getHostAuthState().getAuthScheme().authenticate(upc, hm);
            return null;
        } else if (ret == HttpStatus.SC_OK || ret == HttpStatus.SC_MULTI_STATUS) {
            InputStream is = hm.getResponseBodyAsStream();
            if (is != null) {
                if ("text/xml".equals(hm.getRequestHeader("Content-Type"))) {
                    xml = DOMUtils.parse(is);
                    DOMUtils.logDom(xml);
                } else {
                    System.out.println(FileUtils.streamString(is, false));
                }
            }
        } else {
            System.err.println("method failed:\n" + hm.getStatusLine() + "\n" + hm.getResponseBodyAsString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        hm.releaseConnection();
    }
    return xml;
}