List of usage examples for javax.servlet.http HttpServletResponse addCookie
public void addCookie(Cookie cookie);
From source file:com.vmm.storefront.controllers.pages.ProductPageController.java
@RequestMapping(value = PRODUCT_CODE_PATH_VARIABLE_PATTERN, method = RequestMethod.GET) public String productDetail(@PathVariable("productCode") final String productCode, final Model model, final HttpServletRequest request, final HttpServletResponse response, @CookieValue(value = "lastBrowsedProducts", defaultValue = "") String lastBrowsedProducts) throws CMSItemNotFoundException, UnsupportedEncodingException { // Count of products to be maintained in Cookie final int countOfProducts = 20; System.out.println("praveen cookie value======" + lastBrowsedProducts); if (lastBrowsedProducts.equalsIgnoreCase("")) { lastBrowsedProducts = productCode; } else {/*from w w w . j a v a2s . co m*/ lastBrowsedProducts = listLatestBrowsedProducts(lastBrowsedProducts, productCode, countOfProducts); } final Cookie foo = new Cookie("lastBrowsedProducts", lastBrowsedProducts); foo.setMaxAge(9999999); foo.setPath("/"); response.addCookie(foo); System.out.println("praveen cookie added value------------------" + lastBrowsedProducts); final List<ProductOption> extraOptions = Arrays.asList(ProductOption.VARIANT_MATRIX_BASE, ProductOption.VARIANT_MATRIX_URL, ProductOption.VARIANT_MATRIX_MEDIA); final ProductData productData = productFacade.getProductForCodeAndOptions(productCode, extraOptions); final String redirection = checkRequestUrl(request, response, productDataUrlResolver.resolve(productData)); if (StringUtils.isNotEmpty(redirection)) { return redirection; } updatePageTitle(productCode, model); populateProductDetailForDisplay(productCode, model, request, extraOptions); model.addAttribute(new ReviewForm()); model.addAttribute("pageType", PageType.PRODUCT.name()); model.addAttribute("futureStockEnabled", Boolean.valueOf(Config.getBoolean(FUTURE_STOCK_ENABLED, false))); final String metaKeywords = MetaSanitizerUtil.sanitizeKeywords(productData.getKeywords()); final String metaDescription = MetaSanitizerUtil.sanitizeDescription(productData.getDescription()); setUpMetaData(model, metaKeywords, metaDescription); return getViewForPage(model); }
From source file:com.janrain.backplane2.server.Backplane2Controller.java
private void persistAuthenticatedSession(HttpServletResponse response, String busOwner) throws BackplaneServerException { try {/* ww w.j a v a 2 s .c om*/ String authCookie = ChannelUtil.randomString(AUTH_SESSION_COOKIE_LENGTH); daoFactory.getAuthSessionDAO().persist(new AuthSession(busOwner, authCookie)); response.addCookie(new Cookie(AUTH_SESSION_COOKIE, authCookie)); } catch (SimpleDBException e) { throw new BackplaneServerException(e.getMessage()); } }
From source file:fr.univlille2.ecm.platform.ui.web.auth.cas2.SecurityExceptionHandler.java
@Override public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t) throws IOException, ServletException { @SuppressWarnings("deprecation") Throwable unwrappedException = unwrapException(t); log.debug("handleException#in"); if (!ExceptionHelper.isSecurityError(unwrappedException) && !response.containsHeader(SSO_INITIAL_URL_REQUEST_KEY)) { super.handleException(request, response, t); return;//from w w w. ja v a 2 s . co m } Principal principal = request.getUserPrincipal(); NuxeoPrincipal nuxeoPrincipal = null; if (principal instanceof NuxeoPrincipal) { nuxeoPrincipal = (NuxeoPrincipal) principal; // redirect to login than to requested page if (nuxeoPrincipal.isAnonymous()) { response.resetBuffer(); String urlToReach = getURLToReach(request); log.debug(String.format("handleException#urlToReach#%s", urlToReach)); Cookie cookieUrlToReach = new Cookie(NXAuthConstants.SSO_INITIAL_URL_REQUEST_KEY, urlToReach); cookieUrlToReach.setPath("/"); cookieUrlToReach.setMaxAge(60); response.addCookie(cookieUrlToReach); log.debug(String.format("handleException#cookieUrlToReach#%s", cookieUrlToReach.getName())); if (!response.isCommitted()) { request.getRequestDispatcher(CAS_REDIRECTION_URL).forward(request, response); } FacesContext.getCurrentInstance().responseComplete(); } } // go back to default handler super.handleException(request, response, t); }
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 ww . j a v a 2s . c o m*/ } 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:com.pureinfo.tgirls.sns.servlet.TestSNSEntryServlet.java
@Override protected void doPost(HttpServletRequest _req, HttpServletResponse _resp) throws ServletException, IOException { System.out.println("==================test entry=====POST=============="); try {// w w w . jav a2 s. c om String userId = _req.getParameter("id"); if (StringUtils.isEmpty(userId)) { userId = "1"; } System.out.println("----user id----" + userId); IUserMgr mgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class); User u = mgr.getUserByTaobaoId(userId); System.out.println("user:::;" + u); addCookie(u, _req, _resp); Cookie[] cookies = _req.getCookies(); if (cookies == null) { System.out.println("=====cookie is null======="); } else { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; System.out.println("cookie[" + i + "]:[" + cookie.getName() + ":" + cookie.getValue() + "(" + cookie.getMaxAge() + ")]"); } } int i = new Random().nextInt(); Cookie c = new Cookie("topsessionid", "abc" + i); _resp.addCookie(c); System.out.println("========================"); // Cookie[] cs = _req.getCookies(); // for (int ii = 0; ii < cs.length; ii++) { // Cookie cc = cs[ii]; // System.out.println("cookie[" + cc.getName() + "]:" + cc.getValue()); // } //_resp.sendRedirect(_req.getContextPath() + "/index.html"); RequestDispatcher rd = _req.getRequestDispatcher("/index.html"); rd.forward(_req, _resp); //_req.getSession().setAttribute(ArkHelper.ATTR_LOGIN_USER, u); // _resp.sendRedirect(_req.getContextPath()); // _req.getCookies()[0]. } catch (PureException e) { // TODO Auto-generated catch block e.printStackTrace(System.err); } }
From source file:org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java
/** * Download link and have it be the response. * @param req the http request/* ww w.j a va2 s . co m*/ * @param resp the http response * @param link the link to download * @param c the cookie to set if any * @throws IOException on any error. */ private static void proxyLink(HttpServletRequest req, HttpServletResponse resp, URI link, Cookie c, String proxyHost) throws IOException { org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(link.toString(), false); HttpClientParams params = new HttpClientParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HttpClient client = new HttpClient(params); // Make sure we send the request from the proxy address in the config // since that is what the AM filter checks against. IP aliasing or // similar could cause issues otherwise. HostConfiguration config = new HostConfiguration(); InetAddress localAddress = InetAddress.getByName(proxyHost); if (LOG.isDebugEnabled()) { LOG.debug("local InetAddress for proxy host: " + localAddress.toString()); } config.setLocalAddress(localAddress); HttpMethod method = new GetMethod(uri.getEscapedURI()); @SuppressWarnings("unchecked") Enumeration<String> names = req.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); if (passThroughHeaders.contains(name)) { String value = req.getHeader(name); LOG.debug("REQ HEADER: " + name + " : " + value); method.setRequestHeader(name, value); } } String user = req.getRemoteUser(); if (user != null && !user.isEmpty()) { method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII")); } OutputStream out = resp.getOutputStream(); try { resp.setStatus(client.executeMethod(config, method)); for (Header header : method.getResponseHeaders()) { resp.setHeader(header.getName(), header.getValue()); } if (c != null) { resp.addCookie(c); } InputStream in = method.getResponseBodyAsStream(); if (in != null) { IOUtils.copyBytes(in, out, 4096, true); } } finally { method.releaseConnection(); } }
From source file:de.appsolve.padelcampus.utils.LoginUtil.java
public void deleteLoginCookie(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(COOKIE_LOGIN_TOKEN)) { if (cookie.getValue() != null && cookie.getValue().split(":").length == 2) { LoginCookie loginCookie = loginCookieDAO.findByUUID(cookie.getValue().split(":")[0]); if (loginCookie != null) { loginCookieDAO.deleteById(loginCookie.getId()); break; }// www .ja va2s . com } } } } deleteCookie(request, response, null); deleteCookie(request, response, "/"); deleteCookie(request, response, "/page"); deleteCookie(request, response, "/admin"); deleteCookie(request, response, "/login"); deleteCookie(request, response, "/admin/events"); deleteCookie(request, response, "/admin/events/edit"); deleteCookie(request, response, "/events/event"); Cookie cookie = new Cookie(COOKIE_LOGIN_TOKEN, null); cookie.setDomain(request.getServerName()); cookie.setMaxAge(0); response.addCookie(cookie); }
From source file:com.taobao.ad.easyschedule.exsession.request.session.SessionCookieStore.java
/** * @param response/*ww w. jav a2s . c o m*/ * @param config * @param value * * @throws Exception */ private void saveCookie(HttpServletResponse response, SessionAttributeConfig config, Object value) throws Exception { String cookieName = config.getNickName(); int lifeTime = config.getLifeTime(); //COOKIE String attrValue = getEncodedValue(config, value); Cookie cookie = null; if (attrValue != null) { // if (config.isEncrypt()) { attrValue = URLEncoder.encode(attrValue, "UTF-8"); // } cookie = new Cookie(cookieName, attrValue); } else { cookie = new Cookie(cookieName, ""); } log.debug("cookie name: " + cookieName + " cookie value: " + attrValue); //COOKIE String cookiePath = COOKIE_PATH; if (config.getCookiePath() != null) { cookiePath = config.getCookiePath(); } cookie.setPath(cookiePath); if (lifeTime > 0) { cookie.setMaxAge(lifeTime); } String domain = config.getDomain(); if ((domain != null) && (domain.length() > 0)) { cookie.setDomain(domain); } response.addCookie(cookie); }
From source file:MyServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { Cookie cookie = null;// w ww . j a v a 2s .c om //Get an array of Cookies associated with this domain Cookie[] cookies = request.getCookies(); boolean newCookie = false; //Get the 'mycookie' Cookie if it exists if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("mycookie")) { cookie = cookies[i]; } } //end for } //end if if (cookie == null) { newCookie = true; //Get the cookie's Max-Age from a context-param element //If the 'cookie-age' param is not set properly //then set the cookie to a default of -1, 'never expires' int maxAge; try { maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue(); } catch (Exception e) { maxAge = -1; } //Create the Cookie object cookie = new Cookie("mycookie", "" + getNextCookieValue()); cookie.setPath(request.getContextPath()); cookie.setMaxAge(maxAge); response.addCookie(cookie); } //end if // get some info about the cookie response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Cookie info</title>"); out.println("</head>"); out.println("<body>"); out.println("<h2> Information about the cookie named \"mycookie\"</h2>"); out.println("Cookie value: " + cookie.getValue() + "<br>"); if (newCookie) { out.println("Cookie Max-Age: " + cookie.getMaxAge() + "<br>"); out.println("Cookie Path: " + cookie.getPath() + "<br>"); } out.println("</body>"); out.println("</html>"); out.close(); }
From source file:com.datatorrent.stram.security.StramWSFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest)) { throw new ServletException("This filter only works for HTTP/HTTPS"); }//from w w w. jav a 2s. co m HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpResp = (HttpServletResponse) resp; if (LOG.isDebugEnabled()) { LOG.debug("Remote address for request is: " + httpReq.getRemoteAddr()); } String requestURI = httpReq.getRequestURI(); if (LOG.isDebugEnabled()) { LOG.debug("Request path " + requestURI); } boolean authenticate = true; String user = null; if (getProxyAddresses().contains(httpReq.getRemoteAddr())) { if (httpReq.getCookies() != null) { for (Cookie c : httpReq.getCookies()) { if (WEBAPP_PROXY_USER.equals(c.getName())) { user = c.getValue(); break; } } } if (requestURI.equals(WebServices.PATH) && (user != null)) { String token = createClientToken(user, httpReq.getLocalAddr()); if (LOG.isDebugEnabled()) { LOG.debug("Create token " + token); } Cookie cookie = new Cookie(CLIENT_COOKIE, token); httpResp.addCookie(cookie); } authenticate = false; } if (authenticate) { Cookie cookie = null; if (httpReq.getCookies() != null) { for (Cookie c : httpReq.getCookies()) { if (c.getName().equals(CLIENT_COOKIE)) { cookie = c; break; } } } boolean valid = false; if (cookie != null) { if (LOG.isDebugEnabled()) { LOG.debug("Verifying token " + cookie.getValue()); } user = verifyClientToken(cookie.getValue()); valid = true; if (LOG.isDebugEnabled()) { LOG.debug("Token valid"); } } if (!valid) { httpResp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } } if (user == null) { LOG.warn("Could not find " + WEBAPP_PROXY_USER + " cookie, so user will not be set"); chain.doFilter(req, resp); } else { final StramWSPrincipal principal = new StramWSPrincipal(user); ServletRequest requestWrapper = new StramWSServletRequestWrapper(httpReq, principal); chain.doFilter(requestWrapper, resp); } }