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.login.tool.LoginTool.java

/**
 * Send the login form//from w  w  w  .  ja  v  a  2  s  .c  o m
 *
 * @param req
 *        Servlet request.
 * @param res
 *        Servlet response.
 * @throws IOException
 */
protected void sendForm(HttpServletRequest req, HttpServletResponse res) throws IOException {

    final String headHtml = "<!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\" />"
            + "    <link href=\"SKIN_ROOT/tool_base.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />"
            + "    <link href=\"SKIN_ROOT/DEFAULT_SKIN/tool.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />"
            + "    <meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />"
            + "    <title>UI.SERVICE</title>"
            + "    <script type=\"text/javascript\" language=\"JavaScript\" src=\"/library/js/headscripts.js\"></script>"
            + "  </head>"
            + "  <body onload=\"if ((document.getElementById('pw').passwordfocus != true)) document.getElementById('eid').focus() ;parent.updCourier(doubleDeep, ignoreCourier);\" class=\"servletBody\">";

    final String tailHtml = "</body></html>";

    final String loginHtml = "<table class=\"login\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" summary=\"layout\">"
            + "      <tr>" + "         <th colspan=\"2\">" + "            Login Required" + "         </th>"
            + "      </tr>" + "      <tr>" + "         <td class=\"logo\">" + "         </td>"
            + "         <td class=\"form\">"
            + "            <form method=\"post\" action=\"ACTION\" enctype=\"application/x-www-form-urlencoded\">"
            + "                                        MSG"
            + "                     <table border=\"0\" class=\"loginform\" summary=\"layout\">"
            + "                        <tr>" + "                           <td>"
            + "                              <label for=\"eid\">EID</label>"
            + "                           </td>" + "                           <td class=\"shorttext\">"
            + "                              <input name=\"eid\" id=\"eid\"  type=\"text\" size=\"15\"/>"
            + "                           </td>" + "                        </tr>"
            + "                        <tr>" + "                           <td>"
            + "                              <label for=\"pw\">PW</label>" + "                           </td>"
            + "                           <td class=\"shorttext\">"
            + "                              <input name=\"pw\" id=\"pw\"  type=\"password\" size=\"15\" onFocus=\"this.passwordfocus = true; \" />"
            + "                           </td>" + "                        </tr>"
            + "                        <tr>" + "                           <td colspan=\"2\">"
            + "                              <input name=\"submit\" type=\"submit\" id=\"submit\" value=\"LoginSubmit\"/>"
            + "                           </td>" + "                        </tr>"
            + "                     </table>" + "                  </form>" + "               </td>"
            + "            </tr>" + "         </table>";

    // get the Sakai session
    Session session = SessionManager.getCurrentSession();

    // get my tool registration
    Tool tool = (Tool) req.getAttribute(Tool.TOOL);

    // fragment or not?
    boolean fragment = Boolean.TRUE.toString().equals(req.getAttribute(Tool.FRAGMENT));

    // PDA or not?
    String portalUrl = (String) session.getAttribute(Tool.HELPER_DONE_URL);
    boolean isPDA = false;
    if (portalUrl != null)
        isPDA = portalUrl.endsWith(PDA_PORTAL_SUFFIX);

    String eidWording = rb.getString("userid");
    String pwWording = rb.getString("log.pass");
    String loginRequired = rb.getString("log.logreq");
    String loginWording = rb.getString("log.login");

    if (!fragment) {
        // set our response type
        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");
    }

    String defaultSkin = ServerConfigurationService.getString("skin.default");
    String skinRoot = ServerConfigurationService.getString("skin.repo");
    String uiService = ServerConfigurationService.getString("ui.service");

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

    if (!fragment) {

        // start our complete document
        String head = headHtml;
        if (isPDA) {
            head = head.replaceAll("</title>",
                    "</title><link href=\"SKIN_ROOT/DEFAULT_SKIN/pda.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" /> <meta name=\"viewport\" content=\"width=device-width, user-scalable=yes,  initial-scale=1.0, maximum-scale=1.0\"/>");
        }

        head = head.replaceAll("DEFAULT_SKIN", defaultSkin);
        head = head.replaceAll("SKIN_ROOT", skinRoot);
        head = head.replaceAll("UI.SERVICE", uiService);
        out.println(head);
    }

    // if we are in helper mode, there might be a helper message
    if (session.getAttribute(Tool.HELPER_MESSAGE) != null) {
        out.println("<p>" + session.getAttribute(Tool.HELPER_MESSAGE) + "</p>");
    }

    // add our return URL
    String returnUrl = res.encodeURL(Web.returnUrl(req, null));
    String html = loginHtml.replaceAll("ACTION", res.encodeURL(returnUrl));

    // add our wording
    html = html.replaceAll("EID", eidWording);
    html = html.replaceAll("PW", pwWording);
    html = html.replaceAll("Login Required", loginRequired);
    html = html.replaceAll("LoginSubmit", loginWording);

    // add the default skin
    html = html.replaceAll("DEFAULT_SKIN", defaultSkin);
    html = html.replaceAll("SKIN_ROOT", skinRoot);
    if (isPDA) {
        html = html.replaceAll("class=\"login\"", "class=\"loginPDA\"");
        html = html.replaceAll("</title>",
                "</title><link href=\"SKIN_ROOT/DEFAULT_SKIN/pda.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />");
    }

    // write a message if present
    String msg = (String) session.getAttribute(ATTR_MSG);
    if (msg != null) {
        html = html.replaceAll("MSG",
                "<div class=\"alertMessage\">" + rb.getString("gen.alert") + " " + msg + "</div>");
        session.removeAttribute(ATTR_MSG);
    } else {
        html = html.replaceAll("MSG", "");
    }

    // write the login screen
    out.println(html);

    if (!fragment) {
        // close the complete document
        out.println(tailHtml);
    }
}

