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

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

Introduction

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

Prototype

public abstract void setFollowRedirects(boolean paramBoolean);

Source Link

Usage

From source file:ait.ffma.service.preservation.riskmanagement.api.PreservationRiskmanagementServiceImpl.java

/**
 * This method tries to establish HTTP connection for passed URI
 * @param uri The URI to verify//from w  w  w .  ja  v a 2  s .  co  m
 * @param responseLineList 
 *        This list collects response lines for broken URIs
 * @param brokenUriList
 *        This list collects broken URIs
 */
private void verifyUri(String uri, List<String> responseLineList, List<String> brokenUriList) {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    try {
        HttpMethod method = new GetMethod(uri);
        method.setFollowRedirects(true);
        client.executeMethod(method);
        int response = method.getStatusCode();
        if (response != 200) {
            StatusLine responseLine = method.getStatusLine();
            log.info("uri: " + uri + ", response: " + response + ", responseLine: " + responseLine.toString());
            brokenUriList.add(uri);
            responseLineList.add(responseLine.toString());
        }
        method.releaseConnection();
    } catch (IOException e) {
        log.info("Unable to connect to " + uri + " verification error: " + e);
        brokenUriList.add(uri);
        responseLineList.add(e.getMessage());
    }
}

From source file:it.geosdi.era.server.servlet.HTTPProxy.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse An object by which we can send the proxied
 *                             response back to the client
 * @param digest //from   www.  java  2 s .c  o m
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, String user, String password)
        throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();

    if (user != null && password != null) {
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, upc);
    }

    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(
                stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
        return;
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        // Skip GZIP Responses
        if (header.getName().equalsIgnoreCase(HTTP_HEADER_ACCEPT_ENCODING)
                && header.getValue().toLowerCase().contains("gzip"))
            continue;
        else if (header.getName().equalsIgnoreCase(HTTP_HEADER_CONTENT_ENCODING)
                && header.getValue().toLowerCase().contains("gzip"))
            continue;
        else if (header.getName().equalsIgnoreCase(HTTP_HEADER_TRANSFER_ENCODING))
            continue;
        else
            httpServletResponse.setHeader(header.getName(), header.getValue());
    }

    // Send the content to the client
    InputStream inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream();
    OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();

    int read;
    while ((read = inputStreamServerResponse.read()) > 0) {
        if (escapeHtmlFull(read) > 0) {
            outputStreamClientResponse.write(read);
        }
    }

    inputStreamServerResponse.close();

    outputStreamClientResponse.write('\n');
    outputStreamClientResponse.flush();
    outputStreamClientResponse.close();
}

From source file:net.oauth.client.httpclient3.HttpClient3.java

public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException {
    final String method = request.method;
    final String url = request.url.toExternalForm();
    final InputStream body = request.getBody();
    final boolean isDelete = DELETE.equalsIgnoreCase(method);
    final boolean isPost = POST.equalsIgnoreCase(method);
    final boolean isPut = PUT.equalsIgnoreCase(method);
    byte[] excerpt = null;
    HttpMethod httpMethod;
    if (isPost || isPut) {
        EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url);
        if (body != null) {
            ExcerptInputStream e = new ExcerptInputStream(body);
            String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
            entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e)
                    : new InputStreamRequestEntity(e, Long.parseLong(length)));
            excerpt = e.getExcerpt();/*from  w  w  w .j  av a2s . c o m*/
        }
        httpMethod = entityEnclosingMethod;
    } else if (isDelete) {
        httpMethod = new DeleteMethod(url);
    } else {
        httpMethod = new GetMethod(url);
    }
    for (Map.Entry<String, Object> p : parameters.entrySet()) {
        String name = p.getKey();
        String value = p.getValue().toString();
        if (FOLLOW_REDIRECTS.equals(name)) {
            httpMethod.setFollowRedirects(Boolean.parseBoolean(value));
        } else if (READ_TIMEOUT.equals(name)) {
            httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value));
        }
    }
    for (Map.Entry<String, String> header : request.headers) {
        httpMethod.addRequestHeader(header.getKey(), header.getValue());
    }
    HttpClient client = clientPool.getHttpClient(new URL(httpMethod.getURI().toString()));
    client.executeMethod(httpMethod);
    return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset());
}

From source file:com.xpn.xwiki.plugin.feed.XWikiFeedFetcher.java

