Example usage for javax.servlet.http HttpServletRequest removeAttribute

List of usage examples for javax.servlet.http HttpServletRequest removeAttribute

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest removeAttribute.

Prototype

public void removeAttribute(String name);

Source Link

Document

Removes an attribute from this request.

Usage

From source file:org.pentaho.platform.web.http.filters.PentahoWebContextFilter.java

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

    String requestStr = httpRequest.getRequestURI();

    if (requestStr != null && requestStr.endsWith(WEB_CONTEXT_JS)
            && httpRequest.getAttribute(FILTER_APPLIED) == null) {
        httpRequest.setAttribute(FILTER_APPLIED, Boolean.TRUE);
        // split out a fully qualified url, guaranteed to have a trailing slash
        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
        String contextPath = requestContext.getContextPath();
        try {//from  ww  w.j a  va  2  s  .  c  om
            response.setContentType("text/javascript"); //$NON-NLS-1$
            OutputStream out = response.getOutputStream();
            out.write(initialCommentBytes);

            byte[] contextPathBytes = THREAD_LOCAL_CONTEXT_PATH.get();
            byte[] requireScriptBytes = THREAD_LOCAL_REQUIRE_SCRIPT.get();
            if (contextPathBytes == null) {
                String webContext = "var CONTEXT_PATH = '" + contextPath + "';\n\n"; //$NON-NLS-1$ //$NON-NLS-2$
                contextPathBytes = webContext.getBytes();
                THREAD_LOCAL_CONTEXT_PATH.set(contextPathBytes);
                if (requireScriptBytes == null) {
                    String requireJsLocation = "content/common-ui/resources/web/require.js";
                    String requireJsConfigLocation = "content/common-ui/resources/web/require-cfg.js";
                    String requireScript = "document.write(\"<script type='text/javascript' src='" + contextPath
                            + requireJsLocation + "'></scr\"+\"ipt>\");\n"
                            + "document.write(\"<script type=\'text/javascript\' src='" + contextPath
                            + requireJsConfigLocation + "'></scr\"+\"ipt>\");\n";
                    requireScriptBytes = requireScript.getBytes();
                    THREAD_LOCAL_REQUIRE_SCRIPT.set(requireScriptBytes);
                }
            }

            String basicAuthFlag = (String) httpRequest.getSession().getAttribute("BasicAuth");
            if (basicAuthFlag != null && basicAuthFlag.equals("true")) {
                out.write(("document.write(\"<script type='text/javascript' src='" + contextPath
                        + "js/postAuth.js'></scr\"+\"ipt>\");\n").getBytes("UTF-8"));
            }

            out.write(contextPathBytes);
            out.write(fullyQualifiedUrl.getBytes());
            out.write(serverProtocol.getBytes());
            // Compute the effective locale and set it in the global scope. Also provide it as a module if the RequireJs
            // system is available.
            Locale effectiveLocale = LocaleHelper.getLocale();
            if (!StringUtils.isEmpty(request.getParameter("locale"))) {
                effectiveLocale = new Locale(request.getParameter("locale"));
            }

            // setup the RequireJS config object for plugins to extend
            out.write(REQUIRE_JS_CFG_START);

            // Let all plugins contribute to the RequireJS config
            printResourcesForContext(REQUIRE_JS, out, httpRequest, false);

            out.write(requireScriptBytes);

            printSessionName(out);
            printLocale(effectiveLocale, out);
            printHomeFolder(out);
            printReservedChars(out);
            printReservedCharsDisplay(out);
            printReservedRegexPattern(out);

            boolean requireJsOnly = "true".equals(request.getParameter("requireJsOnly"));

            if (!requireJsOnly) {
                // print global resources defined in plugins
                printResourcesForContext(GLOBAL, out, httpRequest, false);

                // print out external-resources defined in plugins if a context has been passed in
                String contextName = request.getParameter(CONTEXT);
                boolean cssOnly = "true".equals(request.getParameter("cssOnly"));
                if (StringUtils.isNotEmpty(contextName)) {
                    printResourcesForContext(contextName, out, httpRequest, cssOnly);
                }
            }

            // Any subclass can add more information to webcontext.js
            addCustomInfo(out);

            out.close();
            return;
        } finally {
            httpRequest.removeAttribute(FILTER_APPLIED);
        }
    } else {
        chain.doFilter(httpRequest, httpResponse);
        return;
    }
}

From source file:com.concursive.connect.web.controller.hooks.SecurityHook.java

/**
 * Checks to see if a User session object exists, if not then the security
 * check fails./*from   w  w w .j av a2  s.  c  o m*/
 *
 * @param servlet  Description of the Parameter
 * @param request  Description of the Parameter
 * @param response Description of the Parameter
 * @return Description of the Return Value
 */
