Example usage for javax.servlet ServletRequest getRequestDispatcher

List of usage examples for javax.servlet ServletRequest getRequestDispatcher

Introduction

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

Prototype

public RequestDispatcher getRequestDispatcher(String path);

Source Link

Document

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

Usage

From source file:com.persistent.cloudninja.controller.CloudNinjaAuthFilter.java

/**
 * This method filters every incoming request.
 * If request contains cookie, it checks whether the cookie is valid.
 *    A. If request cookie is present and is valid, forwards the request 
 *          to next page./*  w ww .j av  a  2 s.  c o  m*/
 *    B. If cookie is not valid and request is not coming from ACS, this
 *          method redirects the request to ACS login page.
 * If request does not contain a cookie, but contains an ACS token,
 * this method, creates or updates cookie and 
 * forwards the request to landing page.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    // capture ACS response
    String acsToken = httpServletRequest.getParameter("wresult");
    if (null != acsToken && acsToken.trim().length() == 0) {
        acsToken = null;
    }
    String isEncodedWresult = httpServletRequest.getParameter("isEncodedWresult");
    String decodedTokenString = null;
    if (null != acsToken && null != isEncodedWresult && isEncodedWresult.trim().equalsIgnoreCase("true")) {
        decodedTokenString = new String(URLDecoder.decode(acsToken, "UTF-8"));
        acsToken = decodedTokenString;
    }

    // by pass the url access validation validateInvitationCode
    if (httpServletRequest.getRequestURI().contains("/validateInvitationCode")) {
        request.getRequestDispatcher("/validateInvitationCode.htm").forward(httpServletRequest,
                httpServletResponse);
    } else {

        CloudNinjaUser cloudNinjaUser = null;

        boolean isValidCookiePresent = false;
        String cookieName = CloudNinjaConstants.AUTH_COOKIE_NAME;

        Cookie preExistentCookie = AuthFilterUtils.checkForPreExistentCookie(httpServletRequest, cookieName);

        if (preExistentCookie != null && StringUtils.isNotBlank(preExistentCookie.getValue())) {
            isValidCookiePresent = AuthFilterUtils.checkValidityOfCookie(preExistentCookie);
        }

        if (isValidCookiePresent) {
            Cookie cookieToUse = AuthFilterUtils.checkForPreExistentCookie(httpServletRequest, cookieName);
            cookieToUse.setPath("/");
            httpServletResponse.addCookie(cookieToUse);

            // Add cookie userNames, etc to request attributes
            httpServletRequest.setAttribute("cookieNameAttr", cookieToUse.getValue());

            forwardToNextPage(httpServletRequest, httpServletResponse, chain);
        } else if (!isValidCookiePresent && (acsToken == null)) {
            redirectToACSPage(httpServletRequest, httpServletResponse);
            return;
        } else if (acsToken != null) {

            acsToken = new String(acsToken.getBytes(), CloudNinjaConstants.UTF_8_FORMAT);
            boolean isValidCertificate = AuthFilterUtils.checkCertificateValidity(acsToken);
            if (!isValidCertificate) {
                redirectToACSPage(httpServletRequest, httpServletResponse);
                return;
            }

            try {
                cloudNinjaUser = parseSAMLResponseAndCreateCNUser(acsToken);
            } catch (CertificateEncodingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            String liveGuid = null;

            //  GUID is present and user is null it means that user is from windowsLiveId
            // and is login-in in for the first time so we need to ask for verification code
            if (cloudNinjaUser != null && cloudNinjaUser.getUser() == null) {
                liveGuid = cloudNinjaUser.getLiveGUID();
                cloudNinjaUser = null;
                forwardToVerificationPage(httpServletRequest, httpServletResponse, liveGuid, acsToken);
                return;
            }
            // if user is null and no GUID is present
            // redirect to ACS page

            if (null == cloudNinjaUser) {
                redirectToACSPage(httpServletRequest, httpServletResponse);
                return;
            }

            Cookie cookieToUse;
            if (preExistentCookie == null) {
                cookieToUse = AuthFilterUtils.createNewCookieForACSAuthenticatedUser(cloudNinjaUser,
                        cookieName);
            } else {
                cookieToUse = AuthFilterUtils.updateExistingCookie(preExistentCookie, cloudNinjaUser);
            }
            cookieToUse.setMaxAge(getCookieMaxAge());
            cookieToUse.setPath("/");
            httpServletResponse.addCookie(cookieToUse);
            httpServletRequest.setAttribute("cookieNameAttr", cookieToUse.getValue());

            forwardToLandingPage(httpServletRequest, httpServletResponse, chain, cloudNinjaUser);
        }
    }
}