/**
 * @see com.sun.syndication.fetcher.FeedFetcher#retrieveFeed(java.net.URL)
 *///from www . java 2  s  .  c  o  m
public SyndFeed retrieveFeed(URL feedUrl, int timeout)
        throws IllegalArgumentException, IOException, FeedException, FetcherException {
    if (feedUrl == null) {
        throw new IllegalArgumentException("null is not a valid URL");
    }
    HttpClient client = new HttpClient();
    if (timeout != 0) {
        client.getParams().setSoTimeout(timeout);
        client.getParams().setParameter("http.connection.timeout", new Integer(timeout));
    }

    System.setProperty("http.useragent", getUserAgent());
    client.getParams().setParameter("httpclient.useragent", getUserAgent());

    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if ((proxyHost != null) && (!proxyHost.equals(""))) {
        int port = 3128;
        if ((proxyPort != null) && (!proxyPort.equals(""))) {
            port = Integer.parseInt(proxyPort);
        }
        client.getHostConfiguration().setProxy(proxyHost, port);
    }

    String proxyUser = System.getProperty("http.proxyUser");
    if ((proxyUser != null) && (!proxyUser.equals(""))) {
        String proxyPassword = System.getProperty("http.proxyPassword");
        Credentials defaultcreds = new UsernamePasswordCredentials(proxyUser, proxyPassword);
        client.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
    }

    String urlStr = feedUrl.toString();
    FeedFetcherCache cache = getFeedInfoCache();
    if (cache != null) {
        // retrieve feed
        HttpMethod method = new GetMethod(urlStr);
        method.addRequestHeader("Accept-Encoding", "gzip");
        try {
            if (isUsingDeltaEncoding()) {
                method.setRequestHeader("A-IM", "feed");
            }

            // get the feed info from the cache
            // Note that syndFeedInfo will be null if it is not in the cache
            SyndFeedInfo syndFeedInfo = cache.getFeedInfo(feedUrl);
            if (syndFeedInfo != null) {
                method.setRequestHeader("If-None-Match", syndFeedInfo.getETag());

                if (syndFeedInfo.getLastModified() instanceof String) {
                    method.setRequestHeader("If-Modified-Since", (String) syndFeedInfo.getLastModified());
                }
            }

            method.setFollowRedirects(true);

            int statusCode = client.executeMethod(method);
            fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr);
            handleErrorCodes(statusCode);

            SyndFeed feed = getFeed(syndFeedInfo, urlStr, method, statusCode);

            syndFeedInfo = buildSyndFeedInfo(feedUrl, urlStr, method, feed, statusCode);

            cache.setFeedInfo(new URL(urlStr), syndFeedInfo);

            // the feed may have been modified to pick up cached values
            // (eg - for delta encoding)
            feed = syndFeedInfo.getSyndFeed();

            return feed;
        } finally {
            method.releaseConnection();
        }
    } else {
        // cache is not in use
        HttpMethod method = new GetMethod(urlStr);
        try {
            method.setFollowRedirects(true);

            int statusCode = client.executeMethod(method);
            fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr);
            handleErrorCodes(statusCode);

            return getFeed(null, urlStr, method, statusCode);
        } finally {
            method.releaseConnection();
        }
    }
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Executes the {@link org.apache.commons.httpclient.HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @throws java.io.IOException      Can be thrown by the {@link org.apache.commons.httpclient.HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 *//*from w w  w .j av  a2  s .  co  m*/
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    if (httpServletRequest.isSecure()) {
        Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    }
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    InputStream response = httpMethodProxyRequest.getResponseBodyAsStream();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(
                    stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        int length = 0;

        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz);
        } else {
            final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody());
            length = bytes.length;
            response = new ByteArrayInputStream(bytes);
        }
        httpServletResponse.setContentLength(length);
    }

    // Send the content to the client
    debug("Received status code: " + intProxyResponseCode, "Response: " + response);

    //httpServletResponse.getWriter().write(response);
    copy(response, httpServletResponse.getOutputStream());
}

From source file:com.rometools.fetcher.impl.HttpClientFeedFetcher.java