public String beginRequest(Servlet servlet, HttpServletRequest request, HttpServletResponse response) {
    LOG.debug("Security request made");
    ServletConfig config = servlet.getServletConfig();
    ServletContext context = config.getServletContext();
    // Application wide preferences
    ApplicationPrefs prefs = (ApplicationPrefs) context.getAttribute(Constants.APPLICATION_PREFS);
    // Get the intended action, if going to the login module, then let it proceed
    String s = request.getServletPath();
    int slash = s.lastIndexOf("/");
    s = s.substring(slash + 1);
    // If not setup then go to setup
    if (!s.startsWith("Setup") && !prefs.isConfigured()) {
        return "NotSetupError";
    }
    // External calls
    if (s.startsWith("Service")) {
        return null;
    }
    // Set the layout relevant to this request
    if ("text".equals(request.getParameter("out")) || "text".equals(request.getAttribute("out"))) {
        // do not use a layout, send the raw output
    } else if ("true".equals(request.getParameter(Constants.REQUEST_PARAM_POPUP))) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
    } else if ("true".equals(request.getParameter(Constants.REQUEST_PARAM_STYLE))) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
    } else {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, context.getAttribute(Constants.REQUEST_TEMPLATE));
    }
    // If going to Setup then allow
    if (s.startsWith("Setup")) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
        return null;
    }
    // If going to Upgrade then allow
    if (s.startsWith("Upgrade")) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
        return null;
    }
    // Detect mobile users and mobile formatting
    //    ClientType clientType = (ClientType) request.getSession().getAttribute(Constants.SESSION_CLIENT_TYPE);
    // @todo introduce when mobile is implemented
    //    if (clientType.getMobile()) {
    //      request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layoutMobile.jsp");
    //    }

    // URL forwarding for MVC requests (*.do, etc.)
    String requestedPath = (String) request.getAttribute("requestedURL");
    if (requestedPath == null && "GET".equals(request.getMethod())
            && request.getParameter("redirectTo") == null) {
        // Save the requestURI to be used downstream
        String contextPath = request.getContextPath();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        requestedPath = uri.substring(contextPath.length()) + (queryString == null ? "" : "?" + queryString);
        LOG.debug("Requested path: " + requestedPath);
        request.setAttribute("requestedURL", requestedPath);

        // It's important the user is using the correct URL for accessing content;
        // The portal has it's own redirect scheme, this is a general catch all
        if (!s.startsWith("Portal") && !uri.contains(".shtml") && prefs.has(ApplicationPrefs.WEB_DOMAIN_NAME)) {
            // Check to see if an old domain name is used
            PortalBean bean = new PortalBean(request);
            String expectedDomainName = prefs.get(ApplicationPrefs.WEB_DOMAIN_NAME);
            if (expectedDomainName != null && requestedPath != null && !"127.0.0.1".equals(bean.getServerName())
                    && !"127.0.0.1".equals(expectedDomainName) && !"localhost".equals(bean.getServerName())
                    && !"localhost".equals(expectedDomainName)
                    && !bean.getServerName().equals(expectedDomainName)
                    && !bean.getServerName().startsWith("10.") && !bean.getServerName().startsWith("172.")
                    && !bean.getServerName().startsWith("192.")) {
                if (uri != null && !uri.substring(1).equals(prefs.get("PORTAL.INDEX"))) {
                    String newUrl = URLFactory.createURL(prefs.getPrefs()) + requestedPath;
                    request.setAttribute("redirectTo", newUrl);
                    LOG.debug("redirectTo: " + newUrl);
                    request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
                    return "Redirect301";
                }
            }
        }
    }

    // Version check
    if (!s.startsWith("Login") && ApplicationVersion.isOutOfDate(prefs)) {
        return "UpgradeCheck";
    }
    // Get the user object from the Session Validation...
    if (sessionValidator == null) {
        sessionValidator = SessionValidatorFactory.getInstance()
                .getSessionValidator(servlet.getServletConfig().getServletContext(), request);
        LOG.debug("Found sessionValidator? " + (sessionValidator != null));
    }
    // Check cookie for user's previous location info
    SearchBean searchBean = (SearchBean) request.getSession().getAttribute(Constants.SESSION_SEARCH_BEAN);
    if (searchBean == null) {
        String searchLocation = CookieUtils.getCookieValue(request, Constants.COOKIE_USER_SEARCH_LOCATION);
        if (searchLocation != null) {
            LOG.debug("Setting search location from cookie: " + searchLocation);
            searchBean = new SearchBean();
            searchBean.setLocation(searchLocation);
            request.getSession().setAttribute(Constants.SESSION_SEARCH_BEAN, searchBean);
        }
    }
    // Continue with session creation...
    User userSession = sessionValidator.validateSession(context, request, response);
    ConnectionElement ceSession = (ConnectionElement) request.getSession()
            .getAttribute(Constants.SESSION_CONNECTION_ELEMENT);
    // The user is going to the portal so get them guest credentials if they need them
    if ("true".equals(prefs.get("PORTAL")) || s.startsWith("Register") || s.startsWith("ResetPassword")
            || s.startsWith("LoginAccept") || s.startsWith("LoginReject") || s.startsWith("Search")
            || s.startsWith("ContactUs")) {
        if (userSession == null || ceSession == null) {
            // Allow portal mode to create a default session with guest capabilities
            userSession = UserUtils.createGuestUser();
            request.getSession().setAttribute(Constants.SESSION_USER, userSession);
            // Give them a connection element
            ceSession = new ConnectionElement();
            ceSession.setDriver(prefs.get("SITE.DRIVER"));
            ceSession.setUrl(prefs.get("SITE.URL"));
            ceSession.setUsername(prefs.get("SITE.USER"));
            ceSession.setPassword(prefs.get("SITE.PASSWORD"));
            request.getSession().setAttribute(Constants.SESSION_CONNECTION_ELEMENT, ceSession);
        }
        // Make sure SSL is being used for this connection
        if (userSession.getId() > 0 && "true".equals(prefs.get("SSL"))
                && !"https".equals(request.getScheme())) {
            LOG.info("Redirecting to..." + requestedPath);
            request.setAttribute("redirectTo",
                    "https://" + request.getServerName() + request.getContextPath() + requestedPath);
            request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
            return "Redirect301";
        }
        // Generate global items
        Connection db = null;
        try {
            db = getConnection(context, request);
            // TODO: Implement cache since every hit needs this list
            if (db != null) {
                // Load the project languages
                WebSiteLanguageList webSiteLanguageList = new WebSiteLanguageList();
                webSiteLanguageList.setEnabled(Constants.TRUE);
                webSiteLanguageList.buildList(db);
                // If an admin of a language, enable it...
                webSiteLanguageList.add(userSession.getWebSiteLanguageList());
                request.setAttribute("webSiteLanguageList", webSiteLanguageList);

                // Load the menu list
                ProjectList menu = new ProjectList();
                PagedListInfo menuListInfo = new PagedListInfo();
                menuListInfo.setColumnToSortBy("p.portal_default desc, p.level asc, p.title asc");
                menuListInfo.setItemsPerPage(-1);
                menu.setPagedListInfo(menuListInfo);
                menu.setIncludeGuestProjects(false);
                menu.setPortalState(Constants.TRUE);
                menu.setOpenProjectsOnly(true);
                menu.setApprovedOnly(true);
                menu.setBuildLink(true);
                menu.setLanguageId(webSiteLanguageList.getLanguageId(request));
                menu.buildList(db);
                request.setAttribute("menuList", menu);

                // Load the main profile to use throughout
                Project mainProfile = ProjectUtils.loadProject(prefs.get("MAIN_PROFILE"));
                request.setAttribute(Constants.REQUEST_MAIN_PROFILE, mainProfile);

                // Load the project categories for search and tab menus
                ProjectCategoryList categoryList = new ProjectCategoryList();
                categoryList.setEnabled(Constants.TRUE);
                categoryList.setTopLevelOnly(true);
                categoryList.buildList(db);
                request.setAttribute(Constants.REQUEST_TAB_CATEGORY_LIST, categoryList);

                // Determine the tab that needs to be highlighted
                int chosenTabId = -1;
                if (requestedPath != null) {
                    String chosenCategory = null;
                    String chosenTab = null;
                    if (requestedPath.length() > 0) {
                        chosenTab = requestedPath.substring(1);
                    }
                    LOG.debug("chosenTab? " + chosenTab);
                    if (chosenTab == null || "".equals(chosenTab)) {
                        LOG.debug("Setting tab to Home");
                        chosenTab = "home.shtml";
                    } else {
                        boolean foundChosenTab = false;
                        for (ProjectCategory projectCategory : categoryList) {
                            String categoryName = projectCategory.getDescription();
                            String normalizedCategoryTab = projectCategory.getNormalizedCategoryName()
                                    .concat(".shtml");
                            if (chosenTab.startsWith(normalizedCategoryTab)) {
                                foundChosenTab = true;
                                chosenCategory = categoryName;
                                chosenTabId = projectCategory.getId();
                                LOG.debug("found: " + chosenCategory);
                            }
                        }
                        if (!foundChosenTab) {
                            LOG.debug("No tab to highlight");
                            chosenTab = "none";
                        }
                    }
                    request.setAttribute("chosenTab", chosenTab);
                    request.setAttribute("chosenCategory", chosenCategory);
                }

                // Go through the tabs and remove the ones the user shouldn't see, also check permission
                if (!userSession.isLoggedIn()) {
                    boolean allowed = true;
                    Iterator i = categoryList.iterator();
                    while (i.hasNext()) {
                        ProjectCategory projectCategory = (ProjectCategory) i.next();
                        if (projectCategory.getSensitive()) {
                            if (chosenTabId == projectCategory.getId()) {
                                allowed = false;
                            }
                            i.remove();
                        }
                    }
                    if (!allowed) {
                        // Redirect to the login, perhaps the page would exist then
                        String newUrl = URLFactory.createURL(prefs.getPrefs()) + "/login?redirectTo="
                                + requestedPath;
                        request.setAttribute("redirectTo", newUrl);
                        LOG.debug("redirectTo: " + newUrl);
                        request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
                        return "Redirect301";
                    }
                }

                // Category drop-down for search
                HtmlSelect thisSelect = categoryList.getHtmlSelect();
                thisSelect.addItem(-1, prefs.get("TITLE"), 0);
                request.setAttribute(Constants.REQUEST_MENU_CATEGORY_LIST, thisSelect);
            }
        } catch (Exception e) {
            LOG.error("Global items error", e);
        } finally {
            this.freeConnection(context, db);
        }
    }

    // The user is not going to login, so verify login
    if (!s.startsWith("Login")) {
        if (userSession == null || ceSession == null) {
            // boot them off now
            LOG.debug("Security failed.");
            LoginBean failedSession = new LoginBean();
            failedSession.addError("actionError", "* Please login, your session has expired");
            failedSession.checkURL(request);
            request.setAttribute("LoginBean", failedSession);
            request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
            return "SecurityCheck";
        } else {
            // The user should have a valid login now, so let them proceed
            LOG.debug("Security passed: " + userSession.getId() + " (" + userSession.getUsername() + ")");
        }
    }
    // Generate user's global items
    if (userSession != null && userSession.getId() > 0) {
        Connection db = null;
        try {
            db = getConnection(context, request);
            // TODO: Implement cache since every hit needs this list
            if (db != null) {
                // A map for global alerts
                ArrayList<String> alerts = new ArrayList<String>();
                request.setAttribute(Constants.REQUEST_GLOBAL_ALERTS, alerts);

                // Check to see if the application is configured...
                if (userSession.getAccessAdmin()) {
                    String url = URLFactory.createURL(prefs.getPrefs());
                    if (url == null) {
                        alerts.add(
                                "The application configuration requires that the URL properties are updated.  Store <strong>"
                                        + RequestUtils.getAbsoluteServerUrl(request) + "</strong>? <a href=\""
                                        + RequestUtils.getAbsoluteServerUrl(request)
                                        + "/AdminUsage.do?command=StoreURL\">Save Changes</a>");
                    } else if (!url.equals(RequestUtils.getAbsoluteServerUrl(request))) {
                        alerts.add("There is a configuration mismatch -- expected: <strong>"
                                + RequestUtils.getAbsoluteServerUrl(request)
                                + "</strong> but the configuration has <strong><a href=\"" + url + "\">" + url
                                + "</a></strong> <a href=\"" + RequestUtils.getAbsoluteServerUrl(request)
                                + "/AdminUsage.do?command=StoreURL\">Save Changes</a>");
                    }
                }

                // Check the # of invitations
                int invitationCount = InvitationList.queryCount(db, userSession.getId(),
                        userSession.getProfileProjectId());
                request.setAttribute(Constants.REQUEST_INVITATION_COUNT, String.valueOf(invitationCount));

                // Check the # of private messages
                int newMailCount = PrivateMessageList.queryUnreadCountForUser(db, userSession.getId());
                request.setAttribute(Constants.REQUEST_PRIVATE_MESSAGE_COUNT, String.valueOf(newMailCount));

                // NOTE: removed because not currently used
                // Check the number of what's new
                //          int whatsNewCount = ProjectUtils.queryWhatsNewCount(db, userSession.getId());
                //          request.setAttribute(Constants.REQUEST_WHATS_NEW_COUNT, String.valueOf(whatsNewCount));
                // Check the number of assignments
                //          int whatsAssignedCount = ProjectUtils.queryWhatsAssignedCount(db, userSession.getId());
                //          request.setAttribute(Constants.REQUEST_WHATS_ASSIGNED_COUNT, String.valueOf(whatsAssignedCount));
                //          int projectCount = ProjectUtils.queryMyProjectCount(db, userSession.getId());
                //          request.setAttribute(Constants.REQUEST_MY_PROJECT_COUNT, String.valueOf(projectCount));
            }
        } catch (Exception e) {
            LOG.error("User's global items error", e);
        } finally {
            this.freeConnection(context, db);
        }
    }
    return null;
}

