Search in sources :

Example 1 with HttpServletResponseWrapper

use of javax.servlet.http.HttpServletResponseWrapper in project jetty.project by eclipse.

the class DispatchServlet method doGet.

/* ------------------------------------------------------------ */
@Override
public void doGet(HttpServletRequest sreq, HttpServletResponse sres) throws ServletException, IOException {
    if (sreq.getParameter("wrap") != null) {
        sreq = new HttpServletRequestWrapper(sreq);
        sres = new HttpServletResponseWrapper(sres);
    }
    if (sreq.getParameter("session") != null)
        sreq.getSession(true);
    String prefix = sreq.getContextPath() != null ? sreq.getContextPath() + sreq.getServletPath() : sreq.getServletPath();
    String info;
    if (sreq.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH) != null)
        info = (String) sreq.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
    else
        info = sreq.getPathInfo();
    if (info == null)
        info = "NULL";
    if (info.indexOf(sreq.getServletPath()) > 0) {
        sres.sendError(403, "Nested " + sreq.getServletPath() + " forbidden.");
        return;
    }
    if (info.indexOf(getServletName()) > 0) {
        sres.sendError(403, "Nested " + getServletName() + " forbidden.");
        return;
    }
    if (info.startsWith("/includeW/")) {
        sres.setContentType("text/html");
        info = info.substring(9);
        if (info.indexOf('?') < 0)
            info += "?Dispatch=include";
        else
            info += "&Dispatch=include";
        PrintWriter pout = null;
        pout = sres.getWriter();
        pout.write("<H1>Include (writer): " + info + "</H1><HR>");
        RequestDispatcher dispatch = getServletContext().getRequestDispatcher(info);
        if (dispatch == null) {
            pout = sres.getWriter();
            pout.write("<H1>Null dispatcher</H1>");
        } else
            dispatch.include(sreq, sres);
        pout.write("<HR><H1>-- Included (writer)</H1>");
    } else if (info.startsWith("/includeS/")) {
        sres.setContentType("text/html");
        info = info.substring(9);
        if (info.indexOf('?') < 0)
            info += "?Dispatch=include";
        else
            info += "&Dispatch=include";
        OutputStream out = null;
        out = sres.getOutputStream();
        out.write(("<H1>Include (outputstream): " + info + "</H1><HR>").getBytes());
        RequestDispatcher dispatch = getServletContext().getRequestDispatcher(info);
        if (dispatch == null) {
            out = sres.getOutputStream();
            out.write("<H1>Null dispatcher</H1>".getBytes());
        } else
            dispatch.include(sreq, sres);
        out.write("<HR><H1>-- Included (outputstream)</H1>".getBytes());
    } else if (info.startsWith("/forward/")) {
        info = info.substring(8);
        if (info.indexOf('?') < 0)
            info += "?Dispatch=forward";
        else
            info += "&Dispatch=forward";
        RequestDispatcher dispatch = getServletContext().getRequestDispatcher(info);
        if (dispatch != null) {
            ServletOutputStream out = sres.getOutputStream();
            out.print("Can't see this");
            dispatch.forward(sreq, sres);
            try {
                // should be closed
                out.println("IOException");
                // should not get here
                throw new IllegalStateException();
            } catch (IOException e) {
            // getServletContext().log("ignore",e);
            }
        } else {
            sres.setContentType("text/html");
            PrintWriter pout = sres.getWriter();
            pout.write("<H1>No dispatcher for: " + info + "</H1><HR>");
            pout.flush();
        }
    } else if (info.startsWith("/forwardC/")) {
        info = info.substring(9);
        if (info.indexOf('?') < 0)
            info += "?Dispatch=forward";
        else
            info += "&Dispatch=forward";
        String cpath = info.substring(0, info.indexOf('/', 1));
        info = info.substring(cpath.length());
        ServletContext context = getServletContext().getContext(cpath);
        RequestDispatcher dispatch = context.getRequestDispatcher(info);
        if (dispatch != null) {
            dispatch.forward(sreq, sres);
        } else {
            sres.setContentType("text/html");
            PrintWriter pout = sres.getWriter();
            pout.write("<H1>No dispatcher for: " + cpath + "/" + info + "</H1><HR>");
            pout.flush();
        }
    } else if (info.startsWith("/includeN/")) {
        sres.setContentType("text/html");
        info = info.substring(10);
        if (info.indexOf("/") >= 0)
            info = info.substring(0, info.indexOf("/"));
        PrintWriter pout;
        if (info.startsWith("/null"))
            info = info.substring(5);
        else {
            pout = sres.getWriter();
            pout.write("<H1>Include named: " + info + "</H1><HR>");
        }
        RequestDispatcher dispatch = getServletContext().getNamedDispatcher(info);
        if (dispatch != null)
            dispatch.include(sreq, sres);
        else {
            pout = sres.getWriter();
            pout.write("<H1>No servlet named: " + info + "</H1>");
        }
        pout = sres.getWriter();
        pout.write("<HR><H1>Included ");
    } else if (info.startsWith("/forwardN/")) {
        info = info.substring(10);
        if (info.indexOf("/") >= 0)
            info = info.substring(0, info.indexOf("/"));
        RequestDispatcher dispatch = getServletContext().getNamedDispatcher(info);
        if (dispatch != null)
            dispatch.forward(sreq, sres);
        else {
            sres.setContentType("text/html");
            PrintWriter pout = sres.getWriter();
            pout.write("<H1>No servlet named: " + info + "</H1>");
            pout.flush();
        }
    } else {
        sres.setContentType("text/html");
        PrintWriter pout = sres.getWriter();
        pout.write("<H1>Dispatch URL must be of the form: </H1>" + "<PRE>" + prefix + "/includeW/path\n" + prefix + "/includeS/path\n" + prefix + "/forward/path\n" + prefix + "/includeN/name\n" + prefix + "/forwardC/_context/path\n</PRE>");
    }
}
Also used : HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) ServletContext(javax.servlet.ServletContext) IOException(java.io.IOException) RequestDispatcher(javax.servlet.RequestDispatcher) PrintWriter(java.io.PrintWriter)

