Example usage for javax.servlet.http HttpServletResponse addDateHeader

List of usage examples for javax.servlet.http HttpServletResponse addDateHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse addDateHeader.

Prototype

public void addDateHeader(String name, long date);

Source Link

Document

Adds a response header with the given name and date-value.

Usage

From source file:org.sakaiproject.portal.charon.CharonPortal.java

protected PrintWriter startResponse(HttpServletResponse res, String title, String skin, boolean top)
        throws IOException {
    // headers/*from  w  ww .  j  ava2 s.c  o m*/
    res.setContentType("text/html; charset=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");

    // get the writer
    PrintWriter out = res.getWriter();

    // form the head
    out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
            + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
            + "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">" + "  <head>"
            + "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");

    // pick the one full portal skin
    if (skin == null) {
        skin = ServerConfigurationService.getString("skin.default");
    }
    String skinRepo = ServerConfigurationService.getString("skin.repo");

    out.println("    <link href=\"" + skinRepo + "/" + skin
            + "/portal.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />");
    out.println("    <meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />" + "    <title>"
            + Web.escapeHtml(title) + "</title>" + "    <script type=\"text/javascript\" src=\""
            + getScriptPath() + "headscripts.js\"></script>" + "  </head>");

    // start the body
    out.println("<body class=\"portalBody\">");

    // if top, mark this as the portal window
    if (top) {
        out.println("<script type=\"text/javascript\">");
        out.println("var sakaiPortalWindow = \"\";");
        out.println("</script>");
    }

    return out;
}

From source file:org.sakaiproject.portal.charon.handlers.StaticHandler.java

/**
 * serve a registered static file/*  ww w  .  j  a v a2 s . c  o  m*/
 * 
 * @param req
 * @param res
 * @param parts
 * @throws IOException
 */
public void doStatic(HttpServletRequest req, HttpServletResponse res, String[] parts) throws IOException {
    try {
        StaticCache[] staticCache = staticCacheHolder.get();
        if (staticCache == null) {
            staticCache = new StaticCache[100];
            staticCacheHolder.set(staticCache);
        }
        String path = URLUtils.getSafePathInfo(req);
        if (path.indexOf("..") >= 0) {
            res.sendError(404);
            return;
        }
        InputStream inputStream;
        String filename = path.substring(path.lastIndexOf("/"));
        long lastModified = -1;
        long length = -1;
        String realPath = servletContext.getRealPath(path);
        if (realPath == null) {
            // We not uncompressing the webapps.
            URL url = servletContext.getResource(path);
            inputStream = url.openStream();
            if (url != null) {
                try {
                    ZipEntry zipEntry = ((JarURLConnection) url.openConnection()).getJarEntry();
                    lastModified = zipEntry.getLastModifiedTime().toMillis();
                    length = zipEntry.getSize();
                } catch (ClassCastException cce) {
                    // Can't get extra data, but should all work.
                    log.debug("We don't seem to be a JAR either.", cce);
                }
            } else {
                res.sendError(404);
                return;
            }
        } else {
            File f = new File(realPath);
            inputStream = new FileInputStream(f);
            lastModified = f.lastModified();
            length = f.length();
        }
        if (length >= 0 && length < MAX_SIZE_KB * 1024) {
            for (int i = 0; i < staticCache.length; i++) {
                StaticCache sc = staticCache[i];
                if (sc != null && path.equals(sc.path)) {
                    // If we don't have a good last modified time it's cached forever
                    if (lastModified > sc.lastModified) {
                        sc.buffer = loadFileBuffer(inputStream, (int) length);
                        sc.path = path;
                        sc.lastModified = lastModified;
                        sc.contenttype = getContentType(filename);
                        sc.added = System.currentTimeMillis();
                    }
                    // send the output
                    sendContent(res, sc);
                    return;
                }
            }
            // not found in cache, find the oldest or null and evict
            // this is thread Safe, since the cache is per thread.
            StaticCache sc = null;
            for (int i = 1; i < staticCache.length; i++) {
                StaticCache current = staticCache[i];
                if (sc == null) {
                    sc = current;
                }
                if (current == null) {
                    sc = new StaticCache();
                    staticCache[i] = sc;
                    break;
                }
                if (sc.added < current.added) {
                    sc = current;
                }
            }
            sc.buffer = loadFileBuffer(inputStream, (int) length);
            sc.path = path;
            sc.lastModified = lastModified;
            sc.contenttype = getContentType(filename);
            sc.added = System.currentTimeMillis();
            sendContent(res, sc);
            return;

        } else {
            res.setContentType(getContentType(filename));
            res.addDateHeader("Last-Modified", lastModified);
            res.setContentLength((int) length);
            sendContent(res, inputStream);
            return;
        }

    } catch (IOException ex) {
        log.info("Failed to send portal content");
        if (log.isDebugEnabled()) {
            log.debug("Full detail of exception is:", ex);
        }
        res.sendError(404, URLUtils.getSafePathInfo(req));
    }

}