From source file:org.sakaiproject.search.tool.ControllerServlet2.java

public void execute(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);

    VelocityContext vc = new VelocityContext();

    String sakaiHeader = (String) request.getAttribute("sakai.html.head");
    String toolPlacement = (String) request.getAttribute("sakai.tool.placement.id");
    String toolPlacementJs = toolPlacement.toString().replace('-', 'x');
    String skin = "default/"; // this could be changed in the future to
    // make search skin awaire

    vc.put("lang", (new ResourceLoader()).getLocale().toString());
    vc.put("skin", skin);
    vc.put("sakaiheader", sakaiHeader);
    vc.put("includeLatestJQuery", PortalUtils.includeLatestJQuery("Search"));
    vc.put("rlb", rlb);
    vc.put("currentSiteId", ToolManager.getCurrentPlacement().getContext());
    vc.put("sakai_tool_placement_id", toolPlacement);
    vc.put("sakai_tool_placement_id_js", toolPlacementJs);
    vc.put("serverurl", serverUrl);

    String targetURL = persistState(request);
    if (targetURL != null && targetURL.trim().length() > 0) {
        response.sendRedirect(targetURL);
        return;/*from w  w  w  . j  a v a 2s  .c  om*/
    }
    String template = null;
    if (TITLE_PANEL.equals(request.getParameter(PANEL))) {
        template = "title";

    } else {

        String path = request.getPathInfo();
        if (path == null || path.length() == 0) {
            path = "index";
        }
        if (path.startsWith("/")) {
            path = path.substring(1);

            // SAK-13408, SAK-16278 - Websphere must be told to look in a different directory for .vm files.
            // This fix forces the class to use the default directory and file when using WebSphere.
            ServerConfigurationService serverConfigurationService = (ServerConfigurationService) wac
                    .getBean(ServerConfigurationService.class.getName());
            if (serverConfigurationService == null) {
                throw new ServletException("Unable to get " + ServerConfigurationService.class.getName());
            }
            if ("websphere".equals(serverConfigurationService.getString("servlet.container"))) {
                // expecting path like: "tool/fe2bb974-dbd4-4a08-b75b-d69f3cdcacea" or
                //                      "tool/fe2bb974-dbd4-4a08-b75b-d69f3cdcacea/admin/index"
                if (path.indexOf("/") >= 0) {
                    path = path.substring(path.indexOf("/"));
                }
                if (path.startsWith("/")) {
                    path = path.substring(1);
                }
                if (path.indexOf("/") >= 0) {
                    path = path.substring(path.indexOf("/"));
                    if (path.startsWith("/")) {
                        path = path.substring(1);
                    }
                } else {
                    path = "index";
                }
            }
        }
        template = path;
    }
    log.debug("Path is " + template + " for " + request.getPathInfo());
    if ("sakai.gif".equals(template)) {
        try {
            searchBeanFactory.newSherlockSearchBean(request).sendIcon(response);
        } catch (PermissionException e) {
            log.warn("Failed to send gif ", e);
        }
        return;
    }
    try {
        vc.put("searchModel", searchBeanFactory.newSearchBean(request));
    } catch (PermissionException e1) {
        log.debug(e1);
    }
    try {
        SearchAdminBean searchAdminBean = searchBeanFactory.newSearchAdminBean(request);
        if (searchAdminBean.isRedirectRequired()) {
            response.sendRedirect(request.getRequestURL().toString());
            return;
        }
        vc.put("adminModel", searchBeanFactory.newSearchAdminBean(request));
    } catch (PermissionException e1) {
        log.debug(e1);
    }
    try {
        vc.put("sherlockModel", searchBeanFactory.newSherlockSearchBean(request));
    } catch (PermissionException e1) {
        log.debug(e1);
    }
    try {
        vc.put("openSearchModel", searchBeanFactory.newOpenSearchBean(request));
    } catch (PermissionException e1) {
        log.debug(e1);
    }
    try {

        String filePath = "/WEB-INF/vm/" + template + ".vm";
        String contentType = contentTypes.get(template);
        if (contentType == null) {
            contentType = "text/html";
        }
        String characterEncoding = characterEncodings.get(template);
        if (characterEncoding == null) {
            characterEncoding = "UTF-8";
        }

        response.setContentType(contentType);
        response.setCharacterEncoding(characterEncoding);
        vengine.mergeTemplate(filePath, vc, response.getWriter());

        request.removeAttribute(Tool.NATIVE_URL);
    } catch (Exception e) {
        throw new ServletException("Search Failed ", e);
    }
}