From source file:org.ops4j.pax.web.service.internal.WelcomeFilesFilter.java

/**
 * Serves the welcome files if request path ends with "/".
 *
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 *///from   www .j a  va2 s . c  o m
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    LOG.debug("Apply welcome files filter...");
    if (m_welcomeFiles.length > 0 && request instanceof HttpServletRequest) {
        String servletPath = (((HttpServletRequest) request).getServletPath());
        String pathInfo = ((HttpServletRequest) request).getPathInfo();

        LOG.debug("Servlet path: " + servletPath);
        LOG.debug("Path info: " + pathInfo);

        if ((pathInfo != null && pathInfo.endsWith("/"))
                || (servletPath != null && servletPath.endsWith("/"))) {
            final ServletContext servletContext = m_filterConfig.getServletContext();
            for (String welcomeFile : m_welcomeFiles) {
                final String welcomePath = addPaths(servletPath, addPaths(pathInfo, welcomeFile));
                final URL welcomeFileUrl = servletContext.getResource(welcomePath);
                if (welcomeFileUrl != null) {
                    if (m_redirect && response instanceof HttpServletResponse) {
                        ((HttpServletResponse) response).sendRedirect(welcomeFile);
                        return;
                    } else {
                        final RequestDispatcher requestDispatcher = request.getRequestDispatcher(welcomePath);
                        if (requestDispatcher != null) {
                            requestDispatcher.forward(request, response);
                            return;
                        }
                    }
                }
            }
        }
    } else {
        if (m_welcomeFiles.length == 0) {
            LOG.debug("Welcome filter not applied as there are no welcome files configured.");
        }
        if (!(request instanceof HttpServletRequest)) {
            LOG.debug("Welcome filter not applied as the request is not an "
                    + HttpServletRequest.class.getSimpleName());
        }
    }
    // if we are here means that the request was not handled by welcome files filter so, go on
    chain.doFilter(request, response);
}

From source file:com.netspective.sparx.navigate.NavigationPage.java

/**
 * Main method for handling the logic and content of the page. Generally, a navigation page is broken into
 * several sections: header, metadata, body, and footer. If there are no forwards/redirects configured, the page
 * sections are handled by calling the following methods: <code>handlePageMetaData()</code>, <code>handlePageHeader()</code>,
 * <code>handlePageBody()</code>, and <code>handlePageFooter()</code> methods.
 *
 * @param writer Writer object to write the page output to
 * @param nc     current navigation context
 *//*from w  w w  .  j  a v a2s. c o  m*/
