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

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

Introduction

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

Prototype

public abstract int getStatusCode();

Source Link

Usage

From source file:org.iavante.sling.gad.transcoder.TranscoderServiceImplIT.java

/**
 * Tests if the transcoder folder is created and the preview transformation
 * type// w  ww  .  java2s  .  c om
 **/
public void test_transcoder_folder() {

    try {
        Thread.sleep(4000);
    } catch (InterruptedException e1) {

        e1.printStackTrace();
    }

    // Get transcoder folder
    HttpMethod get_trans_folder = new GetMethod(SLING_URL + "/" + "content" + "/" + COMPONENTS_FOLDER + "/"
            + TRANSCODER_FOLDER + "/" + PREVIEW_TRANSFORMATION + ".html");
    get_trans_folder.setDoAuthentication(true);
    try {
        client.executeMethod(get_trans_folder);
    } catch (HttpException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

    assertEquals(200, get_trans_folder.getStatusCode());
    get_trans_folder.releaseConnection();
}

From source file:org.infoscoop.request.filter.ProxyFilterContainer.java

public final int invoke(HttpClient client, HttpMethod method, ProxyRequest request) throws Exception {
    int preStatus = prepareInvoke(client, method, request);
    switch (preStatus) {
    case 0:/*  w  w w.  j  a  va 2 s .  c  o m*/
        break;
    case EXECUTE_POST_STATUS:
        doFilterChain(request, request.getResponseBody());
    default:
        return preStatus;
    }
    // copy headers sent target server
    List ignoreHeaderNames = request.getIgnoreHeaders();
    List allowedHeaderNames = request.getAllowedHeaders();
    boolean allowAllHeader = false;

    Proxy proxy = request.getProxy();
    if (proxy != null) {
        allowAllHeader = proxy.isAllowAllHeader();
        if (!allowAllHeader)
            allowedHeaderNames.addAll(proxy.getAllowedHeaders());
    }

    AuthenticatorUtil.doAuthentication(client, method, request);

    StringBuffer headersSb = new StringBuffer();
    for (String name : request.getRequestHeaders().keySet()) {

        String value = request.getRequestHeader(name);
        String lowname = name.toLowerCase();

        if (!allowAllHeader && !allowedHeaderNames.contains(lowname))
            continue;

        if (ignoreHeaderNames.contains(lowname))
            continue;

        if ("cookie".equalsIgnoreCase(name)) {
            if (proxy.getSendingCookies() != null) {
                value = RequestUtil.removeCookieParam(value, proxy.getSendingCookies());
            }
        }

        if ("if-modified-since".equalsIgnoreCase(name) && "Thu, 01 Jun 1970 00:00:00 GMT".equals(value))
            continue;

        method.addRequestHeader(new Header(name, value));
        headersSb.append(name + "=" + value + ",  ");
    }

    int cacheStatus = getCache(client, method, request);
    if (cacheStatus != 0)
        return cacheStatus;

    if (log.isInfoEnabled())
        log.info("RequestHeader: " + headersSb);

    // execute http method and process redirect
    method.setFollowRedirects(false);

    client.executeMethod(method);

    int statusCode = method.getStatusCode();

    for (int i = 0; statusCode == HttpStatus.SC_MOVED_TEMPORARILY
            || statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_SEE_OTHER
            || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT; i++) {

        // connection release
        method.releaseConnection();

        if (i == 5) {
            log.error("The circular redirect is limited by five times.");
            return 500;
        }

        Header location = method.getResponseHeader("Location");
        String redirectUrl = location.getValue();

        // According to 2,068 1.1 rfc http spec, we cannot appoint the relative URL,
        // but microsoft.com gives back the relative URL.
        if (redirectUrl.startsWith("/")) {
            URI baseURI = method.getURI();
            baseURI.setPath(redirectUrl);

            redirectUrl = baseURI.toString();
        }

        //method.setURI(new URI(redirectUrl, false));
        Header[] headers = method.getRequestHeaders();
        method = new GetMethod(redirectUrl);
        for (int j = 0; j < headers.length; j++) {
            String headerName = headers[j].getName();
            if (!headerName.equalsIgnoreCase("content-length") && !headerName.equalsIgnoreCase("authorization"))
                method.setRequestHeader(headers[j]);
        }
        AuthenticatorUtil.doAuthentication(client, method, request);
        method.setRequestHeader("authorization", request.getRequestHeader("Authorization"));
        method.setFollowRedirects(false);
        client.executeMethod(method);
        statusCode = method.getStatusCode();
        request.setRedirectURL(redirectUrl);

        if (log.isInfoEnabled())
            log.info("Redirect " + request.getTargetURL() + " to " + location + ".");
    }

    // copy response headers to proxyReqeust
    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        request.putResponseHeader(headers[i].getName(), headers[i].getValue());
    }

    if (log.isInfoEnabled())
        log.info("Original Status:" + statusCode);

    // check response code
    if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        log.error("Proxy Authentication Required. Confirm ajax proxy setting.");
        throw new Exception(
                "Http Status 407, Proxy Authentication Required. Please contuct System Administrator.");
    }
    if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_RESET_CONTENT) {
        return statusCode;
    } else if (statusCode < 200 || statusCode >= 300) {
        request.setResponseBody(method.getResponseBodyAsStream());
        return statusCode;
    }

    // process response body
    InputStream responseStream = null;
    if (statusCode != HttpStatus.SC_NO_CONTENT) {
        if (request.allowUserPublicCache()) {
            byte[] responseBody = method.getResponseBody();

            Map<String, List<String>> responseHeaders = request.getResponseHeaders();
            if (request.getRedirectURL() != null)
                responseHeaders.put("X-IS-REDIRECTED-FROM",
                        Arrays.asList(new String[] { request.getRedirectURL() }));
            if (method instanceof GetMethod) {
                putCache(request.getOriginalURL(), new ByteArrayInputStream(responseBody), responseHeaders);
            }

            responseStream = new ByteArrayInputStream(responseBody);
        } else {
            responseStream = method.getResponseBodyAsStream();
        }
    }
    doFilterChain(request, responseStream);

    return statusCode != HttpStatus.SC_NO_CONTENT ? method.getStatusCode() : 200;
}