From source file:org.etudes.tool.melete.MeleteJsfTool.java

/**
 * Respond to requests./*from  w w  w  .  j a  va 2 s .com*/
 * 
 * @param req
 *        The servlet request.
 * @param res
 *        The servlet response.
 * @throws ServletException.
 * @throws IOException.
 */
protected void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // NOTE: this is a simple path dispatching, taking the path as the view id = jsp file name for the view,
    // with default used if no path and a path prefix as configured.
    // TODO: need to allow other sorts of dispatching, such as pulling out drill-down ids and making them
    // available to the JSF

    // build up the target that will be dispatched to
    String target = req.getPathInfo();

    // see if we have a resource request - i.e. a path with an extension, and one that is not the JSF_EXT
    if (isResourceRequest(target)) {
        // get a dispatcher to the path
        RequestDispatcher resourceDispatcher = getServletContext().getRequestDispatcher(target);
        if (resourceDispatcher != null) {
            resourceDispatcher.forward(req, res);
            return;
        }
    }

    if ("Title".equals(req.getParameter("panel"))) {
        // This allows only one Title JSF for each tool
        target = "/title.jsf";
    } else {
        ToolSession session = SessionManager.getCurrentToolSession();

        if (target == null || "/".equals(target)) {
            target = computeDefaultTarget();

            // make sure it's a valid path
            if (!target.startsWith("/")) {
                target = "/" + target;
            }

            // now that we've messed with the URL, send a redirect to make it official
            res.sendRedirect(Web.returnUrl(req, target));
            return;
        }

        // see if we want to change the specifically requested view
        String newTarget = redirectRequestedTarget(target);

        // make sure it's a valid path
        if (!newTarget.startsWith("/")) {
            newTarget = "/" + newTarget;
        }

        if (!newTarget.equals(target)) {
            // now that we've messed with the URL, send a redirect to make it official
            res.sendRedirect(Web.returnUrl(req, newTarget));
            return;
        }
        target = newTarget;

        // store this
        if (m_defaultToLastView) {
            String params = req.getQueryString();
            if (params != null) {
                session.setAttribute(LAST_VIEW_VISITED, target + "?" + params);
            } else {
                session.setAttribute(LAST_VIEW_VISITED, target);
            }
        }
    }

    // these URL paths have the module id encoded in the URL - remove it and place it in threadLocal
    if (target.startsWith("/view_module/") || target.startsWith("/edit_module/")) {
        String[] parts = StringUtil.split(target, "/");

        if (parts.length == 6) {
            String id = parts[2];
            ThreadLocalManager.set("MELETE_MODULE_ID", id);
            String returnBackUrl = "/portal/directtool/" + parts[4] + "/" + parts[5];
            ThreadLocalManager.set("MELETE_NAVIGATE_BACK", returnBackUrl);
            target = "/" + parts[1];
        }
    }

    // Add variable to autosave module and section changes
    if (target.startsWith("/edit_module")) {
        ThreadLocalManager.set("MELETE_SAVE_FROM", "editModule");
    } else if (target.startsWith("/add_module")) {
        ThreadLocalManager.set("MELETE_SAVE_FROM", "addModule");
    } else if (target.startsWith("/editmodulesections")) {
        ThreadLocalManager.set("MELETE_SAVE_FROM", "Section");
    } else if (target.startsWith("/list_auth_modules")) {
        ThreadLocalManager.set("MELETE_SAVE_FROM", "listAuth");
    } else if (target.startsWith("/author_preference")) {
        ThreadLocalManager.set("MELETE_SAVE_FROM", "authPref");
    }

    // add the configured folder root and extension (if missing)
    target = m_path + target;

    // add the default JSF extension (if we have no extension)
    int lastSlash = target.lastIndexOf("/");
    int lastDot = target.lastIndexOf(".");
    if (lastDot < 0 || lastDot < lastSlash) {
        target += JSF_EXT;
    }

    // set the information that can be removed from return URLs
    req.setAttribute(URL_PATH, m_path);
    req.setAttribute(URL_EXT, ".jsp");

    // set the sakai request object wrappers to provide the native, not Sakai set up, URL information
    // - this assures that the FacesServlet can dispatch to the proper view based on the path info
    req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL);

    // TODO: Should setting the HTTP headers be moved up to the portal level as well?
    res.setContentType("text/html; charset=UTF-8");
    res.setCharacterEncoding("UTF-8");
    res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L));
    res.addDateHeader("Last-Modified", System.currentTimeMillis());
    res.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    res.addHeader("Pragma", "no-cache");

    // dispatch to the target
    M_log.debug("dispatching path: " + req.getPathInfo() + " to: " + target + " context: "
            + getServletContext().getServletContextName());
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(target);
    dispatcher.forward(req, res);

    // restore the request object
    req.removeAttribute(Tool.NATIVE_URL);
    req.removeAttribute(URL_PATH);
    req.removeAttribute(URL_EXT);
}

From source file:org.structr.web.servlet.HtmlServlet.java