From source file:org.sakaiproject.login.tool.SkinnableLogin.java

public void sendResponse(LoginRenderContext rcontext, HttpServletResponse res, String template,
        String contentType) throws IOException {
    // headers//w  w w  . j a v  a2 s.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 {
        LoginRenderEngine rengine = rcontext.getRenderEngine();
        rengine.render(template, rcontext, out);
    } catch (Exception e) {
        throw new RuntimeException("Failed to render template ", e);
    }

}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceImpl.java

/**
 * @param userId//w w  w  .j av  a2s .  c  om
 * @param response
 */
void addCookie(HttpServletResponse response, String userId, String tokenType) {
    Cookie c = new HttpOnlyCookie(trustedAuthCookieName, encodeCookie(userId, tokenType));
    c.setMaxAge(-1);
    c.setPath("/");
    c.setSecure(secureCookie);
    response.addCookie(c);
    // rfc 2109 section 4.5. stop http 1.1 caches caching the response
    response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
    // and stop http 1.0 caches caching the response
    response.addDateHeader("Expires", 0);
}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceTest.java

@Test
public void testCookieRefresh() throws InterruptedException {
    ComponentContext context = configureForCookieFast();
    HttpServletResponse response = createMock(HttpServletResponse.class);
    Capture<Cookie> cookieCapture = new Capture<Cookie>();
    response.addCookie(EasyMock.capture(cookieCapture));
    EasyMock.expectLastCall();/*w  w w  . j  a va2 s  .c  om*/
    response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
    expectLastCall();
    response.addDateHeader("Expires", 0);
    expectLastCall();
    replay();
    trustedTokenService.activate(context);
    String cookie = trustedTokenService.encodeCookie("ieb", TrustedTokenTypes.AUTHENTICATED_TRUST);
    Thread.sleep(100L);
    trustedTokenService.refreshToken(response, cookie, "ieb", TrustedTokenTypes.AUTHENTICATED_TRUST);
    Assert.assertTrue(cookieCapture.hasCaptured());
    Cookie cookie2 = cookieCapture.getValue();
    Assert.assertNotNull(cookie);
    Assert.assertNotSame(cookie, cookie2.getValue());
    Assert.assertEquals("secure-cookie", cookie2.getName());
    String[] user = trustedTokenService.decodeCookie(cookie2.getValue());
    Assert.assertArrayEquals("Cookie was " + cookie2.getValue(),
            new String[] { "ieb", TrustedTokenTypes.AUTHENTICATED_TRUST }, user);
    verify();
}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceTest.java