public void handlePage(Writer writer, NavigationContext nc) throws ServletException, IOException {
    Flags flags = (Flags) nc.getActiveState().getFlags();

    enterPage(nc);
    if (getBodyType().getValueIndex() == NavigationPageBodyType.FORWARD) {
        // if we're forwarding to another resource we don't want to put anything into the response otherwise
        // there will be an illegal state exception -- so, we don't create headers, footers, etc because that's
        // the user's responsibility in the forwarded resource.

        String forwardUrl = getForward().getTextValue(nc);
        ServletRequest req = nc.getRequest();
        RequestDispatcher rd = req.getRequestDispatcher(forwardUrl);
        req.setAttribute(REQATTRNAME_NAVIGATION_CONTEXT, nc);
        rd.forward(req, nc.getResponse());
        req.removeAttribute(REQATTRNAME_NAVIGATION_CONTEXT);
    } else if (bodyAffectsNavigationContext(nc)) {
        // render the body first and let it modify the navigation context
        StringWriter body = new StringWriter();
        boolean hasError = false;
        try {
            handlePageBody(body, nc);
        } catch (Exception e) {
            getLog().error("Error occurred while handling the page.", e);
            if (!findErrorPage(nc, e))
                nc.setErrorPageException(getOwner().getDefaultErrorPage(), e, e.getClass());
            nc.getErrorPage().handlePageBody(writer, nc);
            hasError = true;
        }

        if (!hasError && !nc.isRedirected()) {
            if (flags.flagIsSet(Flags.HANDLE_META_DATA))
                handlePageMetaData(writer, nc);
            if (flags.flagIsSet(Flags.HANDLE_HEADER))
                handlePageHeader(writer, nc);
            writer.write(body.getBuffer().toString());
            if (flags.flagIsSet(Flags.HANDLE_FOOTER))
                handlePageFooter(writer, nc);
        }

        // try and do an early GC if possible
        body = null;
    } else {
        if (flags.flagIsSet(Flags.HANDLE_META_DATA))
            handlePageMetaData(writer, nc);
        if (flags.flagIsSet(Flags.HANDLE_HEADER))
            handlePageHeader(writer, nc);
        try {
            handlePageBody(writer, nc);
        } catch (Exception e) {
            getLog().error("Error occurred while handling the page.", e);
            if (!findErrorPage(nc, e))
                nc.setErrorPageException(getOwner().getDefaultErrorPage(), e, e.getClass());
            nc.getErrorPage().handlePageBody(writer, nc);
        }
        if (flags.flagIsSet(Flags.HANDLE_FOOTER))
            handlePageFooter(writer, nc);
    }
    exitPage(nc);
}

From source file:org.openanzo.servlet.WelcomeFilesFilter.java

/**
 * Serves the welcome files if request path ends with "/".
 * /* w  w  w  .ja  v a 2  s . c o  m*/
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    LOG.debug("Apply welcome files filter...");
    if (m_welcomeFiles.length > 0 && request instanceof HttpServletRequest) {
        String servletPath = (((HttpServletRequest) request).getServletPath());
        String pathInfo = ((HttpServletRequest) request).getPathInfo();

        LOG.debug("Servlet path: " + servletPath);
        LOG.debug("Path info: " + pathInfo);

        if ((pathInfo != null && pathInfo.endsWith("/"))
                || (servletPath != null && servletPath.endsWith("/"))) {
            final ServletContext servletContext = m_filterConfig.getServletContext();
            for (String welcomeFile : m_welcomeFiles) {
                final String welcomePath = URIUtil.addPaths(servletPath,
                        URIUtil.addPaths(pathInfo, welcomeFile));
                final String welcomeResource = URIUtil.addPaths(pathInfo, welcomeFile);
                final URL welcomeFileUrl = servletContext.getResource(welcomeResource);
                if (welcomeFileUrl != null) {
                    if (m_redirect && response instanceof HttpServletResponse) {
                        ((HttpServletResponse) response).sendRedirect(welcomeFile);
                        return;
                    } else {
                        final RequestDispatcher requestDispatcher = request.getRequestDispatcher(welcomePath);
                        if (requestDispatcher != null) {
                            requestDispatcher.forward(request, response);
                            return;
                        }
                    }
                }
            }
        } else if ((pathInfo == null || pathInfo.length() == 0)
                && (servletPath != null && paths.contains(servletPath))) {
            final ServletContext servletContext = m_filterConfig.getServletContext();
            for (String welcomeFile : m_welcomeFiles) {
                final String welcomePath = URIUtil.addPaths(servletPath, welcomeFile);
                final String welcomeResource = welcomeFile;
                final URL welcomeFileUrl = servletContext.getResource(welcomeResource);
                if (welcomeFileUrl != null) {
                    if (m_redirect && response instanceof HttpServletResponse) {
                        ((HttpServletResponse) response).sendRedirect(welcomePath);
                        return;
                    } else {
                        final RequestDispatcher requestDispatcher = request.getRequestDispatcher(welcomePath);
                        if (requestDispatcher != null) {
                            requestDispatcher.forward(request, response);
                            return;
                        }
                    }
                }
            }
        }
    } else {
        if (m_welcomeFiles.length == 0) {
            LOG.debug("Welcome filter not applied as there are no welcome files configured.");
        }
        if (!(request instanceof HttpServletRequest)) {
            LOG.debug("Welcome filter not applied as the request is not an "
                    + HttpServletRequest.class.getSimpleName());
        }
    }
    // if we are here means that the request was not handled by welcome files filter so, go on
    chain.doFilter(request, response);
}