@Override
public SyndFeed retrieveFeed(final String userAgent, final URL feedUrl)
        throws IllegalArgumentException, IOException, FeedException, FetcherException {

    if (feedUrl == null) {
        throw new IllegalArgumentException("null is not a valid URL");
    }/*from  ww  w .j  a  va 2  s .  co  m*/

    final HttpClient client = new HttpClient(httpClientParams);

    if (credentialSupplier != null) {

        final HttpClientParams params = client.getParams();
        params.setAuthenticationPreemptive(true);

        final String host = feedUrl.getHost();
        final Credentials credentials = credentialSupplier.getCredentials(null, host);
        if (credentials != null) {
            final AuthScope authScope = new AuthScope(host, -1);
            final HttpState state = client.getState();
            state.setCredentials(authScope, credentials);
        }

    }

    System.setProperty("httpclient.useragent", userAgent);

    final String urlStr = feedUrl.toString();
    final HttpMethod method = new GetMethod(urlStr);

    if (customRequestHeaders == null) {
        method.addRequestHeader("Accept-Encoding", "gzip");
        method.addRequestHeader("User-Agent", userAgent);

    } else {
        for (final Map.Entry<String, String> entry : customRequestHeaders.entrySet()) {
            method.addRequestHeader(entry.getKey(), entry.getValue());
        }
        if (!customRequestHeaders.containsKey("Accept-Encoding")) {
            method.addRequestHeader("Accept-Encoding", "gzip");
        }
        if (!customRequestHeaders.containsKey("User-Agent")) {
            method.addRequestHeader("User-Agent", userAgent);
        }
    }

    method.setFollowRedirects(true);

    if (httpClientMethodCallback != null) {
        synchronized (httpClientMethodCallback) {
            httpClientMethodCallback.afterHttpClientMethodCreate(method);
        }
    }

    final FeedFetcherCache cache = getFeedInfoCache();

    if (cache != null) {
        // retrieve feed
        try {

            if (isUsingDeltaEncoding()) {
                method.setRequestHeader("A-IM", "feed");
            }

            // try to get the feed info from the cache
            SyndFeedInfo syndFeedInfo = cache.getFeedInfo(feedUrl);

            if (syndFeedInfo != null) {

                method.setRequestHeader("If-None-Match", syndFeedInfo.getETag());

                final Object lastModifiedHeader = syndFeedInfo.getLastModified();
                if (lastModifiedHeader instanceof String) {
                    method.setRequestHeader("If-Modified-Since", (String) lastModifiedHeader);
                }

            }

            final int statusCode = client.executeMethod(method);
            fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr);
            handleErrorCodes(statusCode);

            SyndFeed feed = getFeed(syndFeedInfo, urlStr, method, statusCode);

            syndFeedInfo = buildSyndFeedInfo(feedUrl, urlStr, method, feed, statusCode);

            cache.setFeedInfo(feedUrl, syndFeedInfo);

            // the feed may have been modified to pick up cached values
            // (eg - for delta encoding)
            feed = syndFeedInfo.getSyndFeed();

            return feed;

        } finally {

            method.releaseConnection();

        }

    } else {

        // cache is not in use
        try {

            final int statusCode = client.executeMethod(method);
            fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr);
            handleErrorCodes(statusCode);

            return getFeed(null, urlStr, method, statusCode);

        } finally {

            method.releaseConnection();

        }

    }

}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @param httpServletRequest Request object pertaining to the proxied HTTP request
 * @throws IOException      Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 *///from   w w w .  j av a2  s.c  om
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    getCredential(httpServletRequest.getParameter("servername"));
    if (credentials != null) {
        httpClient.getParams().setAuthenticationPreemptive(true);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    httpMethodProxyRequest.setFollowRedirects(true);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    String response = httpMethodProxyRequest.getResponseBodyAsString();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(stringLocation
                    .replace(getProxyHostAndPort(httpServletRequest) + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            response = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, response);
        } else {
            response = new String(ungzip(httpMethodProxyRequest.getResponseBody()));
        }
        httpServletResponse.setContentLength(response.length());
    }

    // Send the content to the client
    if (intProxyResponseCode == 200)
        httpServletResponse.getWriter().write(response);
    else
        httpServletResponse.getWriter().write(intProxyResponseCode);
}

From source file:com.dtolabs.client.utils.HttpClientChannel.java

/**
 * Perform the HTTP request.  Can only be performed once.
 *//*w  w w.  j  a va  2 s .c  om*/
