Example usage for javax.servlet ServletRequest getClass

List of usage examples for javax.servlet ServletRequest getClass

Introduction

In this page you can find the example usage for javax.servlet ServletRequest getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:info.magnolia.cms.util.ServletUtil.java

/**
 * Finds a request wrapper object inside the chain of request wrappers.
 *//*from   w w w.jav a 2 s .co  m*/
public static <T extends ServletRequest> T getWrappedRequest(ServletRequest request, Class<T> clazz) {
    while (request != null) {
        if (clazz.isAssignableFrom(request.getClass())) {
            return (T) request;
        }
        request = (request instanceof ServletRequestWrapper) ? ((ServletRequestWrapper) request).getRequest()
                : null;
    }
    return null;
}

From source file:info.magnolia.module.servletsanity.support.ServletAssert.java

private static void appendRequestChain(HttpServletRequest request) throws IOException {
    append("Request Chain:");
    ServletRequest r = request;
    do {/*from  w w w  .j  a v a2  s.  c o  m*/
        append("&nbsp;&nbsp;&nbsp;&nbsp;" + r.getClass().getName() + " @ " + System.identityHashCode(r) + " - "
                + r.toString());
        r = r instanceof HttpServletRequestWrapper ? ((HttpServletRequestWrapper) r).getRequest() : null;
    } while (r != null);
    append("");
}

From source file:edu.cornell.mannlib.vitro.webapp.beans.SelfEditingConfiguration.java

/**
 * Get the bean from the context. If there no bean, create one on the fly
 * and store it in the context.//from  www .ja  va  2  s .  com
 * 
 * Never returns null.
 */
public static SelfEditingConfiguration getBean(ServletRequest request) {
    if (request == null) {
        log.error("Request is null");
        return new SelfEditingConfiguration(null);
    }

    if (!(request instanceof HttpServletRequest)) {
        log.error("Not an HttpServletRequest: " + request.getClass());
        return new SelfEditingConfiguration(null);
    }
    HttpServletRequest hreq = (HttpServletRequest) request;

    return getBean(hreq.getSession().getServletContext());
}

From source file:fr.mby.saml2.sp.impl.web.Saml20ProcessingFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    ServletRequest chainingRequest = request;

    if (HttpServletRequest.class.isAssignableFrom(request.getClass())) {
        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (SamlHelper.isSamlResponse(httpRequest) || SamlHelper.isSamlRequest(httpRequest)) {
            // If it's a SAML 2.0 Response
            Saml20ProcessingFilter.LOGGER.debug("Start processing SAML 2.0 incoming request ...");
            try {

                // Process SAML response
                final IIncomingSaml samlIncomingMsg = this.processSaml2Request(httpRequest);

                if (samlIncomingMsg != null) {
                    final IQuery samlQuery = samlIncomingMsg.getSamlQuery();
                    Assert.notNull(samlQuery, "No SAML query found in IncomingSaml message !");

                    if (QueryAuthnResponse.class.isAssignableFrom(samlQuery.getClass())) {
                        // The incoming message is a SAML Authn Response
                        final QueryAuthnResponse authnResp = (QueryAuthnResponse) samlQuery;
                        final QueryAuthnRequest authnReq = authnResp.getOriginalRequest();
                        Assert.notNull(authnReq,
                                "No initial Authn Req request corresponding to SAML response found !");

                        // Retrieve initial params
                        final Map<String, String[]> initialParams = authnReq.getParametersMap();
                        Assert.notNull(initialParams, "No initial params bound to the initial request !");

                        // Replace the request with the SAML 2.0 Response one.
                        chainingRequest = new Saml20RequestWrapper(httpRequest, initialParams);
                    }//www .j  a  v a2s .  c  o m

                }

                // Forward
                final RequestDispatcher requestDispatcher = chainingRequest.getRequestDispatcher("/login");
                requestDispatcher.forward(chainingRequest, response);
                return;
            } catch (final Throwable e) {
                Saml20ProcessingFilter.LOGGER.error("Error while processing SAML 2.0 incoming request !", e);
            }
        }
    }

    chain.doFilter(chainingRequest, response);
}

