List of usage examples for javax.servlet.http Cookie setMaxAge
public void setMaxAge(int expiry)
From source file:cn.vlabs.umt.ui.servlet.AuthorizationCodeServlet.java
private void doCoremailRequest(HttpServletRequest request, HttpServletResponse response) { String theme = request.getParameter("themeinfo"); if (StringUtils.isNotEmpty(theme) && theme.startsWith("coremail")) { if (StringUtils.isNotEmpty(request.getParameter("rememberUserName"))) { String userName = request.getParameter("userName"); if (StringUtils.isNotEmpty(userName)) { Cookie cookie = new Cookie("passport.remember.user", userName); cookie.setPath("/"); cookie.setMaxAge(14 * 60 * 60 * 24); response.addCookie(cookie); }/*from w w w .jav a 2 s . c om*/ } else { //cookie Cookie cookie = new Cookie("passport.remember.user", ""); cookie.setPath("/"); cookie.setMaxAge(1); response.addCookie(cookie); } if (StringUtils.isNotEmpty(request.getParameter("secureLogon"))) { request.getSession().setAttribute("coremailSecureLogon", true); } } }
From source file:net.nan21.dnet.core.web.controller.ui.extjs.AbstractUiExtjsController.java
/** * Resolve the user's current language from the cookie. * //www .j a v a 2 s. c o m * @param request * @param response * @return * @throws Exception */ private String resolveLang(HttpServletRequest request, HttpServletResponse response) throws Exception { Cookie[] cookies = request.getCookies(); Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_LANG); if (c == null) { String value = this.getSettings().getParam(SysParams_Core.CORE_DEFAULT_LANGUAGE); c = this.createCookie(Constants.COOKIE_NAME_LANG, value, 60 * 60 * 24 * 365); response.addCookie(c); } String lang = request.getParameter(Constants.REQUEST_PARAM_LANG); if (lang == null || lang.equals("")) { lang = c.getValue(); } else { c.setMaxAge(0); c = this.createCookie(Constants.COOKIE_NAME_LANG, lang, 60 * 60 * 24 * 365); response.addCookie(c); } return lang; }
From source file:net.nan21.dnet.core.web.controller.ui.extjs.AbstractUiExtjsController.java
/** * Resolve the user's current theme from the cookie. * /* w ww.j a v a 2 s . c o m*/ * @param request * @param response * @return * @throws Exception */ private String resolveTheme(HttpServletRequest request, HttpServletResponse response) throws Exception { Cookie[] cookies = request.getCookies(); Cookie c = this.getCookie(cookies, Constants.COOKIE_NAME_THEME); if (c == null) { String value = this.getSettings().getParam(SysParams_Core.CORE_DEFAULT_THEME_EXTJS); c = this.createCookie(Constants.COOKIE_NAME_THEME, value, 60 * 60 * 24 * 365); response.addCookie(c); } String theme = request.getParameter(Constants.REQUEST_PARAM_THEME); if (theme == null || theme.equals("")) { theme = c.getValue(); } else { c.setMaxAge(0); c = this.createCookie(Constants.COOKIE_NAME_THEME, theme, 60 * 60 * 24 * 365); response.addCookie(c); } return theme; }
From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java
/** * Copy cookie from the proxy to the servlet client. Replaces cookie path to * local path and renames cookie to avoid collisions. */// www .ja va 2 s .co m protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Header header) { List<HttpCookie> cookies = HttpCookie.parse(header.getValue()); String path = getServletContext().getServletContextName(); if (path == null) { path = ""; } path += servletRequest.getServletPath(); for (HttpCookie cookie : cookies) { // set cookie name prefixed w/ a proxy value so it won't collide w/ // other cookies String proxyCookieName = getCookieNamePrefix() + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); // set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
From source file:com.egt.core.jsf.JSF.java
private static String putCookie(String key, String value, boolean qualified, int expiry) { Bitacora.trace(JSF.class, "putCookie", "key=" + key, "value=" + value, "qualified=" + qualified, "expiry=" + expiry); FacesContext facesContext = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); String qualifiedKey = key + getRequestQualifier(); String name = qualified ? qualifiedKey : key; Cookie cookie = new Cookie(name, value); /*/*from w w w . java2s.co m*/ * maximum age of the cookie in seconds; if negative, the cookie is not stored; if zero, deletes the cookie. */ cookie.setMaxAge(expiry); response.addCookie(cookie); return name; }
From source file:org.akaza.openclinica.control.MainMenuServlet.java
public String getTimeoutReturnToCookie(HttpServletRequest request, HttpServletResponse response) { String queryStr = ""; if (ub == null || StringUtils.isEmpty(ub.getName())) return queryStr; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equalsIgnoreCase("bridgeTimeoutReturn-" + ub.getName())) { try { queryStr = URLDecoder.decode(cookie.getValue(), "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error("Error decoding redirect URL from queryStr cookie:" + e.getMessage()); }//from w w w.j av a 2s.c o m cookie.setValue(null); cookie.setMaxAge(0); cookie.setPath("/"); if (response != null) response.addCookie(cookie); break; } } return queryStr; }
From source file:alxpez.blog.BlogController.java
private void initializeRoutes() throws IOException { // this is the blog home page get(new FreemarkerBasedRoute("/", "blog_template.ftl") { @Override//www . j av a2s. co m public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); List<Document> posts = blogPostDAO.findByDateDescending(10); SimpleHash root = new SimpleHash(); root.put("myposts", posts); if (username != null) { root.put("username", username); } template.process(root, writer); } }); // used to display actual blog post detail page get(new FreemarkerBasedRoute("/post/:permalink", "entry_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String permalink = request.params(":permalink"); System.out.println("/post: get " + permalink); Document post = blogPostDAO.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); } else { // empty comment to hold new comment in form at bottom of blog entry detail page SimpleHash newComment = new SimpleHash(); newComment.put("name", ""); newComment.put("email", ""); newComment.put("body", ""); SimpleHash root = new SimpleHash(); root.put("post", post); root.put("comment", newComment); template.process(root, writer); } } }); // handle the signup post post(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String email = request.queryParams("email"); String username = request.queryParams("username"); String password = request.queryParams("password"); String verify = request.queryParams("verify"); HashMap<String, String> root = new HashMap<String, String>(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("email", StringEscapeUtils.escapeHtml4(email)); if (validateSignup(username, password, verify, email, root)) { // good user System.out.println("Signup: Creating user with: " + username + " " + password); if (!userDAO.addUser(username, password, email)) { // duplicate user root.put("username_error", "Username already in use, Please choose another"); template.process(root, writer); } else { // good user, let's start a session String sessionID = sessionDAO.startSession(username); System.out.println("Session ID is" + sessionID); response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/welcome"); } } else { // bad signup System.out.println("User Registration did not validate"); template.process(root, writer); } } }); // present signup form for blog get(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); // initialize values for the form. root.put("username", ""); root.put("password", ""); root.put("email", ""); root.put("password_error", ""); root.put("username_error", ""); root.put("email_error", ""); root.put("verify_error", ""); template.process(root, writer); } }); // will present the form used to process new blog posts get(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { // get cookie String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); if (username == null) { // looks like a bad request. user is not logged in response.redirect("/login"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // handle the new post submission post(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String title = StringEscapeUtils.escapeHtml4(request.queryParams("subject")); String post = StringEscapeUtils.escapeHtml4(request.queryParams("body")); String tags = StringEscapeUtils.escapeHtml4(request.queryParams("tags")); String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); if (username == null) { response.redirect("/login"); // only logged in users can post to blog } else if (title.equals("") || post.equals("")) { // redisplay page with errors HashMap<String, String> root = new HashMap<String, String>(); root.put("errors", "post must contain a title and blog entry."); root.put("subject", title); root.put("username", username); root.put("tags", tags); root.put("body", post); template.process(root, writer); } else { // extract tags ArrayList<String> tagsArray = extractTags(tags); // substitute some <p> for the paragraph breaks post = post.replaceAll("\\r?\\n", "<p>"); String permalink = blogPostDAO.addPost(title, post, tagsArray, username); // now redirect to the blog permalink response.redirect("/post/" + permalink); } } }); get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String cookie = getSessionCookie(request); String username = sessionDAO.findUserNameBySessionId(cookie); if (username == null) { System.out.println("welcome() can't identify the user, redirecting to signup"); response.redirect("/signup"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // process a new comment post(new FreemarkerBasedRoute("/newcomment", "entry_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String name = StringEscapeUtils.escapeHtml4(request.queryParams("commentName")); String email = StringEscapeUtils.escapeHtml4(request.queryParams("commentEmail")); String body = StringEscapeUtils.escapeHtml4(request.queryParams("commentBody")); String permalink = request.queryParams("permalink"); Document post = blogPostDAO.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); } // check that comment is good else if (name.equals("") || body.equals("")) { // bounce this back to the user for correction SimpleHash root = new SimpleHash(); SimpleHash comment = new SimpleHash(); comment.put("name", name); comment.put("email", email); comment.put("body", body); root.put("comment", comment); root.put("post", post); root.put("errors", "Post must contain your name and an actual comment"); template.process(root, writer); } else { blogPostDAO.addPostComment(name, email, body, permalink); response.redirect("/post/" + permalink); } } }); // present the login page get(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("username", ""); root.put("login_error", ""); template.process(root, writer); } }); // process output coming from login form. On success redirect folks to the welcome page // on failure, just return an error and let them try again. post(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = request.queryParams("username"); String password = request.queryParams("password"); System.out.println("Login: User submitted: " + username + " " + password); Document user = userDAO.validateLogin(username, password); if (user != null) { // valid user, let's log them in String sessionID = sessionDAO.startSession(user.get("_id").toString()); if (sessionID == null) { response.redirect("/internal_error"); } else { // set the cookie for the user's browser response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/welcome"); } } else { SimpleHash root = new SimpleHash(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("password", ""); root.put("login_error", "Invalid Login"); template.process(root, writer); } } }); // Show the posts filed under a certain tag get(new FreemarkerBasedRoute("/tag/:thetag", "blog_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); SimpleHash root = new SimpleHash(); String tag = StringEscapeUtils.escapeHtml4(request.params(":thetag")); List<Document> posts = blogPostDAO.findByTagDateDescending(tag); root.put("myposts", posts); if (username != null) { root.put("username", username); } template.process(root, writer); } }); // will allow a user to click Like on a post post(new FreemarkerBasedRoute("/like", "entry_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String permalink = request.queryParams("permalink"); String commentOrdinalStr = request.queryParams("comment_ordinal"); // look up the post in question int ordinal = Integer.parseInt(commentOrdinalStr); // TODO: check return or have checkSession throw String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); Document post = blogPostDAO.findByPermalink(permalink); // if post not found, redirect to post not found error if (post == null) { response.redirect("/post_not_found"); } else { blogPostDAO.likePost(permalink, ordinal); response.redirect("/post/" + permalink); } } }); // tells the user that the URL is dead get(new FreemarkerBasedRoute("/post_not_found", "post_not_found.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); template.process(root, writer); } }); // allows the user to logout of the blog get(new FreemarkerBasedRoute("/logout", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String sessionID = getSessionCookie(request); if (sessionID == null) { // no session to end response.redirect("/login"); } else { // deletes from session table sessionDAO.endSession(sessionID); // this should delete the cookie Cookie c = getSessionCookieActual(request); c.setMaxAge(0); response.raw().addCookie(c); response.redirect("/login"); } } }); // used to process internal errors get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("error", "System has encountered an error."); template.process(root, writer); } }); }
From source file:de.escidoc.core.aa.servlet.Login.java
/** * Creates a {@link Cookie} for the provided values. * * @param name The name of the {@link Cookie}. * @param value The value of the {@link Cookie}. * @param maxAge The maxAge of the {@link Cookie}. * @return Returns the created {@link Cookie} with set values and path set to "/". * @throws WebserverSystemException Thrown if cookie creation fails due to an internal error. *//*from w w w .j a v a2 s. co m*/ private Cookie createCookie(final String name, final String value, final int maxAge) throws WebserverSystemException { final Cookie cookie = new Cookie(name, value); cookie.setVersion((int) getEscidocCookieVersion()); cookie.setMaxAge(maxAge); cookie.setPath("/"); return cookie; }
From source file:com.liferay.portal.servlet.MainServlet.java
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { if (!PortalInstances.matches()) { String html = ContentUtil.get("messages/en_US/init.html"); res.getOutputStream().print(html); return;//from w ww . j a v a2 s .co m } if (ShutdownUtil.isShutdown()) { String html = ContentUtil.get("messages/en_US/shutdown.html"); res.getOutputStream().print(html); return; } req.setAttribute("dotcache", "no"); // Shared session HttpSession ses = req.getSession(); if (!GetterUtil.getBoolean(PropsUtil.get(PropsUtil.TCK_URL))) { String sharedSessionId = CookieUtil.get(req.getCookies(), CookieKeys.SHARED_SESSION_ID); _log.debug("Shared session id is " + sharedSessionId); if (sharedSessionId == null) { sharedSessionId = PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2, 12); Cookie sharedSessionIdCookie = new Cookie(CookieKeys.SHARED_SESSION_ID, sharedSessionId); sharedSessionIdCookie.setPath("/"); sharedSessionIdCookie.setMaxAge(86400); res.addCookie(sharedSessionIdCookie); _log.debug("Shared session id is " + sharedSessionId); } // if (ses.getAttribute(WebKeys.SHARED_SESSION_ID) == null) { ses.setAttribute(WebKeys.SHARED_SESSION_ID, sharedSessionId); // } HttpSession portalSes = (HttpSession) SharedSessionPool.get(sharedSessionId); if ((portalSes == null) || (ses != portalSes)) { if (portalSes == null) { _log.debug("No session exists in pool"); } else { _log.debug("Session " + portalSes.getId() + " in pool is old"); } _log.debug("Inserting current session " + ses.getId() + " in pool"); SharedSessionPool.put(sharedSessionId, ses); } } // Test CAS auto login /* * ses.setAttribute( * com.liferay.portal.auth.CASAutoLogin.CAS_FILTER_USER, * "liferay.com.1"); */ // CTX ServletContext ctx = getServletContext(); ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX)); if (portalCtx == null) { portalCtx = ctx; } req.setAttribute(WebKeys.CTX, portalCtx); // CTX_PATH variable String ctxPath = (String) ctx.getAttribute(WebKeys.CTX_PATH); if (portalCtx.getAttribute(WebKeys.CTX_PATH) == null) { portalCtx.setAttribute(WebKeys.CTX_PATH, ctxPath); } if (ses.getAttribute(WebKeys.CTX_PATH) == null) { ses.setAttribute(WebKeys.CTX_PATH, ctxPath); } req.setAttribute(WebKeys.CTX_PATH, ctxPath); // CAPTCHA_PATH variable String captchaPath = (String) ctx.getAttribute(WebKeys.CAPTCHA_PATH); if (portalCtx.getAttribute(WebKeys.CAPTCHA_PATH) == null) { portalCtx.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); } if (ses.getAttribute(WebKeys.CAPTCHA_PATH) == null) { ses.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); } req.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath); // IMAGE_PATH variable String imagePath = (String) ctx.getAttribute(WebKeys.IMAGE_PATH); if (portalCtx.getAttribute(WebKeys.IMAGE_PATH) == null) { portalCtx.setAttribute(WebKeys.IMAGE_PATH, imagePath); } if (ses.getAttribute(WebKeys.IMAGE_PATH) == null) { ses.setAttribute(WebKeys.IMAGE_PATH, imagePath); } req.setAttribute(WebKeys.IMAGE_PATH, imagePath); // WebKeys.COMPANY_ID variable String companyId = (String) ctx.getAttribute(WebKeys.COMPANY_ID); if (portalCtx.getAttribute(WebKeys.COMPANY_ID) == null) { portalCtx.setAttribute(WebKeys.COMPANY_ID, companyId); } if (ses.getAttribute(WebKeys.COMPANY_ID) == null) { ses.setAttribute(WebKeys.COMPANY_ID, companyId); } req.setAttribute(WebKeys.COMPANY_ID, companyId); // Portlet Request Processor PortletRequestProcessor portletReqProcessor = (PortletRequestProcessor) portalCtx .getAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR); if (portletReqProcessor == null) { portletReqProcessor = new PortletRequestProcessor(this, getModuleConfig(req)); portalCtx.setAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor); } // Tiles definitions factory if (portalCtx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY) == null) { portalCtx.setAttribute(TilesUtilImpl.DEFINITIONS_FACTORY, ctx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY)); } // Set character encoding String strutsCharEncoding = PropsUtil.get(PropsUtil.STRUTS_CHAR_ENCODING); req.setCharacterEncoding(strutsCharEncoding); /* * if (!BrowserSniffer.is_wml(req)) { res.setContentType( * Constants.TEXT_HTML + "; charset=" + strutsCharEncoding); } */ // Determine content type String contentType = req.getHeader("Content-Type"); if ((contentType != null) && (contentType.startsWith("multipart/form-data"))) { req = new UploadServletRequest(req); } else if (ParamUtil.get(req, WebKeys.ENCRYPT, false)) { try { Company company = CompanyLocalManagerUtil.getCompany(companyId); req = new EncryptedServletRequest(req, company.getKeyObj()); } catch (Exception e) { } } // Current URL String completeURL = Http.getCompleteURL(req); if (completeURL.indexOf("j_security_check") != -1) { completeURL = ctxPath; } else { completeURL = completeURL.substring(completeURL.indexOf("://") + 3, completeURL.length()); completeURL = completeURL.substring(completeURL.indexOf("/"), completeURL.length()); } req.setAttribute(WebKeys.CURRENT_URL, completeURL); // Chat server // Login String userId = PortalUtil.getUserId(req); if ((userId != null)) { PrincipalThreadLocal.setName(userId); } if (userId == null) { try { User user = UserManagerUtil.getDefaultUser(companyId); if (ses.getAttribute(Globals.LOCALE_KEY) == null) ses.setAttribute(Globals.LOCALE_KEY, user.getLocale()); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } } // Process pre service events try { EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_PRE), req, res); } catch (Exception e) { Logger.error(this, e.getMessage(), e); req.setAttribute(PageContext.EXCEPTION, e); StrutsUtil.forward(PropsUtil.get(PropsUtil.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE), portalCtx, req, res); } // Struts service callParentService(req, res); // Process post service events try { EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_POST), req, res); } catch (Exception e) { Logger.error(this, e.getMessage(), e); } // Clear the principal associated with this thread PrincipalThreadLocal.setName(null); }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractHomeController.java
@RequestMapping(value = "/forum", method = RequestMethod.GET) public String forum(HttpServletResponse response, ModelMap map) { logger.debug("###Entering in forum(response,map) method @POST"); Cookie cookie = new Cookie("JforumSSO", "User" + getCurrentUser().getId()); cookie.setMaxAge(-1); cookie.setPath("/"); response.addCookie(cookie);/*w ww. j ava 2 s . co m*/ map.addAttribute("forumContext", config.getForumContextPath()); logger.debug("###Exiting forum(response,map) method @POST"); return "forum.show"; }