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

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

Introduction

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

Prototype

public abstract byte[] getResponseBody() throws IOException;

Source Link

Usage

From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java

@Test
public void shouldGetLiveReloadScriptWithProxyEnabled() throws Exception {
    // pre-condition
    createAndLaunchLiveReloadServer(true);
    // operation//w  w  w .j  a va  2 s .com
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod("http://localhost:" + liveReloadServerPort + "/livereload.js");
    method.addRequestHeader("Accept", "text/javascript");
    int status = client.executeMethod(method);
    // verification
    assertThat(status).isEqualTo(HttpStatus.SC_OK);
    // Read the response body.
    String responseBody = new String(method.getResponseBody());
    assertThat(responseBody).isNotEmpty();
}

From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java

@Test
public void shouldNotInjectLiveReloadScriptInCssPage() throws Exception {
    createAndLaunchLiveReloadServer(false);
    final String scriptContent = new StringBuilder(
            "<script>document.write('<script src=\"http://' + location.host.split(':')[0]+ ':")
                    .append(liveReloadServerPort).append("/livereload.js\"></'+ 'script>')</script>")
                    .toString();//from  w  w  w  .  j  a  v  a 2s .co  m
    // operation
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(cssDocumentLocation);
    method.addRequestHeader("Accept", "text/css");
    int status = client.executeMethod(method);
    // verification
    assertThat(status).isEqualTo(HttpStatus.SC_OK);
    // Read the response body.
    String responseBody = new String(method.getResponseBody());
    assertThat(responseBody).doesNotContain(scriptContent);
}

From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java

@Test
public void shouldForwardRequestOnProxiedServerWithoutScriptInjection() throws Exception {
    // pre-condition
    createHttpPreviewServer();//from w w  w. ja va 2s  .  co  m
    httpPreviewServer.start(ILaunchManager.RUN_MODE, new NullProgressMonitor());
    createAndLaunchLiveReloadServer(false);
    assertThat(liveReloadServerBehaviour.getProxyServers().keySet()).contains(httpPreviewServer);
    // operation
    int proxyPort = liveReloadServerBehaviour.getProxyServers().get(httpPreviewServer).getConnectors()[0]
            .getPort();
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(
            "http://localhost:" + proxyPort + "/" + projectName + "/WebContent/index.html");
    method.addRequestHeader("Accept", "text/html");
    int status = client.executeMethod(method);
    // verification
    assertThat(status).isEqualTo(HttpStatus.SC_OK);
    // Read the response body.
    String responseBody = new String(method.getResponseBody());
    // verification
    assertThat(responseBody).contains("Hello, World!");
    assertThat(responseBody).doesNotContain("livereload.js");
}

From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java

@Test
public void shouldForwardRequestOnProxiedServerWithScriptInjection() throws Exception {
    // pre-condition
    createHttpPreviewServer();//  w w  w. j  a  va 2 s  . c  o m
    httpPreviewServer.start(ILaunchManager.RUN_MODE, new NullProgressMonitor());
    createAndLaunchLiveReloadServer(true);
    assertThat(liveReloadServerBehaviour.getProxyServers().keySet()).contains(httpPreviewServer);
    // operation
    int proxyPort = liveReloadServerBehaviour.getProxyServers().get(httpPreviewServer).getConnectors()[0]
            .getPort();
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(
            "http://localhost:" + proxyPort + "/" + projectName + "/WebContent/index.html");
    method.addRequestHeader("Accept", "text/html");
    int status = client.executeMethod(method);
    // verification
    assertThat(status).isEqualTo(HttpStatus.SC_OK);
    // Read the response body.
    String responseBody = new String(method.getResponseBody());
    // verification
    assertThat(responseBody).contains("Hello, World!");
    assertThat(responseBody).contains("livereload.js")
            .contains(Integer.toString(liveReloadServerBehaviour.getLiveReloadServer().getPort()));
}

From source file:org.jbpm.process.workitem.rest.RESTWorkItemHandler.java

