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

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

Introduction

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

Prototype

@Override
public Header getResponseHeader(String headerName) 

Source Link

Document

Gets the response header associated with the given name.

Usage

From source file:org.portletbridge.portlet.PortletBridgeServlet.java

protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // get the id
    final String id = portletBridgeService.getIdFromRequestUri(request.getContextPath(),
            request.getRequestURI());/*w  w w  .  ja va2  s. c om*/
    // look up the data associated with that id from the session
    HttpSession session = request.getSession();
    if (session == null) {
        throw new ServletException(resourceBundle.getString("error.nosession"));
    }
    final PortletBridgeMemento memento = (PortletBridgeMemento) session.getAttribute(mementoSessionKey);
    if (memento == null) {
        throw new ServletException(resourceBundle.getString("error.nomemento"));
    }
    final BridgeRequest bridgeRequest = memento.getBridgeRequest(id);
    if (bridgeRequest == null) {
        throw new ServletException(resourceBundle.getString("error.nobridgerequest"));
    }
    final PerPortletMemento perPortletMemento = memento.getPerPortletMemento(bridgeRequest.getPortletId());
    if (perPortletMemento == null) {
        throw new ServletException(resourceBundle.getString("error.noperportletmemento"));
    }

    // go and fetch the data from the backend as appropriate
    final URI url = bridgeRequest.getUrl();

    log.debug("doPost(): URL=" + url);

    try {
        PostMethod postMethod = new PostMethod(url.toString());
        copyRequestHeaders(request, postMethod);
        postMethod.setRequestEntity(new InputStreamRequestEntity(request.getInputStream()));
        httpClientTemplate.service(postMethod, perPortletMemento, new HttpClientCallback() {
            public Object doInHttpClient(int statusCode, HttpMethodBase method)
                    throws ResourceException, Throwable {
                if (statusCode == HttpStatus.SC_OK) {
                    // if it's text/html then store it and redirect
                    // back to the portlet render view (portletUrl)
                    Header responseHeader = method.getResponseHeader("Content-Type");
                    if (responseHeader != null && responseHeader.getValue().startsWith("text/html")) {
                        String content = ResourceUtil.getString(method.getResponseBodyAsStream(),
                                method.getResponseCharSet());
                        // TODO: think about cleaning this up if we
                        // don't get back to the render
                        perPortletMemento.enqueueContent(bridgeRequest.getId(),
                                new PortletBridgeContent(url, "post", content));
                        // redirect
                        // TODO: worry about this... adding the id
                        // at the end

                        log.debug("doPost(): doing response.sendRedirect to URL=" + bridgeRequest.getPageUrl());

                        response.sendRedirect(bridgeRequest.getPageUrl());
                    } else {
                        // if it's anything else then stream it
                        // back... consider stylesheets and
                        // javascript
                        // TODO: javascript and css rewriting
                        response.setContentType(method.getResponseHeader("Content-Type").toExternalForm());
                        ResourceUtil.copy(method.getResponseBodyAsStream(), response.getOutputStream(), 4096);
                    }
                } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                    Header locationHeader = method.getResponseHeader("Location");
                    if (locationHeader != null) {
                        URI redirectUrl = new URI(locationHeader.getValue().trim());
                        log.debug("redirecting to [" + redirectUrl + "]");
                        PseudoRenderResponse renderResponse = createRenderResponse(bridgeRequest);
                        BridgeRequest updatedBridgeRequest = memento.createBridgeRequest(renderResponse,
                                new DefaultIdGenerator().nextId(), redirectUrl);
                        fetch(request, response, updatedBridgeRequest, memento, perPortletMemento, redirectUrl);

                    } else {
                        throw new PortletBridgeException("error.missingLocation");
                    }
                } else {
                    // if there is a problem with the status code
                    // then return that error back
                    response.sendError(statusCode);
                }
                return null;
            }
        });
    } catch (ResourceException resourceException) {
        String format = MessageFormat.format(resourceBundle.getString(resourceException.getMessage()),
                resourceException.getArgs());
        throw new ServletException(format, resourceException);
    }
}

From source file:org.rssowl.core.connection.HttpConnectionInputStream.java