From source file:com.mobileman.filter.SecurityCheckFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest rq1 = (HttpServletRequest) request;
    String requestURI = rq1.getRequestURI().toLowerCase();
    DataHolder holder = new DataHolder(rq1);
    boolean error = false;
    if (requestURI.contains("/patient/")) {
        //check patient loaded         
        if (!holder.isPatient()) {
            error = true;/*  ww  w. j av  a 2 s . co  m*/
        }
    } else if (requestURI.contains("/arzt/")) {
        //check doctor loaded
        if (!holder.isDoctor()) {
            error = true;
        }
    } else if (requestURI.contains("/admin/") && !requestURI.contains("/admin/anmeldung")) {
        //check admin loaded
        if (!holder.isAdmin()) {
            error = true;
        }
    }

    ///////////////
    if (requestURI.contains("/public")) {
        //redirect to /behandlung
        StringBuffer sb = rq1.getRequestURL();
        String newUrl = StringUtils.replace(sb.toString(), "/public", "/behandlung");
        java.io.PrintWriter out = response.getWriter();
        response.setContentType("text/html");

        out.println("<html>");
        out.println("<head>");
        out.println("<meta http-equiv=\"refresh\" content=\"0;url=");
        out.print(newUrl);
        out.println("\" />");
        out.println("</head>");
        out.println("<body>");
        out.println("</body>");
        out.println("</html>");

        return;
    }

    if (error) {
        //redirect
        request.getRequestDispatcher("/").forward(request, response);
        return;
    }
    filterChain.doFilter(request, response);
}