Example 2 with HttpServletResponseWrapper

use of javax.servlet.http.HttpServletResponseWrapper in project jetty.project by eclipse.

the class Dump method doGet.

/* ------------------------------------------------------------ */
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    if (request.getRemoteUser() == null) {
        try {
            request.login("user", "password");
        } catch (ServletException se) {
            getServletContext().log(se.toString());
        }
    }
    // Handle a dump of data
    final String data = request.getParameter("data");
    final String chars = request.getParameter("chars");
    final String block = request.getParameter("block");
    final String dribble = request.getParameter("dribble");
    final boolean flush = request.getParameter("flush") != null ? Boolean.parseBoolean(request.getParameter("flush")) : false;
    if (request.getPathInfo() != null && request.getPathInfo().toLowerCase(Locale.ENGLISH).indexOf("script") != -1) {
        response.sendRedirect(response.encodeRedirectURL(getServletContext().getContextPath() + "/dump/info"));
        return;
    }
    request.setCharacterEncoding("UTF-8");
    if (request.getParameter("busy") != null) {
        long end = System.currentTimeMillis() + Long.parseLong(request.getParameter("busy"));
        while (System.currentTimeMillis() < end) {
        }
    }
    if (request.getParameter("empty") != null) {
        response.setStatus(200);
        response.flushBuffer();
        return;
    }
    if (request.getParameter("sleep") != null) {
        try {
            long s = Long.parseLong(request.getParameter("sleep"));
            if (request.getHeader("Expect") != null && request.getHeader("Expect").indexOf("102") >= 0) {
                Thread.sleep(s / 2);
                response.sendError(102);
                Thread.sleep(s / 2);
            } else
                Thread.sleep(s);
        } catch (InterruptedException e) {
            return;
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
    if (request.getParameter("startAsync") != null && request.getAttribute("ASYNC") != Boolean.TRUE) {
        request.setAttribute("ASYNC", Boolean.TRUE);
        try {
            final AsyncContext async = request.startAsync(request, response);
            async.setTimeout(Long.parseLong(request.getParameter("startAsync")));
            async.addListener(new AsyncListener() {

                @Override
                public void onTimeout(AsyncEvent event) throws IOException {
                    response.addHeader("Dump", "onTimeout");
                    try {
                        if (!dump(response, data, chars, block, dribble, flush)) {
                            response.setContentType("text/plain");
                            response.getOutputStream().println("EXPIRED");
                        }
                        async.complete();
                    } catch (IOException e) {
                        getServletContext().log("", e);
                    }
                }

                @Override
                public void onStartAsync(AsyncEvent event) throws IOException {
                    response.addHeader("Dump", "onStartAsync");
                }

                @Override
                public void onError(AsyncEvent event) throws IOException {
                    response.addHeader("Dump", "onError");
                }

                @Override
                public void onComplete(AsyncEvent event) throws IOException {
                    response.addHeader("Dump", "onComplete");
                }
            });
            if (request.getParameter("dispatch") != null) {
                request.setAttribute("RESUME", Boolean.TRUE);
                final long resume = Long.parseLong(request.getParameter("dispatch"));
                _timer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        async.dispatch();
                    }
                }, resume);
            }
            if (request.getParameter("complete") != null) {
                final long complete = Long.parseLong(request.getParameter("complete"));
                _timer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        try {
                            response.setContentType("text/html");
                            response.getOutputStream().println("<h1>COMPLETED</h1>");
                            async.complete();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, complete);
            }
            return;
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
    request.setAttribute("Dump", this);
    getServletContext().setAttribute("Dump", this);
    // getServletContext().log("dump "+request.getRequestURI());
    // Force a content length response
    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }
    // Handle a dump of data
    if (dump(response, data, chars, block, dribble, flush))
        return;
    // handle an exception
    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {
            throw (Throwable) Thread.currentThread().getContextClassLoader().loadClass(info.substring(1)).newInstance();
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }
    // test a reset
    String reset = request.getParameter("reset");
    if (reset != null && reset.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.setHeader("SHOULD_NOT", "BE SEEN");
        response.reset();
    }
    // handle an redirect
    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(response.encodeRedirectURL(redirect));
        try {
            response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        } catch (IOException e) {
        // ignored as stream is closed.
        }
        return;
    }
    // handle an error
    String error = request.getParameter("error");
    if (error != null && error.length() > 0 && request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE) == null) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        try {
            response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        } catch (IllegalStateException e) {
            try {
                response.getWriter().println("NOR THIS!!");
            } catch (IOException e2) {
            }
        } catch (IOException e) {
        }
        return;
    }
    // Handle a extra headers
    String headers = request.getParameter("headers");
    if (headers != null && headers.length() > 0) {
        long h = Long.parseLong(headers);
        for (int i = 0; i < h; i++) response.addHeader("Header" + i, "Value" + i);
    }
    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));
    String charset = request.getParameter("charset");
    if (charset == null)
        charset = "UTF-8";
    response.setCharacterEncoding(charset);
    response.setContentType("text/html");
    if (info != null && info.indexOf("Locale/") >= 0) {
        try {
            String locale_name = info.substring(info.indexOf("Locale/") + 7);
            Field f = java.util.Locale.class.getField(locale_name);
            response.setLocale((Locale) f.get(null));
        } catch (Exception e) {
            e.printStackTrace();
            response.setLocale(Locale.getDefault());
        }
    }
    String cn = request.getParameter("cookie");
    String cv = request.getParameter("cookiev");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        if (request.getParameter("version") != null)
            cookie.setVersion(Integer.parseInt(request.getParameter("version")));
        cookie.setComment("Cookie from dump servlet");
        response.addCookie(cookie);
    }
    String pi = request.getPathInfo();
    if (pi != null && pi.startsWith("/ex")) {
        OutputStream out = response.getOutputStream();
        out.write("</H1>This text should be reset</H1>".getBytes());
        if ("/ex0".equals(pi))
            throw new ServletException("test ex0", new Throwable());
        else if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        else if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        else if (pi.startsWith("/ex3/"))
            throw new UnavailableException("test ex3", Integer.parseInt(pi.substring(5)));
        throw new RuntimeException("test");
    }
    if ("true".equals(request.getParameter("close")))
        response.setHeader("Connection", "close");
    String buffered = request.getParameter("buffered");
    PrintWriter pout = null;
    try {
        pout = response.getWriter();
    } catch (IllegalStateException e) {
        pout = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), charset));
    }
    if (buffered != null)
        pout = new PrintWriter(new BufferedWriter(pout, Integer.parseInt(buffered)));
    try {
        pout.write("<html>\n<body>\n");
        pout.write("<h1>Dump Servlet</h1>\n");
        pout.write("<table width=\"95%\">");
        pout.write("<tr>\n");
        pout.write("<th align=\"right\">getContentLength:&nbsp;</th>");
        pout.write("<td>" + Integer.toString(request.getContentLength()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getContentType:&nbsp;</th>");
        pout.write("<td>" + notag(request.getContentType()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getContextPath:&nbsp;</th>");
        pout.write("<td>" + request.getContextPath() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getDispatcherType:&nbsp;</th>");
        pout.write("<td>" + request.getDispatcherType() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getLocale:&nbsp;</th>");
        pout.write("<td>" + request.getLocale() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getLocalName:&nbsp;</th>");
        pout.write("<td>" + request.getLocalName() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getLocalAddr:&nbsp;</th>");
        pout.write("<td>" + request.getLocalAddr() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getLocalPort:&nbsp;</th>");
        pout.write("<td>" + Integer.toString(request.getLocalPort()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getMethod:&nbsp;</th>");
        pout.write("<td>" + notag(request.getMethod()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getPathInfo:&nbsp;</th>");
        pout.write("<td>" + notag(request.getPathInfo()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getPathTranslated:&nbsp;</th>");
        pout.write("<td>" + notag(request.getPathTranslated()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getProtocol:&nbsp;</th>");
        pout.write("<td>" + request.getProtocol() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getQueryString:&nbsp;</th>");
        pout.write("<td>" + notag(request.getQueryString()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getRemoteAddr:&nbsp;</th>");
        pout.write("<td>" + request.getRemoteAddr() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getRemoteHost:&nbsp;</th>");
        pout.write("<td>" + request.getRemoteHost() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getRemotePort:&nbsp;</th>");
        pout.write("<td>" + request.getRemotePort() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getRemoteUser:&nbsp;</th>");
        pout.write("<td>" + request.getRemoteUser() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getRequestedSessionId:&nbsp;</th>");
        pout.write("<td>" + request.getRequestedSessionId() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getRequestURI:&nbsp;</th>");
        pout.write("<td>" + notag(request.getRequestURI()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getRequestURL:&nbsp;</th>");
        pout.write("<td>" + notag(request.getRequestURL().toString()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getScheme:&nbsp;</th>");
        pout.write("<td>" + request.getScheme() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getServerName:&nbsp;</th>");
        pout.write("<td>" + notag(request.getServerName()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getServletPath:&nbsp;</th>");
        pout.write("<td>" + notag(request.getServletPath()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getServerPort:&nbsp;</th>");
        pout.write("<td>" + Integer.toString(request.getServerPort()) + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">getUserPrincipal:&nbsp;</th>");
        pout.write("<td>" + request.getUserPrincipal() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">isAsyncStarted():&nbsp;</th>");
        pout.write("<td>" + request.isAsyncStarted() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">isAsyncSupported():&nbsp;</th>");
        pout.write("<td>" + request.isAsyncSupported() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">isSecure():&nbsp;</th>");
        pout.write("<td>" + request.isSecure() + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">isUserInRole(admin):&nbsp;</th>");
        pout.write("<td>" + request.isUserInRole("admin") + "</td>");
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"right\">encodeRedirectURL(/foo?bar):&nbsp;</th>");
        pout.write("<td>" + response.encodeRedirectURL("/foo?bar") + "</td>");
        Enumeration<Locale> locales = request.getLocales();
        while (locales.hasMoreElements()) {
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">getLocales:&nbsp;</th>");
            pout.write("<td>" + locales.nextElement() + "</td>");
        }
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Other HTTP Headers:</big></th>");
        Enumeration<String> h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            Enumeration<String> h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                pout.write("</tr><tr>\n");
                pout.write("<th align=\"right\">" + notag(name) + ":&nbsp;</th>");
                pout.write("<td>" + notag(hv) + "</td>");
            }
        }
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Request Parameters:</big></th>");
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">" + notag(name) + ":&nbsp;</th>");
            pout.write("<td>" + notag(request.getParameter(name)) + "</td>");
            String[] values = request.getParameterValues(name);
            if (values == null) {
                pout.write("</tr><tr>\n");
                pout.write("<th align=\"right\">" + notag(name) + " Values:&nbsp;</th>");
                pout.write("<td>" + "NULL!" + "</td>");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    pout.write("</tr><tr>\n");
                    pout.write("<th align=\"right\">" + notag(name) + "[" + i + "]:&nbsp;</th>");
                    pout.write("<td>" + notag(values[i]) + "</td>");
                }
            }
        }
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Cookies:</big></th>");
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">" + notag(cookie.getName()) + ":&nbsp;</th>");
            pout.write("<td>" + notag(cookie.getValue()) + "</td>");
        }
        String content_type = request.getContentType();
        if (content_type != null && !content_type.startsWith("application/x-www-form-urlencoded") && !content_type.startsWith("multipart/form-data")) {
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"left\" valign=\"top\" colspan=\"2\"><big><br/>Content:</big></th>");
            pout.write("</tr><tr>\n");
            pout.write("<td><pre>");
            char[] content = new char[4096];
            int len;
            try {
                Reader in = request.getReader();
                while ((len = in.read(content)) >= 0) pout.write(notag(new String(content, 0, len)));
            } catch (IOException e) {
                pout.write(e.toString());
            }
            pout.write("</pre></td>");
        }
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Request Attributes:</big></th>");
        Enumeration<String> a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\" valign=\"top\">" + name.replace(".", " .") + ":&nbsp;</th>");
            Object value = request.getAttribute(name);
            if (value instanceof File) {
                File file = (File) value;
                pout.write("<td>" + "<pre>" + file.getName() + " (" + file.length() + " " + new Date(file.lastModified()) + ")</pre>" + "</td>");
            } else
                pout.write("<td>" + "<pre>" + toString(request.getAttribute(name)) + "</pre>" + "</td>");
        }
        request.setAttribute("org.eclipse.jetty.servlet.MultiPartFilter.files", null);
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Servlet InitParameters:</big></th>");
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">" + name + ":&nbsp;</th>");
            pout.write("<td>" + toString(getInitParameter(name)) + "</td>");
        }
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Context InitParameters:</big></th>");
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\" valign=\"top\">" + name.replace(".", " .") + ":&nbsp;</th>");
            pout.write("<td>" + toString(getServletContext().getInitParameter(name)) + "</td>");
        }
        pout.write("</tr><tr>\n");
        pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Context Attributes:</big></th>");
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\" valign=\"top\">" + name.replace(".", " .") + ":&nbsp;</th>");
            pout.write("<td>" + "<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>" + "</td>");
        }
        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"left\" colspan=\"2\"><big><br/>Get Resource: \"" + res + "\"</big></th>");
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">getServletContext().getResource(...):&nbsp;</th>");
            try {
                pout.write("<td>" + getServletContext().getResource(res) + "</td>");
            } catch (Exception e) {
                pout.write("<td>" + "" + e + "</td>");
            }
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">getServletContext().getResourcePaths(...):&nbsp;</th>");
            try {
                pout.write("<td>" + getServletContext().getResourcePaths(res) + "</td>");
            } catch (Exception e) {
                pout.write("<td>" + "" + e + "</td>");
            }
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">getServletContext().getRealPath(...):&nbsp;</th>");
            try {
                pout.write("<td>" + getServletContext().getRealPath(res) + "</td>");
            } catch (Exception e) {
                pout.write("<td>" + "" + e + "</td>");
            }
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">getServletContext().getContext(...):&nbsp;</th>");
            ServletContext context = getServletContext().getContext(res);
            pout.write("<td>" + context + "</td>");
            if (context != null) {
                pout.write("</tr><tr>\n");
                pout.write("<th align=\"right\">getServletContext().getContext(...).getResource(...):&nbsp;</th>");
                try {
                    pout.write("<td>" + context.getResource(res) + "</td>");
                } catch (Exception e) {
                    pout.write("<td>" + "" + e + "</td>");
                }
                pout.write("</tr><tr>\n");
                pout.write("<th align=\"right\">getServletContext().getContext(...).getResourcePaths(...):&nbsp;</th>");
                try {
                    pout.write("<td>" + context.getResourcePaths(res) + "</td>");
                } catch (Exception e) {
                    pout.write("<td>" + "" + e + "</td>");
                }
                String cp = context.getContextPath();
                if (cp == null || "/".equals(cp))
                    cp = "";
                pout.write("</tr><tr>\n");
                pout.write("<th align=\"right\">getServletContext().getContext(...).getRequestDispatcher(...):&nbsp;</th>");
                pout.write("<td>" + context.getRequestDispatcher(res.substring(cp.length())) + "</td>");
                pout.write("</tr><tr>\n");
                pout.write("<th align=\"right\">getServletContext().getContext(...).getRealPath(...):&nbsp;</th>");
                pout.write("<td>" + context.getRealPath(res.substring(cp.length())) + "</td>");
            }
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">this.getClass().getResource(...):&nbsp;</th>");
            pout.write("<td>" + this.getClass().getResource(res) + "</td>");
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">this.getClass().getClassLoader().getResource(...):&nbsp;</th>");
            pout.write("<td>" + this.getClass().getClassLoader().getResource(res) + "</td>");
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">Thread.currentThread().getContextClassLoader().getResource(...):&nbsp;</th>");
            pout.write("<td>" + Thread.currentThread().getContextClassLoader().getResource(res) + "</td>");
            pout.write("</tr><tr>\n");
            pout.write("<th align=\"right\">Thread.currentThread().getContextClassLoader().getResources(...):&nbsp;</th>");
            Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(res);
            if (urls == null)
                pout.write("<td>null</td>");
            else
                pout.write("<td>" + Collections.list(urls) + "</td>");
        }
        pout.write("</tr></table>\n");
        /* ------------------------------------------------------------ */
        pout.write("<h2>Request Wrappers</h2>\n");
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            pout.write((w++) + ": " + rw.getClass().getName() + "<br/>");
            if (rw instanceof HttpServletRequestWrapper)
                rw = ((HttpServletRequestWrapper) rw).getRequest();
            else if (rw instanceof ServletRequestWrapper)
                rw = ((ServletRequestWrapper) rw).getRequest();
            else
                rw = null;
        }
        /* ------------------------------------------------------------ */
        pout.write("<h2>Response Wrappers</h2>\n");
        ServletResponse rsw = response;
        w = 0;
        while (rsw != null) {
            pout.write((w++) + ": " + rsw.getClass().getName() + "<br/>");
            if (rsw instanceof HttpServletResponseWrapper)
                rsw = ((HttpServletResponseWrapper) rsw).getResponse();
            else if (rsw instanceof ServletResponseWrapper)
                rsw = ((ServletResponseWrapper) rsw).getResponse();
            else
                rsw = null;
        }
        pout.write("<br/>");
        pout.write("<h2>International Characters (UTF-8)</h2>");
        pout.write("LATIN LETTER SMALL CAPITAL AE<br/>\n");
        pout.write("Directly uni encoded(\\u1d01): ᴁ<br/>");
        pout.write("HTML reference (&amp;AElig;): &AElig;<br/>");
        pout.write("Decimal (&amp;#7425;): &#7425;<br/>");
        pout.write("Javascript unicode (\\u1d01) : <script language='javascript'>document.write(\"ᴁ\");</script><br/>");
        pout.write("<br/>");
        pout.write("<h2>Form to generate GET content</h2>");
        pout.write("<form method=\"GET\" action=\"" + response.encodeURL(getURI(request)) + "\">");
        pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"value\"/><br/>\n");
        pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\">");
        pout.write("</form>");
        pout.write("<br/>");
        pout.write("<h2>Form to generate POST content</h2>");
        pout.write("<form method=\"POST\" accept-charset=\"utf-8\" action=\"" + response.encodeURL(getURI(request)) + "\">");
        pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"value\"/><br/>\n");
        pout.write("Select: <select multiple name=\"Select\">\n");
        pout.write("<option>ValueA</option>");
        pout.write("<option>ValueB1,ValueB2</option>");
        pout.write("<option>ValueC</option>");
        pout.write("</select><br/>");
        pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\"><br/>");
        pout.write("</form>");
        pout.write("<br/>");
        pout.write("<h2>Form to generate UPLOAD content</h2>");
        pout.write("<form method=\"POST\" enctype=\"multipart/form-data\" accept-charset=\"utf-8\" action=\"" + response.encodeURL(getURI(request)) + (request.getQueryString() == null ? "" : ("?" + request.getQueryString())) + "\">");
        pout.write("TextField: <input type=\"text\" name=\"TextField\" value=\"comment\"/><br/>\n");
        pout.write("File 1: <input type=\"file\" name=\"file1\" /><br/>\n");
        pout.write("File 2: <input type=\"file\" name=\"file2\" /><br/>\n");
        pout.write("<input type=\"submit\" name=\"Action\" value=\"Submit\"><br/>");
        pout.write("</form>");
        pout.write("<h2>Form to set Cookie</h2>");
        pout.write("<form method=\"POST\" action=\"" + response.encodeURL(getURI(request)) + "\">");
        pout.write("cookie: <input type=\"text\" name=\"cookie\" /><br/>\n");
        pout.write("value: <input type=\"text\" name=\"cookiev\" /><br/>\n");
        pout.write("<input type=\"submit\" name=\"Action\" value=\"setCookie\">");
        pout.write("</form>\n");
        pout.write("<h2>Form to get Resource</h2>");
        pout.write("<form method=\"POST\" action=\"" + response.encodeURL(getURI(request)) + "\">");
        pout.write("resource: <input type=\"text\" name=\"resource\" /><br/>\n");
        pout.write("<input type=\"submit\" name=\"Action\" value=\"getResource\">");
        pout.write("</form>\n");
    } catch (Exception e) {
        getServletContext().log("dump " + e);
    }
    String lines = request.getParameter("lines");
    if (lines != null) {
        char[] line = "<span>A line of characters. Blah blah blah blah.  blooble blooble</span></br>\n".toCharArray();
        for (int l = Integer.parseInt(lines); l-- > 0; ) {
            pout.write("<span>" + l + " </span>");
            pout.write(line);
        }
    }
    pout.write("</body>\n</html>\n");
    pout.close();
    if (pi != null) {
        if ("/ex4".equals(pi))
            throw new ServletException("test ex4", new Throwable());
        if ("/ex5".equals(pi))
            throw new IOException("test ex5");
        if ("/ex6".equals(pi))
            throw new UnavailableException("test ex6");
    }
}
Also used : Locale(java.util.Locale) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) OutputStream(java.io.OutputStream) UnavailableException(javax.servlet.UnavailableException) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) Reader(java.io.Reader) AsyncContext(javax.servlet.AsyncContext) URL(java.net.URL) BufferedWriter(java.io.BufferedWriter) ServletException(javax.servlet.ServletException) Field(java.lang.reflect.Field) TimerTask(java.util.TimerTask) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) ServletContext(javax.servlet.ServletContext) ServletResponseWrapper(javax.servlet.ServletResponseWrapper) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) PrintWriter(java.io.PrintWriter) Cookie(javax.servlet.http.Cookie) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) ServletRequestWrapper(javax.servlet.ServletRequestWrapper) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UnavailableException(javax.servlet.UnavailableException) Date(java.util.Date) AsyncListener(javax.servlet.AsyncListener) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File)