/**
 * Creates a <code>HttpConnectionInputStream</code> by assigning the argument
 * <code>inS</code> to the field <code>this.in</code> so as to remember it for
 * later use.//from   ww w .j  a  v a2  s .  c  om
 *
 * @param link the {@link URI} that was used to create the Stream.
 * @param method The Method holding the connection of the given Stream.
 * @param monitor A ProgressMonitor to support early cancelation, or
 * <code>NULL</code> if no monitor is being used.
 * @param inS the underlying input Stream.
 */
public HttpConnectionInputStream(URI link, HttpMethodBase method, IProgressMonitor monitor, InputStream inS) {
    super(inS);
    fLink = link;
    fMethod = method;
    fMonitor = monitor;

    /* Keep some important Headers */
    Header headerLastModified = method.getResponseHeader(HEADER_RESPONSE_LAST_MODIFIED);
    if (headerLastModified != null)
        setIfModifiedSince(headerLastModified.getValue());

    Header headerETag = method.getResponseHeader(HEADER_RESPONSE_ETAG);
    if (headerETag != null)
        setIfNoneMatch(headerETag.getValue());
}

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();// w ww .  j  a  va2 s  . c  o  m

    /* 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);
}

From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java

private boolean isSyncAuthenticationIssue(HttpMethodBase method, URI link) {

    /* Handle Google Error Response "Forbidden" for synced connections */
    if (method.getStatusCode() == HTTP_ERROR_FORBIDDEN && SyncUtils.fromGoogle(link.toString())) {
        Header errorHeader = method.getResponseHeader(HEADER_RESPONSE_ERROR);
        if (errorHeader == null || ERROR_BAD_AUTH.equals(errorHeader.getValue()))
            return true;
    }/*from   ww  w .  ja v a2 s.  c om*/

    return false;
}

From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java