@Test
public void testAddCookie() {
    ComponentContext context = configureForCookie();
    HttpServletResponse response = createMock(HttpServletResponse.class);
    Capture<Cookie> cookieCapture = new Capture<Cookie>();
    response.addCookie(EasyMock.capture(cookieCapture));
    EasyMock.expectLastCall();/*from   w w w  . j  a v  a2 s.  c  om*/
    response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
    expectLastCall();
    response.addDateHeader("Expires", 0);
    expectLastCall();

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.addCookie(response, "ieb", TrustedTokenTypes.AUTHENTICATED_TRUST);
    Assert.assertTrue(cookieCapture.hasCaptured());
    Cookie cookie = cookieCapture.getValue();
    Assert.assertNotNull(cookie);
    Assert.assertEquals("secure-cookie", cookie.getName());
    String[] user = trustedTokenService.decodeCookie(cookie.getValue());
    Assert.assertArrayEquals(new String[] { "ieb", TrustedTokenTypes.AUTHENTICATED_TRUST }, user);
    verify();
}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceTest.java

@Test
public void testInjectCookiePrincipal() {
    ComponentContext context = configureForCookie();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    Principal principal = createMock(Principal.class);
    EasyMock.expect(request.getRemoteAddr()).andReturn("192.168.0.123");
    EasyMock.expect(request.getHeader("remote_user")).andReturn(null);
    EasyMock.expect(request.getUserPrincipal()).andReturn(principal);
    EasyMock.expect(principal.getName()).andReturn("ieb");
    HttpServletResponse response = createMock(HttpServletResponse.class);
    Capture<Cookie> cookieCapture = new Capture<Cookie>();
    response.addCookie(EasyMock.capture(cookieCapture));
    EasyMock.expectLastCall();/*from  w  ww . ja v  a2 s.  co  m*/
    response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
    expectLastCall();
    response.addDateHeader("Expires", 0);
    expectLastCall();

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.injectToken(request, response, TrustedTokenTypes.AUTHENTICATED_TRUST, null);
    Assert.assertTrue(cookieCapture.hasCaptured());
    Cookie cookie = cookieCapture.getValue();
    Assert.assertNotNull(cookie);
    Assert.assertEquals("secure-cookie", cookie.getName());
    String[] user = trustedTokenService.decodeCookie(cookie.getValue());
    Assert.assertArrayEquals(new String[] { "ieb", TrustedTokenTypes.AUTHENTICATED_TRUST }, user);
    verify();
}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceTest.java

@Test
public void testInjectCookieUser() {
    ComponentContext context = configureForCookie();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    Principal principal = createMock(Principal.class);
    EasyMock.expect(request.getRemoteAddr()).andReturn("192.168.0.127"); // not a trusted proxy

    EasyMock.expect(request.getUserPrincipal()).andReturn(principal);
    EasyMock.expect(principal.getName()).andReturn(null);
    EasyMock.expect(request.getRemoteUser()).andReturn("ieb");
    HttpServletResponse response = createMock(HttpServletResponse.class);
    Capture<Cookie> cookieCapture = new Capture<Cookie>();
    response.addCookie(EasyMock.capture(cookieCapture));
    EasyMock.expectLastCall();//from   w ww  .j ava 2  s  .co  m
    response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
    expectLastCall();
    response.addDateHeader("Expires", 0);
    expectLastCall();

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.injectToken(request, response, TrustedTokenTypes.AUTHENTICATED_TRUST, null);
    Assert.assertTrue(cookieCapture.hasCaptured());
    Cookie cookie = cookieCapture.getValue();
    Assert.assertNotNull(cookie);
    Assert.assertEquals("secure-cookie", cookie.getName());
    String[] user = trustedTokenService.decodeCookie(cookie.getValue());
    Assert.assertArrayEquals(new String[] { "ieb", TrustedTokenTypes.AUTHENTICATED_TRUST }, user);
    verify();
}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceTest.java

