Example usage for org.apache.commons.httpclient.auth AuthState getAuthScheme

List of usage examples for org.apache.commons.httpclient.auth AuthState getAuthScheme

Introduction

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

Prototype

public AuthScheme getAuthScheme() 

Source Link

Usage

From source file:com.esri.gpt.framework.http.HttpClientRequest.java

/**
 * Executes the HTTP request.//from  ww  w .  jav  a2  s .  c  om
 * @throws IOException if an Exception occurs
 */
public void execute() throws IOException {

    // initialize
    this.executionLog.setLength(0);
    StringBuffer log = this.executionLog;
    ResponseInfo respInfo = this.getResponseInfo();
    respInfo.reset();
    InputStream responseStream = null;
    HttpMethodBase method = null;

    try {
        log.append("HTTP Client Request\n").append(this.getUrl());

        // make the Apache HTTPClient
        HttpClient client = this.batchHttpClient;
        if (client == null) {
            client = new HttpClient();
            boolean alwaysClose = Val.chkBool(Val.chkStr(ApplicationContext.getInstance().getConfiguration()
                    .getCatalogConfiguration().getParameters().getValue("httpClient.alwaysClose")), false);
            if (alwaysClose) {
                client.setHttpConnectionManager(new SimpleHttpConnectionManager(true));
            }
        }

        // setting timeout info
        client.getHttpConnectionManager().getParams().setConnectionTimeout(getConnectionTimeOutMs());
        client.getHttpConnectionManager().getParams().setSoTimeout(getResponseTimeOutMs());

        // setting retries
        int retries = this.getRetries();

        // create the client and method, apply authentication and proxy settings
        method = this.createMethod();
        //method.setFollowRedirects(true);
        if (retries > -1) {
            // TODO: not taking effect yet?
            DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retries, true);
            client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
        }

        this.applyAuthAndProxySettings(client, this.getUrl());

        // execute the method, determine basic information about the response
        respInfo.setResponseCode(client.executeMethod(method));
        this.determineResponseInfo(method);

        // collect logging info
        if (LOGGER.isLoggable(Level.FINER)) {
            log.append("\n>>").append(method.getStatusLine());
            log.append("\n--Request Header");
            for (Header hdr : method.getRequestHeaders()) {
                log.append("\n  ").append(hdr.getName() + ": " + hdr.getValue());
            }
            log.append("\n--Response Header");
            for (Header hdr : method.getResponseHeaders()) {
                log.append("\n  ").append(hdr.getName() + ": " + hdr.getValue());
            }

            //log.append(" responseCode=").append(this.getResponseInfo().getResponseCode());
            //log.append(" responseContentType=").append(this.getResponseInfo().getContentType());
            //log.append(" responseContentEncoding=").append(this.getResponseInfo().getContentEncoding());
            //log.append(" responseContentLength=").append(this.getResponseInfo().getContentLength());

            if (this.getContentProvider() != null) {
                String loggable = this.getContentProvider().getLoggableContent();
                if (loggable != null) {
                    log.append("\n--Request Content------------------------------------\n").append(loggable);
                }
            }
        }

        // throw an exception if an error is encountered
        if ((respInfo.getResponseCode() < 200) || (respInfo.getResponseCode() >= 300)) {
            String msg = "HTTP Request failed: " + method.getStatusLine();
            if (respInfo.getResponseCode() == HttpStatus.SC_UNAUTHORIZED) {
                AuthState authState = method.getHostAuthState();
                AuthScheme authScheme = authState.getAuthScheme();
                HttpClient401Exception authException = new HttpClient401Exception(msg);
                authException.setUrl(this.getUrl());
                authException.setRealm(authState.getRealm());
                authException.setScheme(authScheme.getSchemeName());
                if ((authException.getRealm() == null) || (authException.getRealm().length() == 0)) {
                    authException.setRealm(authException.generateHostBasedRealm());
                }
                throw authException;
            } else {
                throw new HttpClientException(respInfo.getResponseCode(), msg);
            }
        }

        // handle the response
        if (this.getContentHandler() != null) {
            if (getContentHandler().onBeforeReadResponse(this)) {
                responseStream = getResponseStream(method);
                if (responseStream != null) {
                    this.getContentHandler().readResponse(this, responseStream);
                }
            }

            // log thre response content
            String loggable = this.getContentHandler().getLoggableContent();
            long nBytesRead = this.getResponseInfo().getBytesRead();
            long nCharsRead = this.getResponseInfo().getCharactersRead();
            if ((nBytesRead >= 0) || (nCharsRead >= 0) || (loggable != null)) {
                log.append("\n--Response Content------------------------------------");
                if (nBytesRead >= 0)
                    log.append("\n(").append(nBytesRead).append(" bytes read)");
                if (nCharsRead >= 0)
                    log.append("\n(").append(nCharsRead).append(" characters read)");
                if (loggable != null)
                    log.append("\n").append(loggable);
            }
        }

    } finally {

        // cleanup
        try {
            if (responseStream != null)
                responseStream.close();
        } catch (Throwable t) {
            LOGGER.log(Level.SEVERE, "Unable to close HTTP response stream.", t);
        }
        try {
            if (method != null)
                method.releaseConnection();
        } catch (Throwable t) {
            LOGGER.log(Level.SEVERE, "Unable to release HttpMethod", t);
        }

        // log the request/response
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.finer(this.getExecutionLog().toString());
        }
    }
}

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

protected boolean doRequestedAuthentication(HttpClient client, HttpMethod method, RenderRequest request,
        RenderResponse response) {/*from   ww w.j a  v  a2 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.eclipse.ecf.provider.filetransfer.httpclient.NTLMProxyDetector.java

public static boolean detectNTLMProxy(HttpMethodBase method) {
    if (method == null)
        return false;
    AuthState authState = method.getProxyAuthState();
    if (authState == null)
        return false;
    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null)
        return false;
    String schemeName = authScheme.getSchemeName();
    if (schemeName == null)
        return false;
    return schemeName.equalsIgnoreCase(PROXY_NTLM_VALUE);
}