From source file:org.gridsphere.servlets.GridSphereFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    log.info("START");
    if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        //PersistenceManagerService pms = null;

        // If first time being called, instantiate all portlets

        if (firstDoGet.equals(Boolean.TRUE)) {

            SettingsService settingsService = (SettingsService) PortletServiceFactory
                    .createPortletService(SettingsService.class, true);
            // check if database file exists
            String release = SportletProperties.getInstance().getProperty("gridsphere.release");
            int idx = release.lastIndexOf(" ");
            String gsversion = release.substring(idx + 1);

            //System.err.println("gsversion=" + gsversion);

            String dbpath = settingsService.getRealSettingsPath("/database/GS_" + gsversion);

            File dbfile = new File(dbpath);

            if (!dbfile.exists()) {
                request.setAttribute("setup", "true");
                RequestDispatcher rd = request.getRequestDispatcher("/setup");
                rd.forward(request, response);
                return;
            }//from  w  w  w . jav a  2 s .co m

            PersistenceManagerService pms = (PersistenceManagerService) PortletServiceFactory
                    .createPortletService(PersistenceManagerService.class, true);
            PersistenceManagerRdbms pm = null;
            boolean noAdmin = true;
            try {
                log.info("Starting a database transaction");
                pm = pms.createGridSphereRdbms();
                pm.setClassLoader(Thread.currentThread().getContextClassLoader());
                pm.beginTransaction();

                RoleManagerService roleService = (RoleManagerService) PortletServiceFactory
                        .createPortletService(RoleManagerService.class, true);
                noAdmin = roleService.getUsersInRole(PortletRole.ADMIN).isEmpty();

                pm.endTransaction();
            } catch (StaleObjectStateException staleEx) {
                log.error("This interceptor does not implement optimistic concurrency control!");
                log.error("Your application will not work until you add compensation actions!");
            } catch (Throwable ex) {
                ex.printStackTrace();
                pm.endTransaction();
                try {
                    pm.rollbackTransaction();
                } catch (Throwable rbEx) {
                    log.error("Could not rollback transaction after exception!", rbEx);
                }
            }

            if (noAdmin) {
                request.setAttribute("setup", "true");
                RequestDispatcher rd = request.getRequestDispatcher("/setup");
                rd.forward(request, response);
                return;
            }

            if (!portletsLoaded) {
                System.err.println("Loading portlets!!!");
                log.info("Loading portlets");
                try {
                    // load all portlets
                    PortletManagerService portletManager = (PortletManagerService) PortletServiceFactory
                            .createPortletService(PortletManagerService.class, true);
                    portletManager.loadAllPortletWebApplications(req, res);
                    portletsLoaded = Boolean.TRUE;
                } catch (Exception e) {
                    log.error("GridSphere initialization failed!", e);
                    RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp");
                    req.setAttribute("error", e);
                    rd.forward(req, res);
                    return;
                }
            }
            PortletsSetupModuleService portletsSetupModuleService = null;
            try {
                portletsSetupModuleService = (PortletsSetupModuleService) PortletServiceFactory
                        .createPortletService(PortletsSetupModuleService.class, true);
                if (!portletsSetupModuleService.isPreInitSetupDone()) {
                    request.setAttribute("setup", "true");
                    RequestDispatcher rd = request.getRequestDispatcher("/setup");
                    rd.forward(request, response);
                    return;
                }
            } catch (Exception e) {
                log.error("GridSphere initialization failed!", e);
                RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp");
                req.setAttribute("error", e);
                rd.forward(req, res);
                return;
            }

            if (!portletsInitialized) {
                System.err.println("Initializing portlets!!!");
                log.info("Initializing portlets");
                try {
                    // initialize all portlets
                    PortletManagerService portletManager = (PortletManagerService) PortletServiceFactory
                            .createPortletService(PortletManagerService.class, true);
                    portletManager.initAllPortletWebApplications(req, res);
                    portletsInitialized = Boolean.TRUE;
                } catch (Exception e) {
                    log.error("GridSphere initialization failed!", e);
                    RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp");
                    req.setAttribute("error", e);
                    rd.forward(req, res);
                    return;
                }
            }
            if (!portletsSetupModuleService.isPostInitSetupDone()) {
                request.setAttribute("setup", "true");
                RequestDispatcher rd = request.getRequestDispatcher("/setup");
                rd.forward(request, response);
                return;
            }
            firstDoGet = Boolean.FALSE;
        }

        String pathInfo = req.getPathInfo();
        StringBuffer requestURL = req.getRequestURL();
        String requestURI = req.getRequestURI();
        String query = req.getQueryString();
        log.info("\ncontext path = " + req.getContextPath() + " servlet path=" + req.getServletPath());
        log.info("\n pathInfo= " + pathInfo + " query= " + query);
        log.info(" requestURL= " + requestURL + " requestURI= " + requestURI + "\n");

        String extraInfo = "";

        // use the servlet path to determine where to forward
        // expect servlet path = /servletpath/XXXX

        String path = req.getServletPath();
        int start = path.indexOf("/", 1);

        if ((start > 0) && (path.length() - 1) > start) {

            String parsePath = path.substring(start + 1);
            //System.err.println(parsePath);
            extraInfo = "?";

            StringTokenizer st = new StringTokenizer(parsePath, "/");

            String layoutId = null;
            if (st.hasMoreTokens()) {
                layoutId = (String) st.nextElement();
                extraInfo += SportletProperties.LAYOUT_PAGE_PARAM + "=" + layoutId;
            }
            if (st.hasMoreTokens()) {
                String cid = (String) st.nextElement();
                extraInfo += "&" + SportletProperties.COMPONENT_ID + "=" + cid;
            }
            if (st.hasMoreTokens()) {
                // check for /a/ or /r/ to indicate if it's a render or action
                String phase = (String) st.nextElement();
                if (phase.equals("a")) {
                    if (st.hasMoreTokens()) {
                        extraInfo += "&" + SportletProperties.IS_ACTION + "=1" + "&"
                                + SportletProperties.DEFAULT_PORTLET_ACTION + "=" + (String) st.nextElement();
                    } else {
                        extraInfo += "&" + SportletProperties.IS_ACTION + "=1";
                    }
                } else if (phase.equals("r")) {
                    if (st.hasMoreTokens()) {
                        extraInfo += "&" + SportletProperties.DEFAULT_PORTLET_RENDER + "="
                                + (String) st.nextElement();
                    } else {
                        extraInfo += "&" + SportletProperties.DEFAULT_PORTLET_RENDER + "=";
                    }
                } else if (phase.equals("m")) {
                    if (st.hasMoreTokens()) {
                        extraInfo += "&" + SportletProperties.PORTLET_MODE + "=" + (String) st.nextElement();
                    }
                } else if (phase.equals("s")) {
                    if (st.hasMoreTokens()) {
                        extraInfo += "&" + SportletProperties.PORTLET_WINDOW + "=" + (String) st.nextElement();
                    }
                }
                HttpSession session = req.getSession();
                //capture after login redirect (GPF-463 feature) URI but not for:
                // - login or register layout
                // - logged in users
                // - actions (security reasons)
                // - sessions which already has captured URI
                if (!"login".equals(layoutId) && !"register".equals(layoutId) && !"a".equals(phase)
                        && null != session && null == session.getAttribute(SportletProperties.PORTLET_USER)
                        && null == session.getAttribute(SportletProperties.PORTAL_REDIRECT_PATH)) {
                    String afterLoginRedirect = requestURI;
                    if (null != query) {
                        afterLoginRedirect += '?' + query;
                    }
                    session.setAttribute(SportletProperties.PORTAL_REDIRECT_PATH, afterLoginRedirect);
                }

            }
            if (query != null) {
                extraInfo += "&" + query;
            }
            //String ctxPath = "/" + configService.getProperty("gridsphere.context");
        }

        //chain.doFilter(request, response);

        String ctxPath = "/gs";

        log.info("forwarded URL: " + ctxPath + extraInfo);

        context.getRequestDispatcher(ctxPath + extraInfo).forward(req, res);

        log.info("END");

    }

}