From source file:org.j2free.http.HttpCallable.java

public HttpCallResult call() throws IOException {
    HttpMethod method;

    if (task.method == HttpCallTask.Method.GET)
        method = new GetMethod(task.toString());
    else {//from   w ww. j a  v  a2s .co  m
        method = new PostMethod(task.url);

        String postBody = task.getExplicitPostBody();
        if (postBody != null) {

            ((PostMethod) method).setRequestEntity(new StringRequestEntity(postBody, "text/xml", null));
        } else {
            List<KeyValuePair<String, String>> params = task.getQueryParams();
            NameValuePair[] data = new NameValuePair[params.size()];

            int i = 0;
            for (KeyValuePair<String, String> param : params) {
                data[i] = new NameValuePair(param.key, param.value);
                i++;
            }

            ((PostMethod) method).setRequestBody(data);
        }
    }

    for (Header header : task.getRequestHeaders()) {
        method.setRequestHeader(header);
    }

    method.setFollowRedirects(task.followRedirects);

    try {
        if (log.isDebugEnabled())
            log.debug("Making HTTP call [url=" + task.toString() + "]");

        client.executeMethod(method);

        if (log.isDebugEnabled())
            log.debug("Call returned [status=" + method.getStatusCode() + "]");

        return new HttpCallResult(method);
    } finally {
        // ALWAYS release the connection!!!
        method.releaseConnection();
    }
}

From source file:org.jboss.orion.openshift.server.proxy.JsonProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param proxyDetails/*from   ww  w. j  a  v  a 2  s .c o 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
 * @throws java.io.IOException            Can be thrown by the {@link HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    httpMethodProxyRequest.setDoAuthentication(false);
    httpMethodProxyRequest.setFollowRedirects(false);

    // Create a default HttpClient
    HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest);

    // Execute the request
    int intProxyResponseCode = 500;
    try {
        intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // 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();
        httpServletResponse.sendRedirect(stringLocation
                .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.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 (!ProxySupport.isHopByHopHeader(header.getName())) {
            if (ProxySupport.isSetCookieHeader(header)) {
                HttpProxyRule proxyRule = proxyDetails.getProxyRule();
                String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(),
                        proxyRule.getCookiePath(), proxyRule.getCookieDomain());
                httpServletResponse.setHeader(header.getName(), setCookie);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        }
    }

    // check if we got data, that is either the Content-Length > 0
    // or the response code != 204
    int code = httpMethodProxyRequest.getStatusCode();
    boolean noData = code == HttpStatus.SC_NO_CONTENT;
    if (!noData) {
        String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME);
        if (length != null && "0".equals(length.trim())) {
            noData = true;
        }
    }

    if (!noData) {
        // Send the content to the client
        InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        int intNextByte;
        while ((intNextByte = bufferedInputStream.read()) != -1) {
            outputStreamClientResponse.write(intNextByte);
        }
    }
}

From source file:org.jboss.test.web.jbas8318.unit.ResourceInjectionOnNonJavaEEComponentsTestCase.java

/**
 * Tests that Java EE resource injection in a JSF managed bean works as expected
 *
 * @throws Exception// ww  w . j ava  2s.co m
 */