public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    // extract required parameters
    String urlStr = (String) workItem.getParameter("Url");
    String method = (String) workItem.getParameter("Method");
    if (urlStr == null) {
        throw new IllegalArgumentException("Url is a required parameter");
    }//from ww w.ja v  a  2s. c o m
    if (method == null || method.trim().length() == 0) {
        method = "GET";
    }
    Map<String, Object> params = workItem.getParameters();

    // optional timeout config parameters, defaulted to 60 seconds
    Integer connectTimeout = (Integer) params.get("ConnectTimeout");
    if (connectTimeout == null)
        connectTimeout = 60000;
    Integer readTimeout = (Integer) params.get("ReadTimeout");
    if (readTimeout == null)
        readTimeout = 60000;

    HttpClient httpclient = new HttpClient();
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectTimeout);
    httpclient.getHttpConnectionManager().getParams().setSoTimeout(readTimeout);

    HttpMethod theMethod = null;
    if ("GET".equals(method)) {
        theMethod = new GetMethod(urlStr);
    } else if ("POST".equals(method)) {
        theMethod = new PostMethod(urlStr);
        setBody(theMethod, params);
    } else if ("PUT".equals(method)) {
        theMethod = new PutMethod(urlStr);
        setBody(theMethod, params);
    } else if ("DELETE".equals(method)) {
        theMethod = new DeleteMethod(urlStr);
    } else {
        throw new IllegalArgumentException("Method " + method + " is not supported");
    }
    doAuthorization(httpclient, theMethod, params);
    try {
        int responseCode = httpclient.executeMethod(theMethod);
        Map<String, Object> results = new HashMap<String, Object>();
        if (responseCode >= 200 && responseCode < 300) {
            theMethod.getResponseBody();
            postProcessResult(theMethod.getResponseBodyAsString(), results);
            results.put("StatusMsg",
                    "request to endpoint " + urlStr + " successfully completed " + theMethod.getStatusText());
        } else {
            logger.warn("Unsuccessful response from REST server (status {}, endpoint {}, response {}",
                    responseCode, urlStr, theMethod.getResponseBodyAsString());
            results.put("StatusMsg",
                    "endpoint " + urlStr + " could not be reached: " + theMethod.getResponseBodyAsString());
        }
        results.put("Status", responseCode);

        // notify manager that work item has been completed
        manager.completeWorkItem(workItem.getId(), results);
    } catch (Exception e) {
        handleException(e);
    } finally {
        theMethod.releaseConnection();
    }
}

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  a v  a 2  s.co 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;
}

From source file:org.josso.tc50.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
 * @param valveContext The valve _context used to invoke the next valve
 *  in the current processing pipeline//w w  w  .ja  va  2 s  .  c o m
 * @exception IOException if an input/output error occurs
 * @exception javax.servlet.ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response, ValveContext valveContext)
        throws IOException, javax.servlet.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;
    }

    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;
}

From source file:org.josso.tc55.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
 *  in the current processing pipeline/* w w w. j a v  a  2s. c  o  m*/
 * @exception IOException if an input/output error occurs
 * @exception javax.servlet.ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response) throws IOException, javax.servlet.ServletException {

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("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");
        getNext().invoke(request, response);
        return;
    }

    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 (container.getLogger().isDebugEnabled())
        container.getLogger().debug("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 (container.getLogger().isDebugEnabled())
                        container.getLogger().debug("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 (container.getLogger().isDebugEnabled())
        container.getLogger().debug("ReverseProxyValve finished.");

    return;
}

From source file:org.josso.tc60.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
 *  in the current processing pipeline//w  w  w  .ja v a  2  s.  c  om
 * @exception IOException if an input/output error occurs
 * @exception javax.servlet.ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response) throws IOException, javax.servlet.ServletException {

    if (container.getLogger().isDebugEnabled())
        container.getLogger().debug("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");
        getNext().invoke(request, response);
        return;
    }

    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 (container.getLogger().isDebugEnabled())
        container.getLogger().debug("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.
    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 (container.getLogger().isDebugEnabled())
                        container.getLogger().debug("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 (container.getLogger().isDebugEnabled())
        container.getLogger().debug("ReverseProxyValve finished.");

    return;
}

From source file:org.ktunaxa.referral.server.mvc.ProxyController.java

@SuppressWarnings("unchecked")
@RequestMapping(value = "/proxy")
public final void proxyAjaxCall(@RequestParam(required = true, value = "url") String url,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    // URL needs to be url decoded
    url = URLDecoder.decode(url, "utf-8");

    HttpClient client = new HttpClient();
    try {// www  . ja  va  2 s. c om

        HttpMethod method = null;

        // Split this according to the type of request
        if ("GET".equals(request.getMethod())) {

            method = new GetMethod(url);
            NameValuePair[] pairs = new NameValuePair[request.getParameterMap().size()];
            int i = 0;
            for (Object name : request.getParameterMap().keySet()) {
                pairs[i++] = new NameValuePair((String) name, request.getParameter((String) name));
            }
            method.setQueryString(pairs);

        } else if ("POST".equals(request.getMethod())) {

            method = new PostMethod(url);

            // Set any eventual parameters that came with our original
            // request (POST params, for instance)
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {

                String paramName = (String) paramNames.nextElement();
                ((PostMethod) method).setParameter(paramName, request.getParameter(paramName));
            }

        } else {

            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

        // Execute the method
        client.executeMethod(method);

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {

            if (header.getName().equalsIgnoreCase("Content-Type")) {

                response.setContentType(header.getValue());
            }
        }

        // Write the body, flush and close
        response.getOutputStream().write(method.getResponseBody());

    } catch (HttpException e) {

        // log.error("Oops, something went wrong in the HTTP proxy", null, e);
        response.getOutputStream().write(e.toString().getBytes("UTF-8"));
        throw e;

    } catch (IOException e) {

        e.printStackTrace();
        response.getOutputStream().write(e.toString().getBytes("UTF-8"));
        throw e;
    }
}