public void makeRequest() throws IOException, HttpClientException {
    if (requestMade) {
        return;
    }

    requestMade = true;
    RequestEntity reqEntity = null;
    NameValuePair[] postBody = null;
    if (isPostMethod()) {
        setMethodType("POST");
    }
    HttpMethod method = initMethod();
    if (isPostMethod()) {
        reqEntity = getRequestEntity((PostMethod) method);
        if (null != reqEntity) {
            logger.debug("preparing to post request entity data: " + reqEntity.getContentType());

            ((PostMethod) method).setRequestEntity(reqEntity);
        } else {
            logger.debug("preparing to post form data");
            postBody = getRequestBody((PostMethod) method);
            ((PostMethod) method).setRequestBody(postBody);
        }
    }
    logger.debug("calling preMakeRequest");
    if (!preMakeRequest(method)) {
        return;
    }
    logger.debug("calling doAuthentication...");
    if (!doAuthentication(method)) {
        return;
    }
    int bytesread = 0;
    try {
        if (!isPostMethod()) {
            method.setFollowRedirects(true);
        }
        logger.debug("make request...");
        resultCode = httpc.executeMethod(method);
        reasonCode = method.getStatusText();
        if (isPostMethod()) {
            //check redirect after post
            method = checkFollowRedirect(method, resultCode);
        }
        logger.debug("check needs reauth...");

        if (needsReAuthentication(resultCode, method)) {
            logger.debug("re-authentication needed, performing...");
            method.releaseConnection();
            method.abort();
            //need to re-authenticate.
            method = initMethod();
            if (isPostMethod() && null != reqEntity) {
                ((PostMethod) method).setRequestEntity(reqEntity);
            } else if (isPostMethod() && null != postBody) {
                ((PostMethod) method).setRequestBody(postBody);
            }
            if (!doAuthentication(method)) {
                //user login failed
                return;
            }
            //user login has succeeded
            logger.debug("remaking original request...");
            resultCode = httpc.executeMethod(method);
            reasonCode = method.getStatusText();
            if (needsReAuthentication(resultCode, method)) {
                //user request was unauthorized
                throw new HttpClientException("Unauthorized Action: "
                        + (null != method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER)
                                ? method.getResponseHeader(Constants.X_RUNDECK_ACTION_UNAUTHORIZED_HEADER)
                                        .getValue()
                                : reasonCode));
            }
        }

        logger.debug("finish...");
        if (null != method.getResponseHeader("Content-Type")) {
            resultType = method.getResponseHeader("Content-Type").getValue();
        }
        String type = resultType;
        if (type != null && type.indexOf(";") > 0) {
            type = type.substring(0, type.indexOf(";")).trim();
        }
        if (null == expectedContentType || expectedContentType.equals(type)) {
            if (null != destinationStream && resultCode >= 200 && resultCode < 300) {
                //read the input stream and write it to the destination
                contentLengthRetrieved = Streams.copyStreamCount(method.getResponseBodyAsStream(),
                        destinationStream);
            } else {
                final ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(1024 * 50);
                Streams.copyStream(method.getResponseBodyAsStream(), outputBytes);
                resultStream = new ByteArrayInputStream(outputBytes.toByteArray());
            }
        }
        reqMadeMethod = method;
    } catch (HttpException e) {
        logger.error("HTTP error: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }

    logger.debug("Response received");
    postMakeRequest();
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given {@link HttpServletResponse}
 * /*from w  ww.j  ava  2  s .  co m*/
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse An object by which we can send the proxied response back to the client
 * @param digest
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, String user, String password, ProxyInfo proxyInfo)
        throws IOException, ServletException {

    if (user != null && password != null) {
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, upc);
    }

    httpMethodProxyRequest.setFollowRedirects(false);

    InputStream inputStreamServerResponse = null;
    ByteArrayOutputStream baos = null;

    try {

        // //////////////////////////
        // Execute the request
        // //////////////////////////

        int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);

        onRemoteResponse(httpMethodProxyRequest);

        // ////////////////////////////////////////////////////////////////////////////////
        // Check if the proxy response is a redirect
        // The following code is adapted from
        // org.tigris.noodle.filters.CheckForRedirect
        // Hooray for open source software
        // ////////////////////////////////////////////////////////////////////////////////

        if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
                && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {

            String stringStatusCode = Integer.toString(intProxyResponseCode);
            String stringLocation = httpMethodProxyRequest.getResponseHeader(Utils.LOCATION_HEADER).getValue();

            if (stringLocation == null) {
                throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                        + Utils.LOCATION_HEADER + " header was found in the response");
            }

            // /////////////////////////////////////////////
            // Modify the redirect to go to this proxy
            // servlet rather that the proxied host
            // /////////////////////////////////////////////

            String stringMyHostName = httpServletRequest.getServerName();

            if (httpServletRequest.getServerPort() != 80) {
                stringMyHostName += ":" + httpServletRequest.getServerPort();
            }

            stringMyHostName += httpServletRequest.getContextPath();
            httpServletResponse.sendRedirect(stringLocation.replace(
                    Utils.getProxyHostAndPort(proxyInfo) + proxyInfo.getProxyPath(), stringMyHostName));

            return;

        } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {

            // ///////////////////////////////////////////////////////////////
            // 304 needs special handling. See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // We get a 304 whenever passed an 'If-Modified-Since'
            // header and the data on disk has not changed; server
            // responds w/ a 304 saying I'm not going to send the
            // body because the file has not changed.
            // ///////////////////////////////////////////////////////////////

            httpServletResponse.setIntHeader(Utils.CONTENT_LENGTH_HEADER_NAME, 0);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

            return;
        }

        // /////////////////////////////////////////////
        // Pass the response code back to the client
        // /////////////////////////////////////////////

        httpServletResponse.setStatus(intProxyResponseCode);

        // /////////////////////////////////////////////
        // Pass response headers back to the client
        // /////////////////////////////////////////////

        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();

        for (Header header : headerArrayResponse) {

            // /////////////////////////
            // Skip GZIP Responses
            // /////////////////////////

            if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_ACCEPT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_CONTENT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_TRANSFER_ENCODING))
                continue;
            //                else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_WWW_AUTHENTICATE))
            //                    continue;                
            else
                httpServletResponse.setHeader(header.getName(), header.getValue());
        }

        // ///////////////////////////////////
        // Send the content to the client
        // ///////////////////////////////////

        inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream();

        if (inputStreamServerResponse != null) {
            byte[] b = new byte[proxyConfig.getDefaultStreamByteSize()];

            baos = new ByteArrayOutputStream(b.length);

            int read = 0;
            while ((read = inputStreamServerResponse.read(b)) > 0) {
                baos.write(b, 0, read);
                baos.flush();
            }

            baos.writeTo(httpServletResponse.getOutputStream());
        }

    } catch (HttpException e) {
        if (LOGGER.isLoggable(Level.SEVERE))
            LOGGER.log(Level.SEVERE, "Error executing HTTP method ", e);
    } finally {
        try {
            if (inputStreamServerResponse != null)
                inputStreamServerResponse.close();
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing request input stream ", e);
            throw new ServletException(e.getMessage());
        }

        try {
            if (baos != null) {
                baos.flush();
                baos.close();
            }
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing response stream ", e);
            throw new ServletException(e.getMessage());
        }

        httpMethodProxyRequest.releaseConnection();
    }
}