Example 3 with HttpServletResponseWrapper

use of javax.servlet.http.HttpServletResponseWrapper in project lucene-solr by apache.

the class HadoopAuthPlugin method doAuthenticate.

@Override
public boolean doAuthenticate(ServletRequest request, ServletResponse response, FilterChain filterChain) throws Exception {
    final HttpServletResponse frsp = (HttpServletResponse) response;
    if (TRACE_HTTP) {
        HttpServletRequest req = (HttpServletRequest) request;
        log.info("----------HTTP Request---------");
        log.info("{} : {}", req.getMethod(), req.getRequestURI());
        log.info("Query : {}", req.getQueryString());
        log.info("Headers :");
        Enumeration<String> headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String name = headers.nextElement();
            Enumeration<String> hvals = req.getHeaders(name);
            while (hvals.hasMoreElements()) {
                log.info("{} : {}", name, hvals.nextElement());
            }
        }
        log.info("-------------------------------");
    }
    // Workaround until HADOOP-13346 is fixed.
    HttpServletResponse rspCloseShield = new HttpServletResponseWrapper(frsp) {

        @SuppressForbidden(reason = "Hadoop DelegationTokenAuthenticationFilter uses response writer, this" + "is providing a CloseShield on top of that")
        @Override
        public PrintWriter getWriter() throws IOException {
            final PrintWriter pw = new PrintWriterWrapper(frsp.getWriter()) {

                @Override
                public void close() {
                }

                ;
            };
            return pw;
        }
    };
    authFilter.doFilter(request, rspCloseShield, filterChain);
    if (TRACE_HTTP) {
        log.info("----------HTTP Response---------");
        log.info("Status : {}", frsp.getStatus());
        log.info("Headers :");
        for (String name : frsp.getHeaderNames()) {
            for (String value : frsp.getHeaders(name)) {
                log.info("{} : {}", name, value);
            }
        }
        log.info("-------------------------------");
    }
    if (authFilter instanceof HadoopAuthFilter) {
        // delegation token mgmt.
        String requestContinuesAttr = (String) request.getAttribute(REQUEST_CONTINUES_ATTR);
        if (requestContinuesAttr == null) {
            log.warn("Could not find " + REQUEST_CONTINUES_ATTR);
            return false;
        } else {
            return Boolean.parseBoolean(requestContinuesAttr);
        }
    }
    return true;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) PrintWriter(java.io.PrintWriter)