public void testInjectionInJSFManagedBean() throws Exception {
    URL url = new URL(baseURL + "jbas-8318/test-jsf-injection.jsf");
    HttpMethod request = HttpUtils.accessURL(url);
    int statusCode = request.getStatusCode();
    logger.info("Got status code: " + statusCode + " for URL " + url);
    String response = request.getResponseBodyAsString();
    logger.info("Response for URL " + url + " is " + response);
    // no exceptions == injection worked fine and test passed.
    // TODO: We might want to test for the html output to really make sure of the output.
}

From source file:org.jboss.web.loadbalancer.Loadbalancer.java

protected void parseServerResponse(HttpServletRequest request, HttpServletResponse response, HttpClient client,
        HttpMethod method) throws ServletException, IOException {
    response.setStatus(method.getStatusCode());

    //Cookies/* ww  w . j  av a  2  s.com*/
    org.apache.commons.httpclient.Cookie[] respCookies = client.getState().getCookies();

    for (int i = 0; i < respCookies.length; ++i) {
        Cookie cookie = new Cookie(respCookies[i].getName(), respCookies[i].getValue());

        if (respCookies[i].getPath() != null) {
            cookie.setPath(respCookies[i].getPath());
        }
        response.addCookie(cookie);
    }

    Header[] header = method.getResponseHeaders();

    for (int i = 0; i < header.length; ++i) {
        if (!ignorableHeader.contains(header[i].getName().toLowerCase())) {
            response.setHeader(header[i].getName(), header[i].getValue());
        }
    }

    copyServerResponse(response, method);
}

From source file:org.jetbrains.plugins.github.api.GithubApiUtil.java

private static void checkStatusCode(@NotNull HttpMethod method) throws IOException {
    int code = method.getStatusCode();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;//w w w .  j  a  v  a 2 s .  c  om
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        throw new GithubAuthenticationException("Request response: " + getErrorMessage(method));
    default:
        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
    }
}

From source file:org.jivesoftware.openfire.clearspace.ClearspaceManager.java

/**
 * Makes a rest request of any type at the specified urlSuffix. The urlSuffix should be of the
 * form /userService/users./*ww  w. jav a  2s  .c om*/
 * If CS throws an exception it handled and transalated to a Openfire exception if possible.
 * This is done using the check fault method that tries to throw the best maching exception.
 *
 * @param type      Must be GET or DELETE
 * @param urlSuffix The url suffix of the rest request
 * @param xmlParams The xml with the request params, must be null if type is GET or DELETE only
 * @return The response as a xml doc.
 * @throws ConnectionException Thrown if there are issues perfoming the request.
 * @throws Exception Thrown if the response from Clearspace contains an exception.
 */