From source file:optional.BasicFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    //extract actionname cut of ".do" results in /actionname
    String look = getActionMappingName(((HttpServletRequest) request).getServletPath());

    System.out.println(">>" + look);

    boolean isMultipart = ServletFileUpload.isMultipartContent((HttpServletRequest) request);

    try {//from w  w w  .  j a  va 2s  .  c om
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List /* FileItem */ items = upload.parseRequest((HttpServletRequest) request);

    } catch (FileUploadException e) {

    }

    System.out.println(request.getParameterMap());

    ConfigWrapper config = (ConfigWrapper) actions.get(look);

    if (config == null) {
        return;
    }

    try {
        DirectInterface bean = (DirectInterface) config.getActionclass().newInstance();

        BeanUtils.populate(bean, request.getParameterMap());

        bean.doexecute((HttpServletRequest) request, (HttpServletResponse) response);

    } catch (Exception e) {
        System.out.println();
    }
    //chain.doFilter(request, response);

    //RequestDispatcher rd = request.getRequestDispatcher("/home.jsp");
    RequestDispatcher rd = request.getRequestDispatcher("/blank_view.jsp");
    rd.forward(request, response);
}

From source file:org.seasar.s2click.filter.UrlPatternFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest req = HttpServletRequest.class.cast(request);

    String requestUri = req.getRequestURI();
    String context = req.getContextPath();
    String queryString = req.getQueryString();

    String requestPath = requestUri.substring(context.length());
    if (StringUtils.isNotEmpty(queryString)) {
        requestPath = requestPath + "?" + queryString;
    }/*from   w ww .  ja  va 2s .  c o  m*/
    if (logger.isDebugEnabled()) {
        logger.debug("UrlRewriteFilter???");
        logger.debug("" + requestPath);
    }

    // ?????????
    if (excludePattern != null) {
        Matcher matcher = excludePattern.matcher(requestPath);
        if (matcher.matches()) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "?????UrlRewriteFilter?????");
            }
            chain.doFilter(request, response);
            return;
        }
    }

    // HOT deploy??????ClickApp??
    S2Container container = SingletonS2ContainerFactory.getContainer();

    if (SmartDeployUtil.isHotdeployMode(container) && request.getAttribute(HOTDEPLOY_INIT_KEY) == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("UrlRewriteFilter?Click??????");
        }

        request.setAttribute(HOTDEPLOY_INIT_KEY, "initialize");
        RequestDispatcher dispatcher = request.getRequestDispatcher("/init.htm");
        dispatcher.include(request, response);
    }

    for (UrlRewriteInfo info : UrlPatternManager.getAll()) {
        Matcher matcher = info.pattern.matcher(requestPath);
        if (matcher.matches()) {
            StringBuilder realPath = new StringBuilder();
            realPath.append(info.realPath);
            for (int i = 0; i < info.parameters.length; i++) {
                if (i == 0) {
                    realPath.append("?");
                } else {
                    realPath.append("&");
                }
                realPath.append(info.parameters[i]);
                realPath.append("=");
                realPath.append(matcher.group(i + 1));
            }

            if (logger.isDebugEnabled()) {
                logger.debug(realPath.toString() + "????");
            }

            RequestDispatcher dispatcher = request.getRequestDispatcher(realPath.toString());
            dispatcher.forward(request, response);
            return;
        }
    }

    chain.doFilter(request, response);
}