Example 4 with HttpServletResponseWrapper

use of javax.servlet.http.HttpServletResponseWrapper in project spring-boot by spring-projects.

the class ErrorPageFilterTests method responseUncommittedWithoutErrorPage.

@Test
public void responseUncommittedWithoutErrorPage() throws Exception {
    this.chain = new MockFilterChain() {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
            ((HttpServletResponse) response).sendError(400, "BAD");
            super.doFilter(request, response);
        }
    };
    this.filter.doFilter(this.request, this.response, this.chain);
    assertThat(this.chain.getRequest()).isEqualTo(this.request);
    assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getResponse()).isEqualTo(this.response);
    assertThat(((HttpServletResponseWrapper) this.chain.getResponse()).getStatus()).isEqualTo(400);
    assertThat(this.response.getForwardedUrl()).isNull();
    assertThat(this.response.isCommitted()).isTrue();
}
Also used : ServletException(javax.servlet.ServletException) NestedServletException(org.springframework.web.util.NestedServletException) ServletRequest(javax.servlet.ServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) IOException(java.io.IOException) MockFilterChain(org.springframework.mock.web.MockFilterChain) Test(org.junit.Test)

Example 5 with HttpServletResponseWrapper

use of javax.servlet.http.HttpServletResponseWrapper in project groovity by disney.

