Example usage for javax.servlet.http HttpServletRequestWrapper getRequestDispatcher

List of usage examples for javax.servlet.http HttpServletRequestWrapper getRequestDispatcher

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequestWrapper getRequestDispatcher.

Prototype

public RequestDispatcher getRequestDispatcher(String path) 

Source Link

Document

The default behavior of this method is to return getRequestDispatcher(String path) on the wrapped request object.

Usage

From source file:com.navercorp.pinpoint.web.servlet.RewriteForV2Filter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (enable) {
        HttpServletRequest req = (HttpServletRequest) request;
        String requestURI = req.getRequestURI();

        if (isRedirectTarget(requestURI)) {
            HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper((HttpServletRequest) request);
            RequestDispatcher dispatcher = wrapper.getRequestDispatcher("/v2/index.html");

            dispatcher.forward(request, response);
        } else {/*from ww  w .  jav  a2 s .com*/
            chain.doFilter(request, response);
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:org.broadleafcommerce.openadmin.web.filter.BroadleafAdminTypedEntityRequestFilter.java

@SuppressWarnings("unchecked")
public boolean isRequestForTypedEntity(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    String servletPath = request.getServletPath();
    if (!servletPath.contains(":")) {
        return false;
    }/* w  w w.ja  va  2s .c  o  m*/

    // Find the Admin Section for the typed entity.
    String sectionKey = getSectionKeyFromRequest(request);
    AdminSection typedEntitySection = adminNavigationService.findAdminSectionByURI(sectionKey);

    // If the Typed Entity Section does not exist, continue with the filter chain.
    if (typedEntitySection == null) {
        return false;
    }

    // Check if admin user has access to this section.
    if (!adminUserHasAccess(typedEntitySection)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access is denied");
        return true;
    }

    // Add the typed entity admin section to the request.
    request.setAttribute("typedEntitySection", typedEntitySection);

    // Find the type and build the new path.
    String type = getEntityTypeFromRequest(request);
    final String forwardPath = servletPath.replace(type, "");

    // Get the type field name on the Entity for the given section.
    String typedFieldName = getTypeFieldName(typedEntitySection);

    // Build out the new parameter map to be forwarded.
    final Map parameters = new LinkedHashMap(request.getParameterMap());
    if (typedFieldName != null) {
        parameters.put(typedFieldName, new String[] { type.substring(1).toUpperCase() });
    }

    // Build our request wrapper.
    final HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
        @Override
        public String getParameter(String name) {
            Object temp = parameters.get(name);
            Object[] response = new Object[0];
            if (temp != null) {
                ArrayUtils.addAll(response, temp);
            }
            if (ArrayUtils.isEmpty(response)) {
                return null;
            } else {
                return (String) response[0];
            }
        }

        @Override
        public Map getParameterMap() {
            return parameters;
        }

        @Override
        public Enumeration getParameterNames() {
            return new IteratorEnumeration(parameters.keySet().iterator());
        }

        @Override
        public String[] getParameterValues(String name) {
            return (String[]) parameters.get(name);
        }

        @Override
        public String getServletPath() {
            return forwardPath;
        }
    };
    requestProcessor.process(new ServletWebRequest(wrapper, response));

    // Forward the wrapper to the appropriate path
    wrapper.getRequestDispatcher(wrapper.getServletPath()).forward(wrapper, response);
    return true;
}

From source file:org.jahia.services.render.webflow.WebflowDispatcherScript.java

/**
 * Execute the script and return the result as a string
 *
 * @param resource resource to display//w  ww.  j  a v  a  2  s  .co m
 * @param context
 * @return the rendered resource
 * @throws org.jahia.services.render.RenderException
 *
 */
public String execute(Resource resource, RenderContext context) throws RenderException {
    final View view = getView();
    if (view == null) {
        throw new RenderException("View not found for : " + resource);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("View '" + view + "' resolved for resource: " + resource);
        }
    }

    String identifier;
    try {
        identifier = resource.getNode().getIdentifier();
    } catch (RepositoryException e) {
        throw new RenderException(e);
    }
    String identifierNoDashes = StringUtils.replace(identifier, "-", "_");
    if (!view.getKey().equals("default")) {
        identifierNoDashes += "__" + view.getKey();
    }

    HttpServletRequest request;
    HttpServletResponse response = context.getResponse();

    @SuppressWarnings("unchecked")
    final Map<String, List<String>> parameters = (Map<String, List<String>>) context.getRequest()
            .getAttribute("actionParameters");

    if (xssFilteringEnabled && parameters != null) {
        final Map<String, String[]> m = Maps.transformEntries(parameters,
                new Maps.EntryTransformer<String, List<String>, String[]>() {
                    @Override
                    public String[] transformEntry(@Nullable String key, @Nullable List<String> value) {
                        return value != null ? value.toArray(new String[value.size()]) : null;
                    }
                });
        request = new WebflowHttpServletRequestWrapper(context.getRequest(), m, identifierNoDashes);
    } else {
        request = new WebflowHttpServletRequestWrapper(context.getRequest(),
                new HashMap<>(context.getRequest().getParameterMap()), identifierNoDashes);
    }

    String s = (String) request.getSession().getAttribute("webflowResponse" + identifierNoDashes);
    if (s != null) {
        request.getSession().removeAttribute("webflowResponse" + identifierNoDashes);
        return s;
    }

    // skip aggregation for potentials fragments under the webflow
    boolean aggregationSkippedForWebflow = false;
    if (!AggregateFilter.skipAggregation(context.getRequest())) {
        aggregationSkippedForWebflow = true;
        context.getRequest().setAttribute(AggregateFilter.SKIP_AGGREGATION, true);
    }

    flowPath = MODULE_PREFIX_PATTERN.matcher(view.getPath()).replaceFirst("");

    RequestDispatcher rd = request.getRequestDispatcher("/flow/" + flowPath);

    Object oldModule = request.getAttribute("currentModule");
    request.setAttribute("currentModule", view.getModule());

    if (logger.isDebugEnabled()) {
        dumpRequestAttributes(request);
    }

    StringResponseWrapper responseWrapper = new StringResponseWrapper(response);

    try {
        FlowDefinitionRegistry reg = ((FlowDefinitionRegistry) view.getModule().getContext()
                .getBean("jahiaFlowRegistry"));
        final GenericApplicationContext applicationContext = (GenericApplicationContext) reg
                .getFlowDefinition(flowPath).getApplicationContext();
        applicationContext.setClassLoader(view.getModule().getClassLoader());
        applicationContext.setResourceLoader(new ResourceLoader() {
            @Override
            public org.springframework.core.io.Resource getResource(String location) {
                return applicationContext.getParent().getResource("/" + flowPath + "/" + location);
            }

            @Override
            public ClassLoader getClassLoader() {
                return view.getModule().getClassLoader();
            }
        });

        rd.include(request, responseWrapper);

        String redirect = responseWrapper.getRedirect();
        if (redirect != null && context.getRedirect() == null) {
            // if we have an absolute redirect, set it and move on
            if (redirect.startsWith("http:/") || redirect.startsWith("https://")) {
                context.setRedirect(responseWrapper.getRedirect());
            } else {
                while (redirect != null) {
                    final String qs = StringUtils.substringAfter(responseWrapper.getRedirect(), "?");
                    final Map<String, String[]> params = new HashMap<String, String[]>();
                    if (!StringUtils.isEmpty(qs)) {
                        params.put("webflowexecution" + identifierNoDashes, new String[] { StringUtils
                                .substringAfterLast(qs, "webflowexecution" + identifierNoDashes + "=") });
                    }
                    HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request) {
                        @Override
                        public String getMethod() {
                            return "GET";
                        }

                        @SuppressWarnings("rawtypes")
                        @Override
                        public Map getParameterMap() {
                            return params;
                        }

                        @Override
                        public String getParameter(String name) {
                            return params.containsKey(name) ? params.get(name)[0] : null;
                        }

                        @Override
                        public Enumeration getParameterNames() {
                            return new Vector(params.keySet()).elements();
                        }

                        @Override
                        public String[] getParameterValues(String name) {
                            return params.get(name);
                        }

                        @Override
                        public Object getAttribute(String name) {
                            if (WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE.equals(name)) {
                                return qs;
                            }
                            return super.getAttribute(name);
                        }

                        @Override
                        public String getQueryString() {
                            return qs;
                        }
                    };
                    rd = requestWrapper.getRequestDispatcher("/flow/" + flowPath + "?" + qs);
                    responseWrapper = new StringResponseWrapper(response);
                    rd.include(requestWrapper, responseWrapper);

                    String oldRedirect = redirect;
                    redirect = responseWrapper.getRedirect();
                    if (redirect != null) {
                        // if we have an absolute redirect, exit the loop
                        if (redirect.startsWith("http://") || redirect.startsWith("https://")) {
                            context.setRedirect(redirect);
                            break;
                        }
                    } else if (request.getMethod().equals("POST")) {
                        // set the redirect to the last non-null one
                        request.getSession().setAttribute("webflowResponse" + identifierNoDashes,
                                responseWrapper.getString());
                        context.setRedirect(oldRedirect);
                    }
                }
            }
        }
    } catch (ServletException e) {
        throw new RenderException(e.getRootCause() != null ? e.getRootCause() : e);
    } catch (IOException e) {
        throw new RenderException(e);
    } finally {
        request.setAttribute("currentModule", oldModule);
    }
    try {
        if (aggregationSkippedForWebflow) {
            request.removeAttribute(AggregateFilter.SKIP_AGGREGATION);
        }
        return responseWrapper.getString();
    } catch (IOException e) {
        throw new RenderException(e);
    }
}