@Override
protected void doHead(final HttpServletRequest request, final HttpServletResponse response) {

    final Authenticator auth = getConfig().getAuthenticator();
    SecurityContext securityContext;/* w  ww. ja v  a2 s  .com*/
    List<Page> pages = null;
    boolean requestUriContainsUuids = false;
    final App app;

    try {
        String path = request.getPathInfo();

        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            securityContext = auth.initializeAndExamineRequest(request, response);
            tx.success();
        }

        app = StructrApp.getInstance(securityContext);

        try (final Tx tx = app.tx()) {

            // Ensure access mode is frontend
            securityContext.setAccessMode(AccessMode.Frontend);

            request.setCharacterEncoding("UTF-8");

            // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
            response.setCharacterEncoding("UTF-8");
            response.setContentLength(0);

            boolean dontCache = false;

            logger.log(Level.FINE, "Path info {0}", path);

            // don't continue on redirects
            if (response.getStatus() == 302) {

                tx.success();
                return;
            }

            final Principal user = securityContext.getUser(false);
            if (user != null) {

                // Don't cache if a user is logged in
                dontCache = true;

            }

            final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response);

            renderContext.setResourceProvider(config.getResourceProvider());

            final EditMode edit = renderContext.getEditMode(user);

            DOMNode rootElement = null;
            AbstractNode dataNode = null;

            String[] uriParts = PathHelper.getParts(path);
            if ((uriParts == null) || (uriParts.length == 0)) {

                // find a visible page
                rootElement = findIndexPage(securityContext, pages, edit);

                logger.log(Level.FINE, "No path supplied, trying to find index page");

            } else {

                if (rootElement == null) {

                    rootElement = findPage(securityContext, pages, path, edit);

                } else {
                    dontCache = true;
                }
            }

            if (rootElement == null) { // No page found

                // Look for a file
                File file = findFile(securityContext, request, path);
                if (file != null) {

                    //streamFile(securityContext, file, request, response, edit);
                    tx.success();
                    return;

                }

                // store remaining path parts in request
                Matcher matcher = threadLocalUUIDMatcher.get();

                for (int i = 0; i < uriParts.length; i++) {

                    request.setAttribute(uriParts[i], i);
                    matcher.reset(uriParts[i]);

                    // set to "true" if part matches UUID pattern
                    requestUriContainsUuids |= matcher.matches();

                }

                if (!requestUriContainsUuids) {

                    // Try to find a data node by name
                    dataNode = findFirstNodeByName(securityContext, request, path);

                } else {

                    dataNode = findNodeByUuid(securityContext, PathHelper.getName(path));

                }

                if (dataNode != null && !(dataNode instanceof Linkable)) {

                    // Last path part matches a data node
                    // Remove last path part and try again searching for a page
                    // clear possible entry points
                    request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY);

                    rootElement = findPage(securityContext, pages,
                            StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit);

                    renderContext.setDetailsDataObject(dataNode);

                    // Start rendering on data node
                    if (rootElement == null && dataNode instanceof DOMNode) {

                        rootElement = ((DOMNode) dataNode);

                    }

                }

            }

            // look for pages with HTTP Basic Authentication (must be done as superuser)
            if (rootElement == null) {

                final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path);

                switch (authResult.authState()) {

                // Element with Basic Auth found and authentication succeeded
                case Authenticated:
                    final Linkable result = authResult.getRootElement();
                    if (result instanceof Page) {

                        rootElement = (DOMNode) result;
                        renderContext.pushSecurityContext(authResult.getSecurityContext());

                    } else if (result instanceof File) {

                        //streamFile(authResult.getSecurityContext(), (File)result, request, response, EditMode.NONE);
                        tx.success();
                        return;

                    }
                    break;

                // Page with Basic Auth found but not yet authenticated
                case MustAuthenticate:
                    return;

                // no Basic Auth for given path, go on
                case NoBasicAuth:
                    break;
                }
            }

            // Still nothing found, do error handling
            if (rootElement == null) {

                // Check if security context has set an 401 status
                if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {

                    try {

                        UiAuthenticator.writeUnauthorized(response);

                    } catch (IllegalStateException ise) {
                    }

                } else {

                    rootElement = notFound(response, securityContext);

                }

            }

            if (rootElement == null) {

                // no content
                response.setContentLength(0);
                response.getOutputStream().close();

                tx.success();
                return;
            }

            // check dont cache flag on page (if root element is a page)
            // but don't modify true to false
            dontCache |= rootElement.getProperty(Page.dontCache);

            if (EditMode.WIDGET.equals(edit) || dontCache) {

                setNoCacheHeaders(response);

            }

            if (!securityContext.isVisible(rootElement)) {

                rootElement = notFound(response, securityContext);
                if (rootElement == null) {

                    tx.success();
                    return;
                }

            }

            if (securityContext.isVisible(rootElement)) {

                if (!EditMode.WIDGET.equals(edit) && !dontCache
                        && notModifiedSince(request, response, rootElement, dontCache)) {

                    response.getOutputStream().close();

                } else {

                    // prepare response
                    response.setCharacterEncoding("UTF-8");

                    String contentType = rootElement.getProperty(Page.contentType);

                    if (contentType == null) {

                        // Default
                        contentType = "text/html;charset=UTF-8";
                    }

                    if (contentType.equals("text/html")) {
                        contentType = contentType.concat(";charset=UTF-8");
                    }

                    response.setContentType(contentType);

                    setCustomResponseHeaders(response);

                    response.getOutputStream().close();
                }

            } else {

                notFound(response, securityContext);

                response.getOutputStream().close();
            }

            tx.success();

        } catch (Throwable fex) {
            fex.printStackTrace();
            logger.log(Level.SEVERE, "Exception while processing request", fex);
        }

    } catch (FrameworkException t) {

        t.printStackTrace();
        logger.log(Level.SEVERE, "Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}

From source file:org.dspace.app.webui.servlet.admin.EditCommunitiesServlet.java

protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, AuthorizeException {
    // First, see if we have a multipart request (uploading a logo)
    String contentType = request.getContentType();

    if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) {
        // This is a multipart request, so it's a file upload
        processUploadLogo(context, request, response);

        return;//from w ww .  ja v a  2s .co  m
    }

    /*
     * Respond to submitted forms. Each form includes an "action" parameter
     * indicating what needs to be done (from the constants above.)
     */
    int action = UIUtil.getIntParameter(request, "action");

    /*
     * Most of the forms supply one or more of these values. Since we just
     * get null if we try and find something with ID -1, we'll just try and
     * find both here to save hassle later on
     */
    Community community = Community.find(context, UIUtil.getIntParameter(request, "community_id"));
    Community parentCommunity = Community.find(context, UIUtil.getIntParameter(request, "parent_community_id"));
    Collection collection = Collection.find(context, UIUtil.getIntParameter(request, "collection_id"));

    // Just about every JSP will need the values we received
    request.setAttribute("community", community);
    request.setAttribute("parent", parentCommunity);
    request.setAttribute("collection", collection);

    /*
     * First we check for a "cancel" button - if it's been pressed, we
     * simply return to the main control page
     */
    if (request.getParameter("submit_cancel") != null) {
        showControls(context, request, response);

        return;
    }

    // Now proceed according to "action" parameter
    switch (action) {
    case START_EDIT_COMMUNITY:
        storeAuthorizeAttributeCommunityEdit(context, request, community);

        // Display the relevant "edit community" page
        JSPManager.showJSP(request, response, "/tools/edit-community.jsp");

        break;

    case START_DELETE_COMMUNITY:

        // Show "confirm delete" page
        JSPManager.showJSP(request, response, "/tools/confirm-delete-community.jsp");

        break;

    case START_CREATE_COMMUNITY:
        // no authorize attribute will be given to the jsp so a "clean" creation form
        // will be always supplied, advanced setting on policies and admin group creation
        // will be possible after to have completed the community creation

        // Display edit community page with empty fields + create button
        JSPManager.showJSP(request, response, "/tools/edit-community.jsp");

        break;

    case START_EDIT_COLLECTION:

        HarvestedCollection hc = HarvestedCollection.find(context,
                UIUtil.getIntParameter(request, "collection_id"));
        request.setAttribute("harvestInstance", hc);

        storeAuthorizeAttributeCollectionEdit(context, request, collection);

        // Display the relevant "edit collection" page
        JSPManager.showJSP(request, response, "/tools/edit-collection.jsp");

        break;

    case START_DELETE_COLLECTION:

        // Show "confirm delete" page
        JSPManager.showJSP(request, response, "/tools/confirm-delete-collection.jsp");

        break;

    case START_CREATE_COLLECTION:

        // Forward to collection creation wizard
        response.sendRedirect(response.encodeRedirectURL(
                request.getContextPath() + "/tools/collection-wizard?community_id=" + community.getID()));

        break;

    case CONFIRM_EDIT_COMMUNITY:

        // Edit or creation of a community confirmed
        processConfirmEditCommunity(context, request, response, community);

        break;

    case CONFIRM_DELETE_COMMUNITY:

        // remember the parent community, if any
        Community parent = community.getParentCommunity();

        // Delete the community
        community.delete();

        // if community was top-level, redirect to community-list page
        if (parent == null) {
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/community-list"));
        } else
        // redirect to parent community page
        {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/handle/" + parent.getHandle()));
        }

        // Show main control page
        //showControls(context, request, response);
        // Commit changes to DB
        context.complete();

        break;

    case CONFIRM_EDIT_COLLECTION:

        // Edit or creation of a collection confirmed
        processConfirmEditCollection(context, request, response, community, collection);

        break;

    case CONFIRM_DELETE_COLLECTION:

        // Delete the collection
        community.removeCollection(collection);
        // remove the collection object from the request, so that the user
        // will be redirected on the community home page
        request.removeAttribute("collection");
        // Show main control page
        showControls(context, request, response);

        // Commit changes to DB
        context.complete();

        break;

    default:

        // Erm... weird action value received.
        log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request)));
        JSPManager.showIntegrityError(request, response);
    }
}