public Element executeRequest(HttpType type, String urlSuffix, String xmlParams)
        throws ConnectionException, Exception {
    if (Log.isDebugEnabled()) {
        Log.debug("Outgoing REST call [" + type + "] to " + urlSuffix + ": " + xmlParams);
    }

    String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix;

    String secret = getSharedSecret();

    HttpClient client = new HttpClient();
    HttpMethod method;

    // Configures the authentication
    client.getParams().setAuthenticationPreemptive(true);
    Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret);
    AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM);
    client.getState().setCredentials(scope, credentials);

    // Creates the method
    switch (type) {
    case GET:
        method = new GetMethod(wsUrl);
        break;
    case POST:
        PostMethod pm = new PostMethod(wsUrl);
        StringRequestEntity requestEntity = new StringRequestEntity(xmlParams);
        pm.setRequestEntity(requestEntity);
        method = pm;
        break;
    case PUT:
        PutMethod pm1 = new PutMethod(wsUrl);
        StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams);
        pm1.setRequestEntity(requestEntity1);
        method = pm1;
        break;
    case DELETE:
        method = new DeleteMethod(wsUrl);
        break;
    default:
        throw new IllegalArgumentException();
    }

    method.setRequestHeader("Accept", "text/xml");
    method.setDoAuthentication(true);

    try {
        // Executes the request
        client.executeMethod(method);

        // Parses the result
        String body = method.getResponseBodyAsString();
        if (Log.isDebugEnabled()) {
            Log.debug("Outgoing REST call results: " + body);
        }

        // Checks the http status
        if (method.getStatusCode() != 200) {
            if (method.getStatusCode() == 401) {
                throw new ConnectionException("Invalid password to connect to Clearspace.",
                        ConnectionException.ErrorType.AUTHENTICATION);
            } else if (method.getStatusCode() == 404) {
                throw new ConnectionException("Web service not found in Clearspace.",
                        ConnectionException.ErrorType.PAGE_NOT_FOUND);
            } else if (method.getStatusCode() == 503) {
                throw new ConnectionException("Web service not avaible in Clearspace.",
                        ConnectionException.ErrorType.SERVICE_NOT_AVAIBLE);
            } else {
                throw new ConnectionException(
                        "Error connecting to Clearspace, http status code: " + method.getStatusCode(),
                        new HTTPConnectionException(method.getStatusCode()),
                        ConnectionException.ErrorType.OTHER);
            }
        } else if (body.contains("Clearspace Upgrade Console")) {
            //TODO Change CS to send a more standard error message
            throw new ConnectionException("Clearspace is in an update state.",
                    ConnectionException.ErrorType.UPDATE_STATE);
        }

        Element response = localParser.get().parseDocument(body).getRootElement();

        // Check for exceptions
        checkFault(response);

        // Since there is no exception, returns the response
        return response;
    } catch (DocumentException e) {
        throw new ConnectionException("Error parsing the response of Clearspace.", e,
                ConnectionException.ErrorType.OTHER);
    } catch (HttpException e) {
        throw new ConnectionException("Error performing http request to Clearspace", e,
                ConnectionException.ErrorType.OTHER);
    } catch (UnknownHostException e) {
        throw new ConnectionException("Unknown Host " + getConnectionURI() + " trying to connect to Clearspace",
                e, ConnectionException.ErrorType.UNKNOWN_HOST);
    } catch (IOException e) {
        throw new ConnectionException("Error peforming http request to Clearspace.", e,
                ConnectionException.ErrorType.OTHER);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.jivesoftware.openfire.crowd.CrowdManager.java

private void handleHTTPError(HttpMethod method) throws RemoteException {
    int status = method.getStatusCode();
    String statusText = method.getStatusText();
    String body = null;//from ww  w. ja v a  2s .  c  om
    try {
        body = method.getResponseBodyAsString();
    } catch (IOException ioe) {
        LOG.warn("Unable to retreive Crowd http response body", ioe);
    }

    StringBuilder strBuf = new StringBuilder();
    strBuf.append("Crowd returned HTTP error code:").append(status);
    strBuf.append(" - ").append(statusText);
    if (StringUtils.isNotBlank(body)) {
        strBuf.append("\n").append(body);
    }

    throw new RemoteException(strBuf.toString());
}

From source file:org.josso.gl2.gateway.reverseproxy.ReverseProxyValve.java

/**
 * Intercepts Http request and redirects it to the configured SSO partner application.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 * @exception IOException if an input/output error occurs
 * @exception javax.servlet.ServletException if a servlet error occurs
 *///from   w w w  .  j  ava  2 s . c o  m
public int invoke(Request request, Response response) throws IOException, ServletException {

    if (debug >= 1)
        log("ReverseProxyValve Acting.");

    ProxyContextConfig[] contexts = _rpc.getProxyContexts();

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    HttpServletRequest hsr = (HttpServletRequest) request.getRequest();
    String uri = hsr.getRequestURI();

    String uriContext = null;

    StringTokenizer st = new StringTokenizer(uri.substring(1), "/");
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        uriContext = "/" + token;
        break;
    }

    if (uriContext == null)
        uriContext = uri;

    // Obtain the target host from the
    String proxyForwardHost = null;
    String proxyForwardUri = null;

    for (int i = 0; i < contexts.length; i++) {
        if (contexts[i].getContext().equals(uriContext)) {
            log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost()
                    + contexts[i].getForwardUri());
            proxyForwardHost = contexts[i].getForwardHost();
            proxyForwardUri = contexts[i].getForwardUri();
            break;
        }
    }

    if (proxyForwardHost == null) {
        log("URI '" + uri + "' can't be mapped to host");
        //valveContext.invokeNext(request, response);
        return Valve.INVOKE_NEXT;
    }

    if (proxyForwardUri == null) {
        // trim the uri context before submitting the http request
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = uri.substring(uriTrailStartPos);
    } else {
        int uriTrailStartPos = uri.substring(1).indexOf("/") + 1;
        proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos);
    }

    // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri);

    HttpMethod method;

    // to be moved to a builder which instantiates and build concrete methods.
    if (hsr.getMethod().equals(METHOD_GET)) {
        // Create a method instance.
        HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = getMethod;
    } else if (hsr.getMethod().equals(METHOD_POST)) {
        // Create a method instance.
        PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        postMethod.setRequestBody(hsr.getInputStream());
        method = postMethod;
    } else if (hsr.getMethod().equals(METHOD_HEAD)) {
        // Create a method instance.
        HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
        method = headMethod;
    } else if (hsr.getMethod().equals(METHOD_PUT)) {
        method = new PutMethod(proxyForwardHost + proxyForwardUri
                + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : ""));
    } else
        throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod());

    // copy incoming http headers to reverse proxy request
    Enumeration hne = hsr.getHeaderNames();
    while (hne.hasMoreElements()) {
        String hn = (String) hne.nextElement();

        // Map the received host header to the target host name
        // so that the configured virtual domain can
        // do the proper handling.
        if (hn.equalsIgnoreCase("host")) {
            method.addRequestHeader("Host", proxyForwardHost);
            continue;
        }

        Enumeration hvals = hsr.getHeaders(hn);
        while (hvals.hasMoreElements()) {
            String hv = (String) hvals.nextElement();
            method.addRequestHeader(hn, hv);
        }
    }

    // Add Reverse-Proxy-Host header
    String reverseProxyHost = getReverseProxyHost(request);
    method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost);

    if (debug >= 1)
        log("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost);

    // DO NOT follow redirects !
    method.setFollowRedirects(false);

    // By default the httpclient uses HTTP v1.1. We are downgrading it
    // to v1.0 so that the target server doesn't set a reply using chunked
    // transfer encoding which doesn't seem to be handled properly.
    // Check how to make chunked transfer encoding work.
    client.getParams().setVersion(new HttpVersion(1, 0));

    // Execute the method.
    int statusCode = -1;
    try {
        // execute the method.
        statusCode = client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        log("A recoverable exception occurred " + e.getMessage());
    } catch (IOException e) {
        log("Failed to connect.");
        e.printStackTrace();
    }

    // Check that we didn't run out of retries.
    if (statusCode == -1) {
        log("Failed to recover from exception.");
    }

    // Read the response body.
    byte[] responseBody = method.getResponseBody();

    // Release the connection.
    method.releaseConnection();

    HttpServletResponse sres = (HttpServletResponse) response.getResponse();

    // First thing to do is to copy status code to response, otherwise
    // catalina will do it as soon as we set a header or some other part of the response.
    sres.setStatus(method.getStatusCode());

    // copy proxy response headers to client response
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header responseHeader = responseHeaders[i];
        String name = responseHeader.getName();
        String value = responseHeader.getValue();

        // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses
        // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the
        // backend servers which stay behind the reverse proxy
        switch (method.getStatusCode()) {
        case HttpStatus.SC_MOVED_TEMPORARILY:
        case HttpStatus.SC_MOVED_PERMANENTLY:
        case HttpStatus.SC_SEE_OTHER:
        case HttpStatus.SC_TEMPORARY_REDIRECT:

            if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name)
                    || "URI".equalsIgnoreCase(name)) {

                // Check that this redirect must be adjusted.
                if (value.indexOf(proxyForwardHost) >= 0) {
                    String trail = value.substring(proxyForwardHost.length());
                    value = getReverseProxyHost(request) + trail;
                    if (debug >= 1)
                        log("Adjusting redirect header to " + value);
                }
            }
            break;

        } //end of switch
        sres.addHeader(name, value);

    }

    // Sometimes this is null, when no body is returned ...
    if (responseBody != null && responseBody.length > 0)
        sres.getOutputStream().write(responseBody);

    sres.getOutputStream().flush();

    if (debug >= 1)
        log("ReverseProxyValve finished.");

    return Valve.END_PIPELINE;
}