Example usage for javax.servlet.http HttpServletResponse SC_MULTIPLE_CHOICES

List of usage examples for javax.servlet.http HttpServletResponse SC_MULTIPLE_CHOICES

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_MULTIPLE_CHOICES.

Prototype

int SC_MULTIPLE_CHOICES

To view the source code for javax.servlet.http HttpServletResponse SC_MULTIPLE_CHOICES.

Click Source Link

Document

Status code (300) indicating that the requested resource corresponds to any one of a set of representations, each with its own specific location.

Usage

From source file:org.nunux.poc.portal.ProxyServlet.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//w ww  .  j av a 2s.  c om
 * @param httpServletResponse An object by which we can send the proxied
 * response back to the client
 * @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) 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("=");

                if (nameValue[0].equalsIgnoreCase("jsessionid")) {
                    httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(),
                            nameValue[1]);
                    debug("redirecting: store jsessionid: " + nameValue[1]);
                } else {
                    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 if (header.getName().equals("Set-Cookie")) {
            String[] cookieDetails = header.getValue().split(";");
            String[] nameValue = cookieDetails[0].split("=");
            if (nameValue[0].equalsIgnoreCase("jsessionid")) {
                httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(),
                        nameValue[1]);
                debug("redirecting: store jsessionid: " + nameValue[1]);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        } 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:org.testdwr.custom.CustomResponseServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo = request.getPathInfo();
    String homePage = request.getContextPath() + request.getServletPath() + "/";

    // Redirect from root dir without trailing slash to with trailing slash
    if (pathInfo == null) {
        response.sendRedirect(homePage);
        return;/*w w  w. j  av a2s  .c  o  m*/
    }
    // Send home page
    else if (pathInfo.equals("/") || pathInfo.startsWith("/page")) {
        InputStream in = getClass().getResourceAsStream(RESOURCE_HELP);
        if (in == null) {
            log.error("Missing file " + RESOURCE_HELP);
            response.sendError(500, "Missing file " + RESOURCE_HELP);
        } else {
            response.setContentType("text/html");
            ServletOutputStream out = response.getOutputStream();
            CopyUtils.copy(in, out);
        }
    }
    // Send empty page
    else if (pathInfo.startsWith("/empty")) {
        response.setContentType("text/html");
    }
    // Handle redirects
    else if (pathInfo.matches("\\/redirect\\/[1-9][0-9][0-9]\\/.*")) {
        String responseCodeStr = pathInfo.substring(10, 10 + 3);
        int responseCode = Integer.parseInt(responseCodeStr);
        String redirectPath = URLDecoder.decode(pathInfo.substring(13), "utf-8");
        redirectPath = request.getContextPath() + request.getServletPath() + redirectPath;

        log.info("Sending " + responseCode + ":" + redirectPath + "(" + pathInfo + ")");
        switch (responseCode) {
        case HttpServletResponse.SC_MULTIPLE_CHOICES:
        case HttpServletResponse.SC_MOVED_PERMANENTLY:
        case HttpServletResponse.SC_FOUND:
        case HttpServletResponse.SC_SEE_OTHER:
            response.setHeader("Location", "/" + redirectPath);
            response.setStatus(responseCode);
            break;

        case HttpServletResponse.SC_TEMPORARY_REDIRECT:
            response.sendRedirect(redirectPath);
            break;

        default:
            response.sendError(responseCode, "/" + redirectPath);
            break;
        }
    }
    // Send 404
    else {
        response.sendError(404);
    }
}