the class GroovityServlet method service.

/**
 * Primary request entry method for this servlet
 *
 * see {@link HttpServlet#service(HttpServletRequest, HttpServletResponse)}
 */
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    GroovityError error = null;
    try {
        Processor processor = groovityScriptViewFactory.createProcessor(req);
        if (processor != null) {
            if (req.getMethod().equals("HEAD")) {
                // prevent any body from being written, but we'll capture
                // the length
                final AtomicLong length = new AtomicLong(0);
                final AtomicBoolean scriptSetLength = new AtomicBoolean(false);
                final AtomicReference<PrintWriter> respWriter = new AtomicReference<PrintWriter>(null);
                final ServletOutputStream nullStream = new ServletOutputStream() {

                    @Override
                    public void write(int b) throws IOException {
                        length.incrementAndGet();
                    }

                    @Override
                    public void write(byte[] buf, int offset, int len) throws IOException {
                        length.addAndGet(len);
                    }

                    public void setWriteListener(WriteListener arg0) {
                    }

                    public boolean isReady() {
                        return true;
                    }
                };
                processor.process(req, new HttpServletResponseWrapper(res) {

                    PrintWriter writer;

                    @Override
                    public ServletOutputStream getOutputStream() throws IOException {
                        return nullStream;
                    }

                    @Override
                    public PrintWriter getWriter() throws UnsupportedEncodingException {
                        if (writer == null) {
                            writer = new PrintWriter(new OutputStreamWriter(nullStream, getCharacterEncoding()));
                            respWriter.set(writer);
                        }
                        return writer;
                    }

                    @Override
                    public void setContentLength(int len) {
                        res.setContentLength(len);
                        scriptSetLength.set(true);
                    }
                });
                if (!scriptSetLength.get()) {
                    if (respWriter.get() != null) {
                        respWriter.get().flush();
                    }
                    res.setContentLength((int) length.get());
                }
            } else {
                processor.process(req, res);
            }
        } else {
            error = new GroovityError();
            Object acceptMethods = req.getAttribute(REQUEST_ATTRIBUTE_ALLOW_METHODS);
            if (acceptMethods != null && acceptMethods instanceof Collection) {
                @SuppressWarnings("unchecked") Collection<String> am = (Collection<String>) acceptMethods;
                String sep = "";
                StringBuilder sb = new StringBuilder();
                for (Object m : am) {
                    String method = m.toString();
                    sb.append(sep).append(method);
                    sep = ", ";
                }
                res.setHeader("Allow", sb.toString());
                error.setStatus(405);
                error.setMessage("Allowed methods for " + req.getRequestURI() + " are " + sb.toString());
            } else {
                error.setStatus(404);
            }
        }
    } catch (Throwable e) {
        error = new GroovityError();
        error.setCause(e);
        error.setStatus(500);
    }
    if (error != null) {
        error.setReason(EnglishReasonPhraseCatalog.INSTANCE.getReason(error.getStatus(), res.getLocale()));
        String uri = req.getRequestURI();
        if (req.getQueryString() != null) {
            uri = uri.concat("?").concat(req.getQueryString());
        }
        error.setUri(uri);
        req.setAttribute(GroovityScriptView.GROOVITY_ERROR, error);
        boolean handled = false;
        GroovityErrorHandlerChain handlers = groovityScriptViewFactory.getErrorHandlers();
        if (handlers != null) {
            handled = handlers.handleError(req, res, error);
        }
        if (!handled) {
            Throwable cause = error.getCause();
            if (cause != null) {
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                }
                throw new ServletException(cause);
            } else {
                res.sendError(error.getStatus(), error.getMessage());
            }
        }
    }
}
Also used : Processor(com.disney.groovity.servlet.GroovityScriptView.Processor) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) GroovityError(com.disney.groovity.servlet.error.GroovityError) ServletException(javax.servlet.ServletException) WriteListener(javax.servlet.WriteListener) PrintWriter(java.io.PrintWriter) GroovityErrorHandlerChain(com.disney.groovity.servlet.error.GroovityErrorHandlerChain) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) Collection(java.util.Collection) OutputStreamWriter(java.io.OutputStreamWriter)

Aggregations

HttpServletResponseWrapper (javax.servlet.http.HttpServletResponseWrapper)40 HttpServletResponse (javax.servlet.http.HttpServletResponse)28 HttpServletRequest (javax.servlet.http.HttpServletRequest)16 IOException (java.io.IOException)15 ServletException (javax.servlet.ServletException)13 PrintWriter (java.io.PrintWriter)12 ServletOutputStream (javax.servlet.ServletOutputStream)9 ServletResponse (javax.servlet.ServletResponse)9 ServletRequest (javax.servlet.ServletRequest)7 Test (org.junit.Test)7 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)6 OutputStreamWriter (java.io.OutputStreamWriter)5 Provider (com.google.inject.Provider)4 ServletTestUtils.newFakeHttpServletRequest (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest)4 ServletTestUtils.newFakeHttpServletResponse (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse)4 Filter (javax.servlet.Filter)4 FilterChain (javax.servlet.FilterChain)4 FilterConfig (javax.servlet.FilterConfig)4 File (java.io.File)3 Injector (com.google.inject.Injector)2