From source file:org.sakaiproject.portal.charon.handlers.StaticHandler.java

/**
 * send the content from the static cache.
 * //from   w  w  w.ja  v a2  s .c  om
 * @param res
 * @param sc
 * @throws IOException
 */
void sendContent(HttpServletResponse res, StaticCache sc) throws IOException {
    if (sc.contenttype != null) {
        res.setContentType(sc.contenttype);
    }
    res.addDateHeader("Last-Modified", sc.lastModified);
    res.setContentLength(sc.buffer.length);
    res.getOutputStream().write(sc.buffer);

}

From source file:org.sakaiproject.portal.charon.SkinnableCharonPortal.java

public void sendResponse(PortalRenderContext rcontext, HttpServletResponse res, String template,
        String contentType) throws IOException {
    // headers/*from  www  .  ja v a2s  . c o  m*/
    if (contentType == null) {
        res.setContentType("text/html; charset=UTF-8");
    } else {
        res.setContentType(contentType);
    }
    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");

    // get the writer
    PrintWriter out = res.getWriter();

    try {
        PortalRenderEngine rengine = rcontext.getRenderEngine();
        rengine.render(template, rcontext, out);
    } catch (Exception e) {
        throw new RuntimeException("Failed to render template ", e);
    }

}

From source file:org.sakaiproject.portal.util.ErrorReporter.java