From source file:com.microsoft.aad.adal4jsample.BasicFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        try {//from w w  w  .j  a  v  a2s.  c o  m
            String currentUri = httpRequest.getRequestURL().toString();
            String queryStr = httpRequest.getQueryString();
            String fullUrl = currentUri + (queryStr != null ? "?" + queryStr : "");

            // check if user has a AuthData in the session
            if (!AuthHelper.isAuthenticated(httpRequest)) {
                if (AuthHelper.containsAuthenticationData(httpRequest)) {
                    processAuthenticationData(httpRequest, currentUri, fullUrl);
                } else {
                    // not authenticated
                    sendAuthRedirect(httpRequest, httpResponse);
                    return;
                }
            }
            if (isAuthDataExpired(httpRequest)) {
                updateAuthDataUsingRefreshToken(httpRequest);
            }
        } catch (AuthenticationException authException) {
            // something went wrong (like expiration or revocation of token)
            // we should invalidate AuthData stored in session and redirect to Authorization server
            removePrincipalFromSession(httpRequest);
            sendAuthRedirect(httpRequest, httpResponse);
            return;
        } catch (Throwable exc) {
            httpResponse.setStatus(500);
            request.setAttribute("error", exc.getMessage());
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }
    chain.doFilter(request, response);
}

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);
                    }//from w w  w .j a  v a  2  s . c  om

                }

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