From source file:org.apache.nifi.web.ContentViewerController.java

/**
 * Gets the content and defers to registered viewers to generate the markup.
 *
 * @param request servlet request/*from   w  w w. java  2s .  c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    // specify the charset in a response header
    response.addHeader("Content-Type", "text/html; charset=UTF-8");

    // get the content
    final ServletContext servletContext = request.getServletContext();
    final ContentAccess contentAccess = (ContentAccess) servletContext.getAttribute("nifi-content-access");

    final ContentRequestContext contentRequest;
    try {
        contentRequest = getContentRequest(request);
    } catch (final Exception e) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Unable to interpret content request.");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    if (contentRequest.getDataUri() == null) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "The data reference must be specified.");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // get the content
    final DownloadableContent downloadableContent;
    try {
        downloadableContent = contentAccess.getContent(contentRequest);
    } catch (final ResourceNotFoundException rnfe) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Unable to find the specified content");

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    } catch (final AccessDeniedException ade) {
        request.setAttribute("title", "Access Denied");
        request.setAttribute("messages",
                "Unable to approve access to the specified content: " + ade.getMessage());

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    } catch (final Exception e) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "An unexpected error has occurred: " + e.getMessage());

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // determine how we want to view the data
    String mode = request.getParameter("mode");

    // if the name isn't set, use original
    if (mode == null) {
        mode = DisplayMode.Original.name();
    }

    // determine the display mode
    final DisplayMode displayMode;
    try {
        displayMode = DisplayMode.valueOf(mode);
    } catch (final IllegalArgumentException iae) {
        request.setAttribute("title", "Error");
        request.setAttribute("messages", "Invalid display mode: " + mode);

        // forward to the error page
        final ServletContext viewerContext = servletContext.getContext("/nifi");
        viewerContext.getRequestDispatcher("/message").forward(request, response);
        return;
    }

    // buffer the content to support resetting in case we need to detect the content type or char encoding
    try (final BufferedInputStream bis = new BufferedInputStream(downloadableContent.getContent());) {
        final String mimeType;
        final String normalizedMimeType;

        // when standalone and we don't know the type is null as we were able to directly access the content bypassing the rest endpoint,
        // when clustered and we don't know the type set to octet stream since the content was retrieved from the node's rest endpoint
        if (downloadableContent.getType() == null || StringUtils
                .startsWithIgnoreCase(downloadableContent.getType(), MediaType.OCTET_STREAM.toString())) {
            // attempt to detect the content stream if we don't know what it is ()
            final DefaultDetector detector = new DefaultDetector();

            // create the stream for tika to process, buffered to support reseting
            final TikaInputStream tikaStream = TikaInputStream.get(bis);

            // provide a hint based on the filename
            final Metadata metadata = new Metadata();
            metadata.set(Metadata.RESOURCE_NAME_KEY, downloadableContent.getFilename());

            // Get mime type
            final MediaType mediatype = detector.detect(tikaStream, metadata);
            mimeType = mediatype.toString();
        } else {
            mimeType = downloadableContent.getType();
        }

        // Extract only mime type and subtype from content type (anything after the first ; are parameters)
        // Lowercase so subsequent code does not need to implement case insensitivity
        normalizedMimeType = mimeType.split(";", 2)[0].toLowerCase();

        // add attributes needed for the header
        request.setAttribute("filename", downloadableContent.getFilename());
        request.setAttribute("contentType", mimeType);

        // generate the header
        request.getRequestDispatcher("/WEB-INF/jsp/header.jsp").include(request, response);

        // remove the attributes needed for the header
        request.removeAttribute("filename");
        request.removeAttribute("contentType");

        // generate the markup for the content based on the display mode
        if (DisplayMode.Hex.equals(displayMode)) {
            final byte[] buffer = new byte[BUFFER_LENGTH];
            final int read = StreamUtils.fillBuffer(bis, buffer, false);

            // trim the byte array if necessary
            byte[] bytes = buffer;
            if (read != buffer.length) {
                bytes = new byte[read];
                System.arraycopy(buffer, 0, bytes, 0, read);
            }

            // convert bytes into the base 64 bytes
            final String base64 = Base64.encodeBase64String(bytes);

            // defer to the jsp
            request.setAttribute("content", base64);
            request.getRequestDispatcher("/WEB-INF/jsp/hexview.jsp").include(request, response);
        } else {
            // lookup a viewer for the content
            final String contentViewerUri = servletContext.getInitParameter(normalizedMimeType);

            // handle no viewer for content type
            if (contentViewerUri == null) {
                request.getRequestDispatcher("/WEB-INF/jsp/no-viewer.jsp").include(request, response);
            } else {
                // create a request attribute for accessing the content
                request.setAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE, new ViewableContent() {
                    @Override
                    public InputStream getContentStream() {
                        return bis;
                    }

                    @Override
                    public String getContent() throws IOException {
                        // detect the charset
                        final CharsetDetector detector = new CharsetDetector();
                        detector.setText(bis);
                        detector.enableInputFilter(true);
                        final CharsetMatch match = detector.detect();

                        // ensure we were able to detect the charset
                        if (match == null) {
                            throw new IOException("Unable to detect character encoding.");
                        }

                        // convert the stream using the detected charset
                        return IOUtils.toString(bis, match.getName());
                    }

                    @Override
                    public ViewableContent.DisplayMode getDisplayMode() {
                        return displayMode;
                    }

                    @Override
                    public String getFileName() {
                        return downloadableContent.getFilename();
                    }

                    @Override
                    public String getContentType() {
                        return normalizedMimeType;
                    }

                    @Override
                    public String getRawContentType() {
                        return mimeType;
                    }
                });

                try {
                    // generate the content
                    final ServletContext viewerContext = servletContext.getContext(contentViewerUri);
                    viewerContext.getRequestDispatcher("/view-content").include(request, response);
                } catch (final Exception e) {
                    String message = e.getMessage() != null ? e.getMessage() : e.toString();
                    message = "Unable to generate view of data: " + message;

                    // log the error
                    logger.error(message);
                    if (logger.isDebugEnabled()) {
                        logger.error(StringUtils.EMPTY, e);
                    }

                    // populate the request attributes
                    request.setAttribute("title", "Error");
                    request.setAttribute("messages", message);

                    // forward to the error page
                    final ServletContext viewerContext = servletContext.getContext("/nifi");
                    viewerContext.getRequestDispatcher("/message").forward(request, response);
                    return;
                }

                // remove the request attribute
                request.removeAttribute(ViewableContent.CONTENT_REQUEST_ATTRIBUTE);
            }
        }

        // generate footer
        request.getRequestDispatcher("/WEB-INF/jsp/footer.jsp").include(request, response);
    }
}

From source file:org.structr.web.servlet.HtmlServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) {

    final Authenticator auth = getConfig().getAuthenticator();
    List<Page> pages = null;
    boolean requestUriContainsUuids = false;

    SecurityContext securityContext;/*  www .  j  a  v  a  2s . c om*/
    final App app;

    try {
        final String path = request.getPathInfo();

        // check for registration (has its own tx because of write access
        if (checkRegistration(auth, request, response, path)) {

            return;
        }

        // check for registration (has its own tx because of write access
        if (checkResetPassword(auth, request, response, path)) {

            return;
        }

        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            securityContext = auth.initializeAndExamineRequest(request, response);
            tx.success();
        }

        app = StructrApp.getInstance(securityContext);

        try (final Tx tx = app.tx()) {

            // Ensure access mode is frontend
            securityContext.setAccessMode(AccessMode.Frontend);

            request.setCharacterEncoding("UTF-8");

            // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
            response.setCharacterEncoding("UTF-8");

            boolean dontCache = false;

            logger.log(Level.FINE, "Path info {0}", path);

            // don't continue on redirects
            if (response.getStatus() == 302) {

                tx.success();
                return;
            }

            final Principal user = securityContext.getUser(false);
            if (user != null) {

                // Don't cache if a user is logged in
                dontCache = true;

            }

            final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response);

            renderContext.setResourceProvider(config.getResourceProvider());

            final EditMode edit = renderContext.getEditMode(user);

            DOMNode rootElement = null;
            AbstractNode dataNode = null;

            final String[] uriParts = PathHelper.getParts(path);
            if ((uriParts == null) || (uriParts.length == 0)) {

                // find a visible page
                rootElement = findIndexPage(securityContext, pages, edit);

                logger.log(Level.FINE, "No path supplied, trying to find index page");

            } else {

                if (rootElement == null) {

                    rootElement = findPage(securityContext, pages, path, edit);

                } else {
                    dontCache = true;
                }
            }

            if (rootElement == null) { // No page found

                // Look for a file
                final File file = findFile(securityContext, request, path);
                if (file != null) {

                    streamFile(securityContext, file, request, response, edit);
                    tx.success();
                    return;

                }

                // store remaining path parts in request
                final Matcher matcher = threadLocalUUIDMatcher.get();

                for (int i = 0; i < uriParts.length; i++) {

                    request.setAttribute(uriParts[i], i);
                    matcher.reset(uriParts[i]);

                    // set to "true" if part matches UUID pattern
                    requestUriContainsUuids |= matcher.matches();

                }

                if (!requestUriContainsUuids) {

                    // Try to find a data node by name
                    dataNode = findFirstNodeByName(securityContext, request, path);

                } else {

                    dataNode = findNodeByUuid(securityContext, PathHelper.getName(path));

                }

                //if (dataNode != null && !(dataNode instanceof Linkable)) {
                if (dataNode != null) {

                    // Last path part matches a data node
                    // Remove last path part and try again searching for a page
                    // clear possible entry points
                    request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY);

                    rootElement = findPage(securityContext, pages,
                            StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit);

                    renderContext.setDetailsDataObject(dataNode);

                    // Start rendering on data node
                    if (rootElement == null && dataNode instanceof DOMNode) {

                        rootElement = ((DOMNode) dataNode);
                    }
                }
            }

            // look for pages with HTTP Basic Authentication (must be done as superuser)
            if (rootElement == null) {

                final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path);

                switch (authResult.authState()) {

                // Element with Basic Auth found and authentication succeeded
                case Authenticated:
                    final Linkable result = authResult.getRootElement();
                    if (result instanceof Page) {

                        rootElement = (DOMNode) result;
                        securityContext = authResult.getSecurityContext();
                        renderContext.pushSecurityContext(securityContext);

                    } else if (result instanceof File) {

                        streamFile(authResult.getSecurityContext(), (File) result, request, response,
                                EditMode.NONE);
                        tx.success();
                        return;

                    }
                    break;

                // Page with Basic Auth found but not yet authenticated
                case MustAuthenticate:
                    tx.success();
                    return;

                // no Basic Auth for given path, go on
                case NoBasicAuth:
                    break;
                }

            }

            // Still nothing found, do error handling
            if (rootElement == null) {
                rootElement = notFound(response, securityContext);
            }

            if (rootElement == null) {
                tx.success();
                return;
            }

            // check dont cache flag on page (if root element is a page)
            // but don't modify true to false
            dontCache |= rootElement.getProperty(Page.dontCache);

            if (EditMode.WIDGET.equals(edit) || dontCache) {

                setNoCacheHeaders(response);

            }

            if (!securityContext.isVisible(rootElement)) {

                rootElement = notFound(response, securityContext);
                if (rootElement == null) {

                    tx.success();
                    return;
                }

            } else {

                if (!EditMode.WIDGET.equals(edit) && !dontCache
                        && notModifiedSince(request, response, rootElement, dontCache)) {

                    ServletOutputStream out = response.getOutputStream();
                    out.flush();
                    //response.flushBuffer();
                    out.close();

                } else {

                    // prepare response
                    response.setCharacterEncoding("UTF-8");

                    String contentType = rootElement.getProperty(Page.contentType);

                    if (contentType == null) {

                        // Default
                        contentType = "text/html;charset=UTF-8";
                    }

                    if (contentType.equals("text/html")) {
                        contentType = contentType.concat(";charset=UTF-8");
                    }

                    response.setContentType(contentType);

                    setCustomResponseHeaders(response);

                    final boolean createsRawData = rootElement.getProperty(Page.pageCreatesRawData);

                    // async or not?
                    if (isAsync && !createsRawData) {

                        final AsyncContext async = request.startAsync();
                        final ServletOutputStream out = async.getResponse().getOutputStream();
                        final AtomicBoolean finished = new AtomicBoolean(false);
                        final DOMNode rootNode = rootElement;

                        threadPool.submit(new Runnable() {

                            @Override
                            public void run() {

                                try (final Tx tx = app.tx()) {

                                    //final long start = System.currentTimeMillis();
                                    // render
                                    rootNode.render(renderContext, 0);
                                    finished.set(true);

                                    //final long end = System.currentTimeMillis();
                                    //System.out.println("Done in " + (end-start) + " ms");
                                    tx.success();

                                } catch (Throwable t) {
                                    t.printStackTrace();
                                    final String errorMsg = t.getMessage();
                                    try {
                                        //response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                                        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                                errorMsg);
                                        finished.set(true);
                                    } catch (IOException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                            }

                        });

                        // start output write listener
                        out.setWriteListener(new WriteListener() {

                            @Override
                            public void onWritePossible() throws IOException {

                                try {

                                    final Queue<String> queue = renderContext.getBuffer().getQueue();
                                    while (out.isReady()) {

                                        String buffer = null;

                                        synchronized (queue) {
                                            buffer = queue.poll();
                                        }

                                        if (buffer != null) {

                                            out.print(buffer);

                                        } else {

                                            if (finished.get()) {

                                                async.complete();
                                                response.setStatus(HttpServletResponse.SC_OK);

                                                // prevent this block from being called again
                                                break;
                                            }

                                            Thread.sleep(1);
                                        }
                                    }

                                } catch (Throwable t) {
                                    t.printStackTrace();
                                }
                            }

                            @Override
                            public void onError(Throwable t) {
                                t.printStackTrace();
                            }
                        });

                    } else {

                        final StringRenderBuffer buffer = new StringRenderBuffer();
                        renderContext.setBuffer(buffer);

                        // render
                        rootElement.render(renderContext, 0);

                        try {

                            response.getOutputStream().write(buffer.getBuffer().toString().getBytes("utf-8"));
                            response.getOutputStream().flush();
                            response.getOutputStream().close();

                        } catch (IOException ioex) {
                            ioex.printStackTrace();
                        }
                    }
                }
            }

            tx.success();

        } catch (FrameworkException fex) {
            fex.printStackTrace();
            logger.log(Level.SEVERE, "Exception while processing request", fex);
        }

    } catch (IOException | FrameworkException t) {

        t.printStackTrace();
        logger.log(Level.SEVERE, "Exception while processing request", t);
        UiAuthenticator.writeInternalServerError(response);
    }
}

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