public void report(HttpServletRequest req, HttpServletResponse res, Throwable t, boolean fullPage) {
    boolean showStackTrace = SecurityService.isSuperUser()
            || ServerConfigurationService.getBoolean("portal.error.showdetail", false);

    String bugId = IdManager.createUuid();

    String headInclude = (String) req.getAttribute("sakai.html.head");
    String bodyOnload = (String) req.getAttribute("sakai.html.body.onload");
    Time reportTime = TimeService.newTime();
    String time = reportTime.toStringLocalDate() + " " + reportTime.toStringLocalTime24();
    String usageSessionId = UsageSessionService.getSessionId();
    String userId = SessionManager.getCurrentSessionUserId();
    String requestDisplay = requestDisplay(req);
    String placementDisplay = placementDisplay();
    String problem = throwableDisplay(t);
    String problemdigest = computeSha1(problem);
    String postAddr = ServerConfigurationService.getPortalUrl() + "/error-report";
    String requestURI = req.getRequestURI();

    if (bodyOnload == null) {
        bodyOnload = "";
    } else {/*w  w w  .  j  ava2s. co  m*/
        bodyOnload = " onload=\"" + bodyOnload + "\"";
    }
    try {
        // headers
        res.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        res.setContentType("text/html; charset=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");

        PrintWriter out = null;
        try {
            out = res.getWriter();
        } catch (Exception ex) {
            out = new PrintWriter(res.getOutputStream());
        }

        if (fullPage) {
            out.println(
                    "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
            out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">");
            if (headInclude != null) {
                out.println("<head>");
                out.println(headInclude);
                out.println("</head>");
            }
            out.println("<body" + bodyOnload + ">");
            out.println("<div class=\"portletBody\">");
        }
        out.println("<h3>" + rb.getString("bugreport.error") + "</h3>");
        out.println("<p>" + rb.getString("bugreport.statement") + "<br /><br /></p>");

        out.println("<h4>" + rb.getString("bugreport.sendtitle") + "</h4>");
        out.println("<p>" + rb.getString("bugreport.sendinstructions") + "</p>");

        out.println("<form action=\"" + postAddr + "\" method=\"POST\">");

        if (showStackTrace) {
            out.println("<input type=\"hidden\" name=\"problem\" value=\"");
            out.println(FormattedText.escapeHtml(problem, false));
            out.println("\">");
        }

        out.println("<input type=\"hidden\" name=\"problemRequest\" value=\"");
        out.println(FormattedText.escapeHtml(requestDisplay, false));
        out.println("\">");
        out.println("<input type=\"hidden\" name=\"problemPlacement\" value=\"");
        out.println(FormattedText.escapeHtml(placementDisplay, false));
        out.println("\">");
        out.println("<input type=\"hidden\" name=\"problemdigest\" value=\""
                + FormattedText.escapeHtml(problemdigest, false) + "\">");
        out.println("<input type=\"hidden\" name=\"session\" value=\""
                + FormattedText.escapeHtml(usageSessionId, false) + "\">");
        out.println("<input type=\"hidden\" name=\"bugid\" value=\"" + FormattedText.escapeHtml(bugId, false)
                + "\">");
        out.println("<input type=\"hidden\" name=\"user\" value=\"" + FormattedText.escapeHtml(userId, false)
                + "\">");
        out.println("<input type=\"hidden\" name=\"time\" value=\"" + FormattedText.escapeHtml(time, false)
                + "\">");

        out.println("<table class=\"itemSummary\" cellspacing=\"5\" cellpadding=\"5\">");
        out.println("<tbody>");
        out.println("<tr>");
        out.println("<td><textarea rows=\"10\" cols=\"60\" name=\"comment\"></textarea></td>");
        out.println("</tr>");
        out.println("</tbody>");
        out.println("</table>");
        out.println("<div class=\"act\">");
        out.println("<input type=\"submit\" value=\"" + rb.getString("bugreport.sendsubmit") + "\">");
        out.println("</div>");
        out.println("</form><br />");

        out.println("<h4>" + rb.getString("bugreport.recoverytitle") + "</h4>");
        out.println("<p>" + rb.getString("bugreport.recoveryinstructions") + "");
        out.println("<ul><li>" + rb.getString("bugreport.recoveryinstructions1") + "</li>");
        out.println("<li>" + rb.getString("bugreport.recoveryinstructions2") + "</li>");
        out.println("<li>" + rb.getString("bugreport.recoveryinstructions3") + "</li></ul><br /><br /></p>");

        if (showStackTrace) {
            out.println("<h4>" + rb.getString("bugreport.detailstitle") + "</h4>");
            out.println("<p>" + rb.getString("bugreport.detailsnote") + "</p>");

            out.println("<p><pre>");
            out.println(FormattedText.escapeHtml(problem, false));
            out.println();
            out.println(rb.getString("bugreport.user") + ": " + FormattedText.escapeHtml(userId, false) + "\n");
            out.println(rb.getString("bugreport.usagesession") + ": "
                    + FormattedText.escapeHtml(usageSessionId, false) + "\n");
            out.println(rb.getString("bugreport.time") + ": " + FormattedText.escapeHtml(time, false) + "\n");
            out.println("</pre></p>");
        }

        if (fullPage) {
            out.println("</body>");
            out.println("</html>");
        }

        if (out != null) {
            out.close();
        }

        // log and send the preliminary email
        logAndMail(bugId, usageSessionId, userId, time, problem, problemdigest, requestURI, requestDisplay,
                placementDisplay, null);
    } catch (Throwable any) {
        M_log.warn(rbDefault.getString("bugreport.troublereporting"), any);
    }
}