protected void handleForbidden(HttpMethodBase method) throws ConnectionException {
    String errorMsg = null;//  w  ww  .j  a va 2s . co  m
    String errorUrl = null;

    /* Lookup Google Error if present */
    Header errorHeader = method.getResponseHeader(HEADER_RESPONSE_ERROR);
    if (errorHeader != null && StringUtils.isSet(errorHeader.getValue())) {
        String errorCode = errorHeader.getValue();
        if (ERROR_BAD_AUTH.equals(errorCode))
            errorMsg = Messages.DefaultProtocolHandler_GR_ERROR_BAD_AUTH;
        else if (ERROR_NOT_VERIFIED.equals(errorCode))
            errorMsg = Messages.DefaultProtocolHandler_GR_ERROR_NOT_VERIFIED;
        else if (ERROR_NO_TERMS.equals(errorCode))
            errorMsg = Messages.DefaultProtocolHandler_GR_ERROR_NO_TERMS;
        else if (ERROR_UNKNOWN.equals(errorCode))
            errorMsg = Messages.DefaultProtocolHandler_GR_ERROR_UNKNOWN;
        else if (ERROR_ACCOUNT_DELETED.equals(errorCode))
            errorMsg = Messages.DefaultProtocolHandler_GR_ERROR_ACCOUNT_DELETED;
        else if (ERROR_ACCOUNT_DISABLED.equals(errorCode))
            errorMsg = Messages.DefaultProtocolHandler_GR_ERROR_ACCOUNT_DISABLED;
        else if (ERROR_SERVICE_DISABLED.equals(errorCode))
            errorMsg = Messages.DefaultProtocolHandler_GR_ERROR_SERVICE_DISABLED;
        else if (ERROR_SERVICE_UNAVAILABLE.equals(errorCode))
            errorMsg = Messages.DefaultProtocolHandler_GR_ERROR_SERVICE_UNAVAILABLE;
        else if (ERROR_CAPTCHA_REQUIRED.equals(errorCode)) {
            errorMsg = Messages.DefaultProtocolHandler_GR_ERROR_CAPTCHA_REQUIRED;
            errorUrl = SyncUtils.CAPTCHA_UNLOCK_URL;
        }

        /* Also look up specified Error URL as necessary */
        if (errorUrl == null) {
            Header urlHeader = method.getResponseHeader(HEADER_RESPONSE_URL);
            if (urlHeader != null && StringUtils.isSet(urlHeader.getValue()))
                errorUrl = urlHeader.getValue();
        }
    }

    /* Otherwise throw generic Forbidden Exception */
    if (errorMsg == null)
        errorMsg = Messages.DefaultProtocolHandler_ERROR_FORBIDDEN;

    abortAndRelease(method);

    if (errorUrl != null)
        throw new SyncConnectionException(errorUrl, Activator.getDefault().createErrorStatus(errorMsg, null));

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

From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java

private InputStream pipeStream(InputStream inputStream, HttpMethodBase method) throws IOException {
    Assert.isNotNull(inputStream);/*  w w  w.  j  av a  2s  .co  m*/

    /* Retrieve the Content Encoding */
    String contentEncoding = method.getResponseHeader(HEADER_RESPONSE_CONTENT_ENCODING) != null
            ? method.getResponseHeader(HEADER_RESPONSE_CONTENT_ENCODING).getValue()
            : null;
    boolean isGzipStream = false;

    /*
     * Return in case the Content Encoding is not given and the InputStream does
     * not support mark() and reset()
     */
    if ((contentEncoding == null || !contentEncoding.equals("gzip")) && !inputStream.markSupported()) //$NON-NLS-1$
        return inputStream;

    /* Content Encoding is set to gzip, so use the GZipInputStream */
    if (contentEncoding != null && contentEncoding.equals("gzip")) { //$NON-NLS-1$
        isGzipStream = true;
    }

    /* Detect if the Stream is gzip encoded */
    else if (inputStream.markSupported()) {
        inputStream.mark(2);
        int id1 = inputStream.read();
        int id2 = inputStream.read();
        inputStream.reset();

        /* Check for GZip Magic Numbers (See RFC 1952) */
        if (id1 == 0x1F && id2 == 0x8B)
            isGzipStream = true;
    }

    /* Create the GZipInputStream then */
    if (isGzipStream) {
        try {
            return new GZIPInputStream(inputStream);
        } catch (IOException e) {
            return inputStream;
        }
    }
    return inputStream;
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

@Override
protected boolean checkRemoteAvailability(long newerThen, ProxyRepository repository,
        ResourceStoreRequest request, boolean isStrict) throws RemoteStorageException {
    URL remoteURL = getAbsoluteUrlFromBase(repository, request);

    HttpMethodBase method = new HeadMethod(remoteURL.toString());

    int response = HttpStatus.SC_BAD_REQUEST;

    // artifactory hack, it pukes on HEAD so we will try with GET if HEAD fails
    boolean doGet = false;

    try {// ww  w.  java  2 s .  c  o m
        response = executeMethod(repository, request, method, remoteURL);
    } catch (RemoteStorageException e) {
        // If HEAD failed, attempt a GET. Some repos may not support HEAD method
        doGet = true;

        getLogger().debug("HEAD method failed, will attempt GET.  Exception: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();

        // HEAD returned error, but not exception, try GET before failing
        if (!doGet && response != HttpStatus.SC_OK) {
            doGet = true;

            getLogger().debug("HEAD method failed, will attempt GET.  Status: " + response);
        }
    }

    if (doGet) {
        // create a GET
        method = new GetMethod(remoteURL.toString());

        try {
            // execute it
            response = executeMethod(repository, request, method, remoteURL);
        } finally {
            // and release it immediately
            method.releaseConnection();
        }
    }

    // if we are not strict and remote is S3
    if (!isStrict && isRemotePeerAmazonS3Storage(repository)) {
        // if we are relaxed, we will accept any HTTP response code below 500. This means anyway the HTTP
        // transaction succeeded. This method was never really detecting that the remoteUrl really denotes a root of
        // repository (how could we do that?)
        // this "relaxed" check will help us to "pass" S3 remote storage.
        return response >= HttpStatus.SC_OK && response <= HttpStatus.SC_INTERNAL_SERVER_ERROR;
    } else {
        // non relaxed check is strict, and will select only the OK response
        if (response == HttpStatus.SC_OK) {
            // we have it
            // we have newer if this below is true
            return makeDateFromHeader(method.getResponseHeader("last-modified")) > newerThen;
        } else if ((response >= HttpStatus.SC_MULTIPLE_CHOICES && response < HttpStatus.SC_BAD_REQUEST)
                || response == HttpStatus.SC_NOT_FOUND) {
            return false;
        } else {
            throw new RemoteStorageException("Unexpected response code while executing " + method.getName()
                    + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                    + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString()
                    + "\"]. Expected: \"SUCCESS (200)\". Received: " + response + " : "
                    + HttpStatus.getStatusText(response));
        }
    }
}

From source file:org.tinygroup.httpvisit.impl.HttpVisitorImpl.java

String execute(HttpMethodBase method) {
    try {//from w  ww .jav a 2 s .c  o m
        if (client == null) {
            init();
        }
        LOGGER.logMessage(LogLevel.DEBUG, "?:{}", method.getURI().toString());
        if (!("ISO-8859-1").equals(requestCharset)) {
            method.addRequestHeader("Content-Type", "text/html; charset=" + requestCharset);
        }
        method.setDoAuthentication(authEnabled);
        int iGetResultCode = client.executeMethod(method);
        if (iGetResultCode == HttpStatus.SC_OK) {
            LOGGER.logMessage(LogLevel.DEBUG, "?");
            Header responseHeader = method.getResponseHeader("Content-Encoding");
            if (responseHeader != null) {
                String acceptEncoding = responseHeader.getValue();
                if (acceptEncoding != null && ("gzip").equals(acceptEncoding)) {
                    //gzip?
                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                            method.getResponseBody());
                    GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
                    return IOUtils.readFromInputStream(gzipInputStream, responseCharset);
                }
            }
            return new String(method.getResponseBody(), responseCharset);
        }
        LOGGER.logMessage(LogLevel.ERROR, "{}",
                method.getStatusLine().toString());
        throw new RuntimeException(method.getStatusLine().toString());
    } catch (Exception e) {
        LOGGER.logMessage(LogLevel.DEBUG, "{}", e.getMessage());
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.zend.php.zendserver.deployment.core.targets.OpenShiftTargetInitializer.java

private String executeEula(String url, Map<String, String> params) {
    HttpClient client = new HttpClient();
    HttpMethodBase method = createPostRequest(url, params);

    if (method != null) {
        int statusCode = -1;
        try {/*from  w ww  .ja v  a 2 s .c  om*/
            statusCode = client.executeMethod(method);
            if (statusCode == 302) {
                Header sessionId = method.getResponseHeader("Set-Cookie"); //$NON-NLS-1$
                String value = sessionId.getValue();
                String[] segments = value.split(";"); //$NON-NLS-1$
                for (String segment : segments) {
                    if (segment.startsWith(SESSION_ID)) {
                        String[] parts = segment.split("="); //$NON-NLS-1$
                        if (parts.length > 1) {
                            return parts[1].trim();
                        }
                    }
                }
            }
        } catch (IOException e) {
            DeploymentCore.log(e);
        } finally {
            method.releaseConnection();
        }
    }
    return null;
}

From source file:org.zend.sdklib.internal.target.ApiKeyDetector.java

private String executeLogin(String url, Map<String, String> params) throws SdkException {
    HttpClient client = new HttpClient();
    HttpMethodBase method = createPostRequest(url, params);
    if (method != null) {
        int statusCode = -1;
        try {/*w ww  . j av a 2s  .  c  o  m*/
            statusCode = client.executeMethod(method);
            if (statusCode == 302) {
                Header sessionId = method.getResponseHeader("Set-Cookie"); //$NON-NLS-1$
                String value = sessionId.getValue();
                String[] segments = value.split(";"); //$NON-NLS-1$
                String currentValue = null;
                for (String segment : segments) {
                    String[] parts = segment.split(","); //$NON-NLS-1$
                    for (String part : parts) {
                        if (part.trim().startsWith(SESSION_ID)) {
                            String[] id = part.split("="); //$NON-NLS-1$
                            if (id.length > 1) {
                                currentValue = id[1].trim();
                            }
                        }
                    }
                }
                return currentValue;
            } else if (statusCode == 200) {
                throw new InvalidCredentialsException();
            }
        } catch (IOException e) {
            throw new SdkException(e);
        } finally {
            method.releaseConnection();
        }
    }
    return null;
}