From source file:com.groupon.odo.Proxy.java

/**
 * Execute a request//from   www .j av  a2s . co m
 *
 * @param httpMethodProxyRequest
 * @param httpServletRequest
 * @param httpServletResponse
 * @param history
 * @param outStream
 * @throws Exception
 */
private void executeRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, History history, OutputStream outStream) throws Exception {
    int intProxyResponseCode = 999;
    try {
        // Create a default HttpClient
        HttpClient httpClient = new HttpClient();
        httpMethodProxyRequest.setFollowRedirects(false);
        ArrayList<String> headersToRemove = getRemoveHeaders();

        httpClient.getParams().setSoTimeout(60000);

        httpServletRequest.setAttribute("com.groupon.odo.removeHeaders", headersToRemove);
        intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    } catch (Exception e) {
        requestInformation.get().outputString = "TIMEOUT";
        logRequestHistory(httpMethodProxyRequest, httpServletResponse, history);
        throw e;
    }
    logger.info("Response code: {}, {}", intProxyResponseCode,
            HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {

        String stringStatusCode = Integer.toString(intProxyResponseCode);
        processRedirect(stringStatusCode, httpMethodProxyRequest, httpServletRequest, httpServletResponse);
    } else {
        // Pass the response code back to the client
        httpServletResponse.setStatus(intProxyResponseCode);

        // Pass response headers back to the client
        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
        for (Header header : headerArrayResponse) {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }

        // there is no data for a HTTP 304
        if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED) {
            // Send the content to the client
            InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);

            int intNextByte;
            // Collect all of the server data
            while ((intNextByte = bufferedInputStream.read()) != -1) {
                outStream.write(intNextByte);
            }
        }
    }
}