/**
 * Handles the generation of the page body using the assigned page skin
 *
 * @param writer writer object to write the output to
 * @param nc     current navigation context
 *///from ww  w.  j  av  a  2  s. c o m
public void handlePageBody(Writer writer, NavigationContext nc) throws ServletException, IOException {
    // see if dynamic commands should be allowed
    HttpServletRequest request = nc.getHttpRequest();
    String panelEditorCommandSpec = request
            .getParameter(PanelEditorCommand.PANEL_EDITOR_COMMAND_REQUEST_PARAM_NAME);
    if (panelEditorCommandSpec != null && getFlags().flagIsSet(Flags.ALLOW_PANEL_EDITING)) {
        PanelEditorCommand command = new PanelEditorCommand();
        command.setParameters(panelEditorCommandSpec);
        Object panelEditorSource = null;
        // verify that this command is configured to be in this pae
        if (!getFlags().flagIsSet(Flags.VALIDATE_PANEL_EDITOR_IN_PAGE)
                || verifyPanelEditorInPage(nc, command)) {
            try {
                command.handleCommand(writer, nc, false);
            } catch (CommandException e) {
                getLog().error("Command error in body", e);
                throw new ServletException(e);
            }
            return;
        } else {
            getLog().error("Request to execute a panel editor '" + command.getPanelEditorName()
                    + "' that does not exist in page.");
        }
    }

    if (getFlags().flagIsSet(Flags.ALLOW_PAGE_CMD_PARAM)) {
        String commandSpec = request.getParameter(AbstractHttpServletCommand.PAGE_COMMAND_REQUEST_PARAM_NAME);
        if (commandSpec != null) {
            HttpServletCommand command = (HttpServletCommand) Commands.getInstance().getCommand(commandSpec);
            try {
                command.handleCommand(writer, nc, false);
            } catch (CommandException e) {
                getLog().error("Command error in body", e);
                throw new ServletException(e);
            }
            return;
        }
    }

    switch (getBodyType().getValueIndex()) {
    case NavigationPageBodyType.NONE:
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName() + " class but has no body.");
        break;

    case NavigationPageBodyType.OVERRIDE:
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName()
                + " class and is set as override class but does not override handlePageBody().");
        break;

    case NavigationPageBodyType.CUSTOM_HANDLER:
        for (int i = 0; i < customHandlers.size(); i++)
            ((NavigationPageBodyHandler) customHandlers.get(i)).handleNavigationPageBody(this, writer, nc);
        break;

    case NavigationPageBodyType.COMMAND:
        ValueSource commandExpr = getCommandExpr();
        if (commandExpr != null) {
            String commandText = commandExpr.getTextValue(nc);
            if (commandText != null) {
                try {
                    HttpServletCommand httpCommand = (HttpServletCommand) Commands.getInstance()
                            .getCommand(commandText);
                    httpCommand.handleCommand(writer, nc, false);
                    break;
                } catch (Exception e) {
                    getLog().error("Command error in " + this.getClass().getName(), e);
                    throw new ServletException(e);
                }
            }
        }

        // if we get to here, we don't have an expression or the expression returned null so see if we have static
        // command supplied
        try {
            ((HttpServletCommand) getCommand()).handleCommand(writer, nc, false);
        } catch (CommandException e) {
            getLog().error("Command error in body", e);
            throw new ServletException(e);
        }
        break;

    case NavigationPageBodyType.PANEL:
        getBodyPanel().render(writer, nc, nc.getActiveTheme(), HtmlPanel.RENDERFLAGS_DEFAULT);
        break;

    case NavigationPageBodyType.TEMPLATE:
        getBodyTemplate().process(writer, nc, createDefaultBodyTemplateVars(nc));
        break;

    case NavigationPageBodyType.FORWARD:
        // this should never happen -- forwards should never get to this point but we'll add a sanity check
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName()
                + " class and the body type is set to FORWARD but forwarding should happen before any response is committed.");
        break;

    case NavigationPageBodyType.INCLUDE: {
        String includeUrl = getInclude().getTextValue(nc);
        RequestDispatcher rd = request.getRequestDispatcher(includeUrl);
        ServletResponse response = nc.getResponse();
        if (writer != response.getWriter())
            response = new AlternateOutputDestServletResponse(writer, response);
        request.setAttribute(REQATTRNAME_NAVIGATION_CONTEXT, nc);
        rd.include(request, response);
        request.removeAttribute(REQATTRNAME_NAVIGATION_CONTEXT);
    }
        break;

    default:
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName() + " but doesn't know how to handle body type "
                + getBodyType().getValueIndex() + ".");
    }
}