From source file:edu.utah.further.i2b2.hook.further.FurtherInterceptionFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */// ww w.j a v  a  2s.c o m
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain)
        throws IOException, ServletException {
    // Cast to friendler versions
    if (!HttpServletRequest.class.isAssignableFrom(req.getClass())) {
        throw new ServletException("ServletRequest must be an instance of HttpServletRequest");
    }
    if (!HttpServletResponse.class.isAssignableFrom(resp.getClass())) {
        throw new ServletException("ServletResponse must be an instance of HttpServletResponse");
    }
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) resp;

    // Decorate the i2b2 processing chain. Decorate the HTTP request so that input
    // stream can be read twice - once by this filter's methods, and one by the
    // i2b2 processing chain call chain.doFilter().
    final HttpServletRequest bufferedRequest = new BufferedRequestWrapper(request);
    final CapturedResponseWrapper capturedResponse = new CapturedResponseWrapper(response);
    beforeRequest(bufferedRequest);
    chain.doFilter(bufferedRequest, capturedResponse);
    afterRequest(bufferedRequest, response, capturedResponse);
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute("Dump", this);
    request.setCharacterEncoding("ISO_8859_1");
    getServletContext().setAttribute("Dump", this);

    String info = request.getPathInfo();
    if (info != null && info.endsWith("Exception")) {
        try {/*from w  w w. ja va2s .  com*/
            throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance());
        } catch (Throwable th) {
            throw new ServletException(th);
        }
    }

    String redirect = request.getParameter("redirect");
    if (redirect != null && redirect.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendRedirect(redirect);
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String error = request.getParameter("error");
    if (error != null && error.length() > 0) {
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        response.sendError(Integer.parseInt(error));
        response.getOutputStream().println("THIS SHOULD NOT BE SEEN!");
        return;
    }

    String length = request.getParameter("length");
    if (length != null && length.length() > 0) {
        response.setContentLength(Integer.parseInt(length));
    }

    String buffer = request.getParameter("buffer");
    if (buffer != null && buffer.length() > 0)
        response.setBufferSize(Integer.parseInt(buffer));

    request.setCharacterEncoding("UTF-8");
    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) {
            LogSupport.ignore(log, e);
            response.setLocale(Locale.getDefault());
        }
    }

    String cn = request.getParameter("cookie");
    String cv = request.getParameter("value");
    String v = request.getParameter("version");
    if (cn != null && cv != null) {
        Cookie cookie = new Cookie(cn, cv);
        cookie.setComment("Cookie from dump servlet");
        if (v != null) {
            cookie.setMaxAge(300);
            cookie.setPath("/");
            cookie.setVersion(Integer.parseInt(v));
        }
        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());
        if ("/ex1".equals(pi))
            throw new IOException("test ex1");
        if ("/ex2".equals(pi))
            throw new UnavailableException("test ex2");
        if ("/ex3".equals(pi))
            throw new HttpException(501);
    }

    PrintWriter pout = response.getWriter();
    Page page = null;

    try {
        page = new Page();
        page.title("Dump Servlet");

        page.add(new Heading(1, "Dump Servlet"));
        Table table = new Table(0).cellPadding(0).cellSpacing(0);
        page.add(table);
        table.newRow();
        table.addHeading("getMethod:&nbsp;").cell().right();
        table.addCell("" + request.getMethod());
        table.newRow();
        table.addHeading("getContentLength:&nbsp;").cell().right();
        table.addCell(Integer.toString(request.getContentLength()));
        table.newRow();
        table.addHeading("getContentType:&nbsp;").cell().right();
        table.addCell("" + request.getContentType());
        table.newRow();
        table.addHeading("getCharacterEncoding:&nbsp;").cell().right();
        table.addCell("" + request.getCharacterEncoding());
        table.newRow();
        table.addHeading("getRequestURI:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURI());
        table.newRow();
        table.addHeading("getRequestURL:&nbsp;").cell().right();
        table.addCell("" + request.getRequestURL());
        table.newRow();
        table.addHeading("getContextPath:&nbsp;").cell().right();
        table.addCell("" + request.getContextPath());
        table.newRow();
        table.addHeading("getServletPath:&nbsp;").cell().right();
        table.addCell("" + request.getServletPath());
        table.newRow();
        table.addHeading("getPathInfo:&nbsp;").cell().right();
        table.addCell("" + request.getPathInfo());
        table.newRow();
        table.addHeading("getPathTranslated:&nbsp;").cell().right();
        table.addCell("" + request.getPathTranslated());
        table.newRow();
        table.addHeading("getQueryString:&nbsp;").cell().right();
        table.addCell("" + request.getQueryString());

        table.newRow();
        table.addHeading("getProtocol:&nbsp;").cell().right();
        table.addCell("" + request.getProtocol());
        table.newRow();
        table.addHeading("getScheme:&nbsp;").cell().right();
        table.addCell("" + request.getScheme());
        table.newRow();
        table.addHeading("getServerName:&nbsp;").cell().right();
        table.addCell("" + request.getServerName());
        table.newRow();
        table.addHeading("getServerPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getServerPort()));
        table.newRow();
        table.addHeading("getLocalName:&nbsp;").cell().right();
        table.addCell("" + request.getLocalName());
        table.newRow();
        table.addHeading("getLocalAddr:&nbsp;").cell().right();
        table.addCell("" + request.getLocalAddr());
        table.newRow();
        table.addHeading("getLocalPort:&nbsp;").cell().right();
        table.addCell("" + Integer.toString(request.getLocalPort()));
        table.newRow();
        table.addHeading("getRemoteUser:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteUser());
        table.newRow();
        table.addHeading("getRemoteAddr:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteAddr());
        table.newRow();
        table.addHeading("getRemoteHost:&nbsp;").cell().right();
        table.addCell("" + request.getRemoteHost());
        table.newRow();
        table.addHeading("getRemotePort:&nbsp;").cell().right();
        table.addCell("" + request.getRemotePort());
        table.newRow();
        table.addHeading("getRequestedSessionId:&nbsp;").cell().right();
        table.addCell("" + request.getRequestedSessionId());
        table.newRow();
        table.addHeading("isSecure():&nbsp;").cell().right();
        table.addCell("" + request.isSecure());

        table.newRow();
        table.addHeading("isUserInRole(admin):&nbsp;").cell().right();
        table.addCell("" + request.isUserInRole("admin"));

        table.newRow();
        table.addHeading("getLocale:&nbsp;").cell().right();
        table.addCell("" + request.getLocale());

        Enumeration locales = request.getLocales();
        while (locales.hasMoreElements()) {
            table.newRow();
            table.addHeading("getLocales:&nbsp;").cell().right();
            table.addCell(locales.nextElement());
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers")
                .attribute("COLSPAN", "2").left();
        Enumeration h = request.getHeaderNames();
        String name;
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();

            Enumeration h2 = request.getHeaders(name);
            while (h2.hasMoreElements()) {
                String hv = (String) h2.nextElement();
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().right();
                table.addCell(hv);
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters")
                .attribute("COLSPAN", "2").left();
        h = request.getParameterNames();
        while (h.hasMoreElements()) {
            name = (String) h.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().right();
            table.addCell(request.getParameter(name));
            String[] values = request.getParameterValues(name);
            if (values == null) {
                table.newRow();
                table.addHeading(name + " Values:&nbsp;").cell().right();
                table.addCell("NULL!!!!!!!!!");
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) {
                    table.newRow();
                    table.addHeading(name + "[" + i + "]:&nbsp;").cell().right();
                    table.addCell(values[i]);
                }
            }
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left();
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];

            table.newRow();
            table.addHeading(cookie.getName() + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell(cookie.getValue());
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes")
                .attribute("COLSPAN", "2").left();
        Enumeration a = request.getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>");
        }

        /* ------------------------------------------------------------ */
        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getInitParameterNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>");
        }

        table.newRow();
        table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes")
                .attribute("COLSPAN", "2").left();
        a = getServletContext().getAttributeNames();
        while (a.hasMoreElements()) {
            name = (String) a.nextElement();
            table.newRow();
            table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
            table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>");
        }

        if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")
                && request.getContentLength() < 1000000) {
            MultiPartRequest multi = new MultiPartRequest(request);
            String[] parts = multi.getPartNames();

            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content")
                    .attribute("COLSPAN", "2").left();
            for (int p = 0; p < parts.length; p++) {
                name = parts[p];
                table.newRow();
                table.addHeading(name + ":&nbsp;").cell().attribute("VALIGN", "TOP").right();
                table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>");
            }
        }

        String res = request.getParameter("resource");
        if (res != null && res.length() > 0) {
            table.newRow();
            table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res)
                    .attribute("COLSPAN", "2").left();

            table.newRow();
            table.addHeading("this.getClass():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getResource(res));

            table.newRow();
            table.addHeading("this.getClass().getClassLoader():&nbsp;").cell().right();
            table.addCell("" + this.getClass().getClassLoader().getResource(res));

            table.newRow();
            table.addHeading("Thread.currentThread().getContextClassLoader():&nbsp;").cell().right();
            table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res));

            table.newRow();
            table.addHeading("getServletContext():&nbsp;").cell().right();
            try {
                table.addCell("" + getServletContext().getResource(res));
            } catch (Exception e) {
                table.addCell("" + e);
            }
        }

        /* ------------------------------------------------------------ */
        page.add(Break.para);
        page.add(new Heading(1, "Request Wrappers"));
        ServletRequest rw = request;
        int w = 0;
        while (rw != null) {
            page.add((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;
        }

        page.add(Break.para);
        page.add(new Heading(1, "International Characters"));
        page.add("Directly encoced:  Drst<br/>");
        page.add("HTML reference: D&uuml;rst<br/>");
        page.add("Decimal (252) 8859-1: D&#252;rst<br/>");
        page.add("Hex (xFC) 8859-1: D&#xFC;rst<br/>");
        page.add(
                "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>");
        page.add(Break.para);
        page.add(new Heading(1, "Form to generate GET content"));
        TableForm tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("GET");
        tf.addTextField("TextField", "TextField", 20, "value");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(Break.para);
        page.add(new Heading(1, "Form to generate POST content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("TextField", "TextField", 20, "value");
        Select select = tf.addSelect("Select", "Select", true, 3);
        select.add("ValueA");
        select.add("ValueB1,ValueB2");
        select.add("ValueC");
        tf.addButton("Action", "Submit");
        page.add(tf);

        page.add(new Heading(1, "Form to upload content"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.attribute("enctype", "multipart/form-data");
        tf.addFileField("file", "file");
        tf.addButton("Upload", "Upload");
        page.add(tf);

        page.add(new Heading(1, "Form to get Resource"));
        tf = new TableForm(response.encodeURL(getURI(request)));
        tf.method("POST");
        tf.addTextField("resource", "resource", 20, "");
        tf.addButton("Action", "getResource");
        page.add(tf);

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    page.write(pout);

    String data = request.getParameter("data");
    if (data != null && data.length() > 0) {
        int d = Integer.parseInt(data);
        while (d > 0) {
            pout.println("1234567890123456789012345678901234567890123456789\n");
            d = d - 50;

        }
    }

    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");
        if ("/ex7".equals(pi))
            throw new HttpException(501);
    }

    request.getInputStream().close();

}

From source file:org.solmix.wmix.web.servlet.AbstractWmixFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String method = httpRequest.getMethod();

        if ("HEAD".equalsIgnoreCase(method)) {
            httpResponse = new NoBodyResponse(httpResponse);
        }//from w ww .j a v  a  2  s .com

        try {
            doFilter(httpRequest, httpResponse, chain);
        } finally {
            if (httpResponse instanceof NoBodyResponse) {
                ((NoBodyResponse) httpResponse).setContentLength();
            }
        }
    } else {
        LOG.debug("Skipped filtering due to the unknown request/response types: {}, {}",
                request.getClass().getName(), response.getClass().getName());

        chain.doFilter(request, response);
    }

}

From source file:gov.nih.nci.firebird.web.filter.FirebirdCsrfGuardFilter.java

@Override
@SuppressWarnings("PMD.EmptyIfStmt")
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    /** only work with HttpServletRequest objects **/
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession(true);

        CsrfGuard csrfGuard = CsrfGuard.getInstance();
        csrfGuard.getLogger().log(String.format("CsrfGuard analyzing request %s", httpRequest.getRequestURI()));

        InterceptRedirectResponse httpResponse = new InterceptRedirectResponse((HttpServletResponse) response,
                httpRequest, csrfGuard);

        if (BooleanUtils.toBoolean(filterConfig.getInitParameter("Owasp.CsrfGuard.Config.Log.Results"))) {
            logCsrfGuardResults(request, httpRequest, csrfGuard);
        }//from   w  w  w.j  a v a2 s  .c o  m

        if (session.isNew() && csrfGuard.isUseNewTokenLandingPage()) {
            csrfGuard.writeLandingPage(httpRequest, httpResponse);
        } else if (csrfGuard.isValidRequest(httpRequest, httpResponse)) {
            filterChain.doFilter(httpRequest, httpResponse);
        } else {
            /** invalid request - nothing to do - actions already executed **/
        }

        /** update tokens **/
        csrfGuard.updateTokens(httpRequest);

    } else {
        filterConfig.getServletContext()
                .log(String.format("[WARNING] CsrfGuard does not know how to work with requests of class %s ",
                        request.getClass().getName()));

        filterChain.doFilter(request, response);
    }
}

From source file:org.xmlactions.web.conceal.HttpPager.java

public void processPage(ServletRequest request, ServletResponse response, String page)
        throws ServletException, IOException {
    IExecContext execContext = null;// w  w  w. j a v  a  2 s . c om
    if (response instanceof HttpServletResponse && request instanceof HttpServletRequest) {
        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;

            execContext = setupExecContext(httpServletRequest, httpServletResponse);

            String pageName = httpServletRequest.getServletPath();

            if (pageName.indexOf("axelconfig") > 0) {
                PrintWriter out = response.getWriter();
                out.print(buildInfo(httpServletRequest, httpServletResponse));
                out.close();
                return;
            }

            if (!pageName.endsWith(".ajax")) {

                String alternatePage = processPrePages(execContext, httpServletRequest, httpServletResponse);
                if ("stop".equals(execContext.getString("pre.page.stop"))) {
                    execContext.put("pre.page.stop", "");
                    response.setContentType("text/html;charset=UTF-8");

                    PrintWriter out = response.getWriter();
                    out.print(alternatePage);
                    out.close();
                }
            }

            log.debug("contextPath:" + httpServletRequest.getContextPath());
            log.debug("URI:" + httpServletRequest.getRequestURI());
            log.debug("root:" + realPath + " page:" + pageName + " wrapperPage:" + wrapperPage);
            log.debug(HttpSessionInfo.sysInfo(httpServletRequest));
            Action action;
            if (pageName.endsWith(".ajax")) {
                page = processAjaxCall(httpServletRequest, httpServletResponse,
                        pageName.substring(1, pageName.length() - ".ajax".length()), execContext);
                page = StrSubstitutor.replace(page, execContext);
            } else if (pageName.endsWith(".bin") || pageName.endsWith(".pdfbin")) {
                String pn = null;
                if (pageName.endsWith(".pdfbin")) {
                    pn = pageName.substring(1, pageName.length() - ".pdfbin".length());
                } else {
                    pn = pageName.substring(1, pageName.length() - ".bin".length());
                }
                page = processAjaxCall(httpServletRequest, httpServletResponse, pn, execContext);

                if (page.startsWith("EX:")) {
                    PrintWriter out = response.getWriter();
                    out.print(page);
                    out.close();
                } else {
                    byte[] image = (byte[]) execContext.get("image");
                    if (pageName.endsWith(".pdfbin")) {
                        String outputPdfFileName = execContext.getString("outputFileName");
                        String ex = serviceJasperPdfRequest(httpServletResponse, image, outputPdfFileName);
                        if (ex != null) {
                            PrintWriter out = response.getWriter();
                            out.print(page);
                            out.close();
                        }
                        return;
                    } else {

                        String responseType = execContext.getString("response_type");
                        if (StringUtils.isEmpty(responseType)) {
                            responseType = "image/png";
                        }
                        response.setContentType(responseType);

                        processPostPages(execContext, httpServletRequest, httpServletResponse);

                        InputStream in = new ByteArrayInputStream(image);
                        OutputStream out = response.getOutputStream();

                        // Copy the contents of the file to the output
                        // stream
                        byte[] buf = new byte[1024];
                        int count = 0;
                        while ((count = in.read(buf)) >= 0) {
                            out.write(buf, 0, count);
                        }
                        in.close();
                        out.close();
                    }
                    return;
                }
            } else {
                if (pageName.startsWith("/:")) {
                    String wrapperPageName = null;
                    int secondColon = pageName.indexOf(':', 2);
                    if (secondColon >= 0) {
                        wrapperPageName = pageName.substring(2, secondColon);
                        execContext.put("inner_page", "/" + pageName.substring(secondColon + 1));
                    } else {
                        if (StringUtils.isEmpty(wrapperPage)) {
                            throw new ServletException("No wrapper page set, why use :");
                        }
                        wrapperPageName = wrapperPage;
                        execContext.put("inner_page", "/" + pageName.substring(2));
                    }
                    // insert the requested page into the wrapper page
                    action = new Action(realPath, wrapperPageName, nameSpace);
                } else {
                    if (StringUtils.isNotEmpty(wrapperPage)) {
                        // we have a base wrapper page defined
                        execContext.put("inner_page", "/" + pageName);
                        action = new Action(realPath, wrapperPage, nameSpace);
                    } else {
                        if (pageName.indexOf("show_axel_config") >= 0) {
                            page = AxelConfig.getAxelConfig(execContext);
                            log.info(page);
                            page = "Config Copied to Log";
                            action = null;
                        } else {
                            // if we don't have a wrapper page we show the requested page
                            action = new Action(realPath, pageName, nameSpace);
                        }
                    }
                }
                if (action != null) {
                    if (StringUtils.isNotEmpty(page)) {
                        page = action.processPage(execContext, page);
                    } else {
                        page = action.processPage(execContext);
                    }
                }
            }

            log.debug("URI:" + httpServletRequest.getRequestURI());
            // log.debug("page:" + page);
            Object object = execContext.get(ActionConst.NO_STR_SUBST);
            // log.debug(ActionConst.NO_STR_SUBST + ":[" + object + "]");
            execContext.put(ActionConst.NO_STR_SUBST, null);

            if (pageName.toLowerCase().endsWith("soap")) {
                response.setContentType(IExecContext.CONTENT_TYPE_XML);

            } else if (pageName.toLowerCase().endsWith("json")) {
                response.setContentType(IExecContext.CONTENT_TYPE_JSON);

            } else {
                response.setContentType(IExecContext.CONTENT_TYPE_HTML);
            }

            processPostPages(execContext, httpServletRequest, httpServletResponse);

            // = = =
            // check if there is a contentType value stored in the execContext.  This could have been set by one of the actions such as an action that wants to return a JSON data.
            // = = =
            String contentType = execContext.getString(IExecContext.CONTENT_TYPE_KEY);
            if (StringUtils.isNotBlank(contentType)) {
                response.setContentType(contentType);
                //               if (contentType.equals(IExecContext.CONTENT_TYPE_JSON) || contentType.equals(IExecContext.CONTENT_TYPE_XML)) {
                //                  if (response instanceof HttpServletResponse) {
                //                     ((HttpServletResponse)response).setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1
                //                     ((HttpServletResponse)response).setHeader("Pragma", "no-cache"); // HTTP 1.0
                //                     ((HttpServletResponse)response).setDateHeader("Expires", 0); // Proxies.
                //                  }
                //               }
            }
            execContext.remove("content_type");
            PrintWriter out = response.getWriter();
            out.print(page);
            out.close();

        } catch (Throwable t) {
            // TODO review this, use a better way for reporting the error.
            log.info(t.getMessage(), t);
            throw new ServletException(t);
        } finally {
            if (execContext != null) {
                execContext.saveToPersistence();
                RequestExecContext.remove();
            }
        }
    } else {
        String msg = "Not processing page. Must be HttpServletRequest not [" + request.getClass().getName()
                + "] and HttpServletResponse not [" + response.getClass().getName() + "]";

        log.info(msg);
        throw new ServletException(msg);
    }
}

From source file:org.apache.catalina.core.ApplicationDispatcher.java

/**
 * Create and return a request wrapper that has been inserted in the
 * appropriate spot in the request chain.
 *///from  www. ja  v a  2s  .c  om
private ServletRequest wrapRequest() {

    // Locate the request we should insert in front of
    ServletRequest previous = null;
    ServletRequest current = outerRequest;
    while (current != null) {
        if ("org.apache.catalina.servlets.InvokerHttpRequest".equals(current.getClass().getName()))
            break; // KLUDGE - Make nested RD.forward() using invoker work
        if (!(current instanceof ServletRequestWrapper))
            break;
        if (current instanceof ApplicationHttpRequest)
            break;
        if (current instanceof ApplicationRequest)
            break;
        if (current instanceof Request)
            break;
        previous = current;
        current = ((ServletRequestWrapper) current).getRequest();
    }

    // Instantiate a new wrapper at this point and insert it in the chain
    ServletRequest wrapper = null;
    if ((current instanceof ApplicationHttpRequest) || (current instanceof HttpRequest)
            || (current instanceof HttpServletRequest)) {
        // Compute a crossContext flag
        HttpServletRequest hcurrent = (HttpServletRequest) current;
        boolean crossContext = !(context.getPath().equals(hcurrent.getContextPath()));
        wrapper = new ApplicationHttpRequest(hcurrent, context, crossContext);
    } else {
        wrapper = new ApplicationRequest(current);
    }
    if (previous == null)
        outerRequest = wrapper;
    else
        ((ServletRequestWrapper) previous).setRequest(wrapper);
    wrapRequest = wrapper;
    return (wrapper);

}