From source file:org.sakaiproject.portal.util.ErrorReporter.java

/**
 * Accept the user feedback post./*w w  w.j  a  v  a 2s . c  om*/
 * 
 * @param req
 *        The request.
 * @param res
 *        The response.
 */
public void thanksResponse(HttpServletRequest req, HttpServletResponse res) {
    String headInclude = (String) req.getAttribute("sakai.html.head");
    String bodyOnload = (String) req.getAttribute("sakai.html.body.onload");

    if (bodyOnload == null) {
        bodyOnload = "";
    } else {
        bodyOnload = " onload=\"" + bodyOnload + "\"";
    }
    try {
        // headers
        res.setContentType("text/html; charset=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");

        PrintWriter out = res.getWriter();
        out.println(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">");
        if (headInclude != null) {
            out.println("<head>");
            out.println(headInclude);
            out.println("</head>");
        }
        out.println("<body" + bodyOnload + ">");
        out.println("<div class=\"portletBody\">");

        out.println("<h4>" + rb.getString("bugreport.senttitle") + "</h4>");
        out.println("<p>" + rb.getString("bugreport.sentnote") + "<br /><br /></p>");

        out.println("<h4>" + rb.getString("bugreport.recoverytitle") + "</h4>");
        out.println("<p>" + rb.getString("bugreport.recoveryinstructions.reported") + "");
        out.println("<ul><li>" + rb.getString("bugreport.recoveryinstructions1") + "</li>");
        out.println("<li>" + rb.getString("bugreport.recoveryinstructions2") + "</li>");
        out.println("<li>" + rb.getString("bugreport.recoveryinstructions3") + "</li></ul><br /><br /></p>");

        out.println("</body>");
        out.println("</html>");
    } catch (Throwable any) {
        M_log.warn(rbDefault.getString("bugreport.troublethanks"), any);
    }
}

From source file:org.sakaiproject.presence.tool.PresenceTool.java

/**
 * Start the response./*  ww w.  j  a v a2  s .c  o m*/
 * 
 * @param req
 * @param res
 * @param title
 * @param skin
 * @return
 * @throws IOException
 */
protected PrintWriter startResponse(HttpServletRequest req, HttpServletResponse res, String title)
        throws IOException {
    // headers
    res.setContentType("text/html; charset=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");

    // get the writer
    PrintWriter out = res.getWriter();

    if ("yes".equals(req.getParameter(OUTPUT_FRAGMENT)))
        return out;

    // form the head
    out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
            + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
            + "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">" + "  <head>"
            + "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");

    out.println("<title>" + rb.getString("insite") + "</title>");

    // send the portal set-up head
    String head = (String) req.getAttribute("sakai.html.head");
    if (head != null) {
        out.println(head);
    }

    out.println("</head>");

    // Note: we ignore the portal set-up body onload

    // start the body
    out.println("<body>");

    return out;
}

From source file:org.sakaiproject.signup.tool.SignupServlet.java

protected void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    ToolSession session = null;//from   w  w w. j  a v  a 2 s.co  m
    String target = req.getPathInfo();

    // see if we have a helper request
    if (sendToHelper(req, res, target)) {
        return;
    }

    // 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 {
        session = SessionManager.getCurrentToolSession();

        if (target == null || "/".equals(target) || target.length() == 0) {
            if (!m_defaultToLastView) {
                // make sure tool session is clean
                session.clearAttributes();
            }

            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
        session.setAttribute(LAST_VIEW_VISITED, target);
    }

    // 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.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");

    if (session != null && ("true").equals(session.getAttribute("SENT_TO_FILEPICKER_HELPER"))) {
        AttachmentHandler bean = (AttachmentHandler) lookupBeanFromExternalServlet("AttachmentHandler", req,
                res);
        bean.setAttachmentItems();
        session.removeAttribute("SENT_TO_FILEPICKER_HELPER");
    }

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

    // see if we have a helper request
    if (!sendToHelper(req, res, "")) {
        ToolSession toolSession = SessionManager.getCurrentToolSession();
        if (("true").equals(toolSession.getAttribute("SENT_TO_FILEPICKER_HELPER"))) {
            AttachmentHandler bean = (AttachmentHandler) lookupBeanFromExternalServlet("AttachmentHandler", req,
                    res);
            bean.setAttachmentItems();
            toolSession.removeAttribute("SENT_TO_FILEPICKER_HELPER");
        }
    }
}