@Test
public void testInjectCookieHeader() {
    ComponentContext context = configureForCookie();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    EasyMock.expect(request.getRemoteAddr()).andReturn("192.168.0.123");
    EasyMock.expect(request.getHeader("remote_user")).andReturn("ieb").anyTimes();
    HttpServletResponse response = createMock(HttpServletResponse.class);
    Capture<Cookie> cookieCapture = new Capture<Cookie>();
    response.addCookie(EasyMock.capture(cookieCapture));
    EasyMock.expectLastCall();/* ww w.jav  a 2  s. c  o  m*/
    response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
    expectLastCall();
    response.addDateHeader("Expires", 0);
    expectLastCall();

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.injectToken(request, response, TrustedTokenTypes.AUTHENTICATED_TRUST, null);
    Assert.assertTrue(cookieCapture.hasCaptured());
    Cookie cookie = cookieCapture.getValue();
    Assert.assertNotNull(cookie);
    Assert.assertEquals("secure-cookie", cookie.getName());
    String[] user = trustedTokenService.decodeCookie(cookie.getValue());
    Assert.assertArrayEquals(new String[] { "ieb", TrustedTokenTypes.AUTHENTICATED_TRUST }, user);
    verify();
}

From source file:org.sakaiproject.nakamura.auth.trusted.TrustedTokenServiceTest.java

@Test
public void testInjectCookieParameter() {
    ComponentContext context = configureForCookieParameter();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    EasyMock.expect(request.getRemoteAddr()).andReturn("192.168.0.123");
    EasyMock.expect(request.getHeader("remote_user")).andReturn("").anyTimes();
    EasyMock.expect(request.getParameter("remote_user_parameter")).andReturn("ieb").anyTimes();
    HttpServletResponse response = createMock(HttpServletResponse.class);
    Capture<Cookie> cookieCapture = new Capture<Cookie>();
    response.addCookie(EasyMock.capture(cookieCapture));
    EasyMock.expectLastCall();/*from  w w w.j  a  va2 s .co m*/
    response.addHeader("Cache-Control", "no-cache=\"set-cookie\" ");
    expectLastCall();
    response.addDateHeader("Expires", 0);
    expectLastCall();

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.injectToken(request, response, TrustedTokenTypes.AUTHENTICATED_TRUST, null);
    Assert.assertTrue(cookieCapture.hasCaptured());
    Cookie cookie = cookieCapture.getValue();
    Assert.assertNotNull(cookie);
    Assert.assertEquals("secure-cookie", cookie.getName());
    String[] user = trustedTokenService.decodeCookie(cookie.getValue());
    Assert.assertArrayEquals(new String[] { "ieb", TrustedTokenTypes.AUTHENTICATED_TRUST }, user);
    verify();
}

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

/**
 * Output the content of the title frame for a tool.
 *//*w  w  w.j  a  va 2  s .c om*/
