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

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

Introduction

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

Prototype

@Override
public AuthState getHostAuthState() 

Source Link

Document

Returns the target host AuthState authentication state

Usage

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

/**
 * Executes the HTTP request.//from w w w. j a v a  2 s.  c o  m
 * @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.rssowl.core.internal.connection.DefaultProtocolHandler.java

private InputStream internalOpenStream(URI link, URI authLink, String authRealm, Map<Object, Object> properties)
        throws ConnectionException {

    /* Handle File Protocol at first */
    if (URIUtils.FILE_SCHEME.equals(link.getScheme()))
        return loadFileProtocol(link);

    /* SSL Support */
    if (URIUtils.HTTPS_SCHEME.equals(link.getScheme()))
        initSSLProtocol();/*from   w ww.j  a v a2  s  .  c  om*/

    /* Feed Support */
    if (URIUtils.FEED_SCHEME.equals(link.getScheme()))
        initFeedProtocol();

    /* Init Client */
    HttpClient client = initClient(properties);

    /* Init the connection */
    HttpMethodBase method = null;
    InputStream inS = null;
    try {

        /* Create Method (GET or POST) */
        method = initConnection(link, properties);

        /* Proxy if required */
        setupProxy(link, client);

        /* Authentication if required */
        setupAuthentication(authLink, authRealm, client, method);

        /* Open the connection */
        inS = openConnection(client, method);

        /* Try to pipe the resulting stream into a GZipInputStream */
        if (inS != null)
            inS = pipeStream(inS, method);
    } catch (IOException e) {
        abortAndRelease(method);
        throw new ConnectionException(Activator.getDefault().createErrorStatus(e.getMessage(), e));
    }

    /* In case authentication required */
    int statusCode = method.getStatusCode();
    if (statusCode == HTTP_ERROR_AUTH_REQUIRED) {
        AuthState hostAuthState = method.getHostAuthState();
        String realm = hostAuthState != null ? hostAuthState.getRealm() : null;
        abortAndRelease(method);

        throw new AuthenticationRequiredException(realm, Activator.getDefault()
                .createErrorStatus(Messages.DefaultProtocolHandler_ERROR_AUTHENTICATION_REQUIRED, null));
    }

    /* In case sync authentication failed (Forbidden) */
    else if (isSyncAuthenticationIssue(method, authLink)) {
        abortAndRelease(method);

        throw new AuthenticationRequiredException(null, Activator.getDefault()
                .createErrorStatus(Messages.DefaultProtocolHandler_GR_ERROR_BAD_AUTH, null));
    }

    /* In case of Forbidden Status with Error Code (Google Reader) */
    else if (statusCode == HTTP_ERROR_FORBIDDEN && method.getResponseHeader(HEADER_RESPONSE_ERROR) != null)
        handleForbidden(method);

    /* In case proxy-authentication required / failed */
    else if (statusCode == HTTP_ERROR_PROXY_AUTH_REQUIRED) {
        abortAndRelease(method);

        throw new ProxyAuthenticationRequiredException(Activator.getDefault()
                .createErrorStatus(Messages.DefaultProtocolHandler_ERROR_PROXY_AUTHENTICATION_REQUIRED, null));
    }

    /* If status code is 4xx, throw an IOException with the status code included */
    else if (statusCode >= HTTP_ERRORS) {
        String error = getError(statusCode);
        abortAndRelease(method);

        if (error != null)
            throw new ConnectionException(Activator.getDefault()
                    .createErrorStatus(NLS.bind(Messages.DefaultProtocolHandler_ERROR_HTTP_STATUS_MSG,
                            String.valueOf(statusCode), error), null));

        throw new ConnectionException(Activator.getDefault().createErrorStatus(
                NLS.bind(Messages.DefaultProtocolHandler_ERROR_HTTP_STATUS, String.valueOf(statusCode)), null));
    }

    /* In case the Feed has not been modified since */
    else if (statusCode == HTTP_STATUS_NOT_MODIFIED) {
        abortAndRelease(method);

        throw new NotModifiedException(Activator.getDefault()
                .createInfoStatus(Messages.DefaultProtocolHandler_INFO_NOT_MODIFIED_SINCE, null));
    }

    /* In case response body is not available */
    if (inS == null) {
        abortAndRelease(method);

        throw new ConnectionException(Activator.getDefault()
                .createErrorStatus(Messages.DefaultProtocolHandler_ERROR_STREAM_UNAVAILABLE, null));
    }

    /* Check wether a Progress Monitor is provided to support early cancelation */
    IProgressMonitor monitor = null;
    if (properties != null && properties.containsKey(IConnectionPropertyConstants.PROGRESS_MONITOR))
        monitor = (IProgressMonitor) properties.get(IConnectionPropertyConstants.PROGRESS_MONITOR);

    /* Return a Stream that releases the connection once closed */
    return new HttpConnectionInputStream(link, method, monitor, inS);
}