From source file:org.sakaiproject.siteassociation.tool.servlet.SiteAssocJsfTool.java

@Override
protected void dispatch(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    logger.debug("dispatch()");

    String target = req.getPathInfo();

    ToolSession session = sessionManager.getCurrentToolSession();

    if (logger.isDebugEnabled()) {
        Map<String, String[]> reqParms = req.getParameterMap();
        for (Map.Entry<String, String[]> entry : reqParms.entrySet()) {
            String reqParmKey = entry.getKey();
            StringBuffer sb = new StringBuffer();
            sb.append("REQ_PARM: ");
            sb.append(reqParmKey);/*from   w w  w .j  a  va 2  s . co m*/
            sb.append(" = ");
            sb.append('[');
            String[] reqParm = reqParms.get(reqParmKey);
            for (int i = 0; i < reqParm.length;) {
                sb.append(reqParm[i]);
                if (++i < reqParm.length) {
                    sb.append(", ");
                }
            }
            sb.append(']');
            logger.debug(sb.toString());
        }
        Enumeration<String> sessionParmNames = session.getAttributeNames();
        while (sessionParmNames.hasMoreElements()) {
            String sessionParmName = sessionParmNames.nextElement();
            logger.debug("SESS_PARM: " + sessionParmName + " = " + session.getAttribute(sessionParmName));
        }
    }

    // see if this is the helper trying to return to caller
    if (HELPER_RETURN_NOTIFICATION.equals(target)) {
        target = (String) session.getAttribute(toolManager.getCurrentTool().getId() + Tool.HELPER_DONE_URL);
        if (target != null) {

            // FIXME: Workaround for
            // http://bugs.sakaiproject.org/jira/browse/GM-88
            Object viewCollection = session.getAttribute(STORED_MYFACES_VIEW_COLLECTION);
            if (viewCollection != null) {
                session.removeAttribute(STORED_MYFACES_VIEW_COLLECTION);
                session.setAttribute(MYFACES_VIEW_COLLECTION, viewCollection);
            }

            session.removeAttribute(toolManager.getCurrentTool().getId() + Tool.HELPER_DONE_URL);
            res.sendRedirect(target);
            return;
        }
    }

    // Need this here until ToolServlet is updated to support this in
    // sendToHelper method
    // http://bugs.sakaiproject.org/jira/browse/SAK-9043
    // http://bugs.sakaiproject.org/jira/browse/GM-69
    Enumeration<String> params = req.getParameterNames();
    while (params.hasMoreElements()) {
        String paramName = params.nextElement();
        if (paramName.startsWith(HELPER_SESSION_PREFIX)) {
            String attributeName = paramName.substring(HELPER_SESSION_PREFIX.length());
            session.setAttribute(attributeName, req.getParameter(paramName));
        }
    }

    if (sendToHelper(req, res, target)) {
        return;
    }

    // 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 {

        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) {
            session.setAttribute(LAST_VIEW_VISITED, target);
        }
    }

    // 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.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.sakaiproject.spring.util.SpringTool.java

/**
 * Respond to requests./*from  w ww  .j a  v  a  2 s .c om*/
 *
 * @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 helper request
    if (sendToHelper(req, res, target)) {
        return;
    }

    // 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.osp";
    }

    else {
        ToolSession session = SessionManager.getCurrentToolSession();

        if (target == null || "/".equals(target)) {
            if (!m_defaultToLastView) {
                // make sure tool session is clean
                session.clearAttributes();
            }

            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
        session.setAttribute(LAST_VIEW_VISITED, target);
    }

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