protected void includeTitle(ActiveTool tool, HttpServletRequest req, HttpServletResponse res,
        ToolConfiguration placement, String skin, String toolContextPath, String toolPathInfo)
        throws IOException {

    // TODO: After 2.3 and the background document is modified - this may no
    // longer be needed
    // as the title is simply in the background document

    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 (skin == null || skin.length() == 0)
        skin = ServerConfigurationService.getString("skin.default");
    String skinRepo = ServerConfigurationService.getString("skin.repo");

    // the title to display in the title frame
    String toolTitle = Web.escapeHtml(placement.getTitle());

    // for the reset button
    String resetActionUrl = toolContextPath + "?reset=true";
    boolean resetToolNow = "true".equals(req.getParameter("reset"));
    boolean showResetButton = !"false".equals(placement.getConfig().getProperty(TOOLCONFIG_SHOW_RESET_BUTTON));

    // for the help button
    // get the help document ID from the tool config (tool registration
    // usually).
    // The help document ID defaults to the tool ID
    boolean helpEnabledGlobally = ServerConfigurationService.getBoolean("display.help.icon", true);
    boolean helpEnabledInTool = !"false".equals(placement.getConfig().getProperty(TOOLCONFIG_SHOW_HELP_BUTTON));
    boolean showHelpButton = helpEnabledGlobally && helpEnabledInTool;

    String helpActionUrl = "";
    if (showHelpButton) {
        String helpDocId = placement.getConfig().getProperty(TOOLCONFIG_HELP_DOCUMENT_ID);
        String helpDocUrl = placement.getConfig().getProperty(TOOLCONFIG_HELP_DOCUMENT_URL);
        if (helpDocUrl != null && helpDocUrl.length() > 0) {
            helpActionUrl = helpDocUrl;
        } else {
            if (helpDocId == null || helpDocId.length() == 0) {
                helpDocId = tool.getId();
            }
            helpActionUrl = ServerConfigurationService.getHelpUrl(helpDocId);
        }
    }

    PrintWriter out = res.getWriter();

    final String headHtml = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
            + "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n" + "  <head>\n"
            + "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
            + "    <link href=\"" + skinRepo
            + "/tool_base.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n" + "    <link href=\""
            + skinRepo + "/" + skin + "/tool.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n"
            + "    <meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />\n"
            + "    <script type=\"text/javascript\" src=\"" + getScriptPath() + "headscripts.js\"></script>\n"
            + "    <title>" + toolTitle + "</title>\n" + "  </head>\n" + "  <body>\n";
    final String tailHtml = "</body></html>\n";

    out.write(headHtml);

    out.write("<div class=\"portletTitle\">\n");
    out.write("\t<div class=\"title\">\n");
    if (showResetButton) {
        out.write("\t\t<a href=\"" + resetActionUrl + "\" title=\"" + Web.escapeHtml(rb.getString("sit_reset"))
                + "\"><img src=\"/library/image/transparent.gif\" alt=\""
                + Web.escapeHtml(rb.getString("sit_reset")) + "\" border=\"1\" /></a>");
    }

    out.write("<h2>" + toolTitle + "\n" + "\t</h2></div>\n");
    out.write("\t<div class=\"action\">\n");
    if (showHelpButton) {
        out.write(makeHelpButton(helpActionUrl));
    }

    out.write("\t</div>\n");
    out.write("</div>\n");

    if (resetToolNow) {
        // cause main tool frame to be reset

        // clear the session data associated with the tool - should reset
        // the tool
        Session s = SessionManager.getCurrentSession();
        ToolSession ts = s.getToolSession(placement.getId());
        ts.clearAttributes();

        // redirect the main tool frame back to the initial tool URL.
        String mainFrameId = Web.escapeJavascript("Main" + placement.getId());
        String mainFrameUrl = ServerConfigurationService.getToolUrl() + "/" + Web.escapeUrl(placement.getId())
                + "?panel=Main";

        out.write("<script type=\"text/javascript\">\n");
        out.write("try\n");
        out.write("{\n");
        out.write("   if (parent." + mainFrameId + ".location.toString().length > 1)\n");
        out.write("   {\n");
        out.write("      parent." + mainFrameId + ".location = '" + mainFrameUrl + "';\n");
        out.write("   }\n");
        out.write("}\n");
        out.write("catch (e1)\n");
        out.write("{\n");
        out.write("   try\n");
        out.write("   {\n");
        out.write("      if (parent.parent." + mainFrameId + ".location.toString().length > 1)\n");
        out.write("      {\n");
        out.write("         parent.parent." + mainFrameId + ".location = '" + mainFrameUrl + "';\n");
        out.write("      }\n");
        out.write("   }\n");
        out.write("   catch (e2)\n");
        out.write("   {\n");
        out.write("   }\n");
        out.write("}\n");
        out.write("</script>\n");
    }

    out.write(tailHtml);
}