List of usage examples for javax.servlet.http Cookie setMaxAge
public void setMaxAge(int expiry)
From source file:com.google.gsa.Kerberos.java
/** * Creates the referer cookie//from w w w.java 2 s .co m * */ private void createRefererCookie(Cookie gsaRefererCookie) { // Instantiate authentication cookie with default value gsaRefererCookie = new Cookie(refererCookieName, valveConf.getTestFormsCrawlUrl()); // Set cookie domain gsaRefererCookie.setDomain(authCookieDomain); // Set cookie path gsaRefererCookie.setPath(authCookiePath); // Set expiration time gsaRefererCookie.setMaxAge(authMaxAge); }
From source file:fi.hoski.web.forms.RaceEntryServlet.java
/** * Handles the HTTP/* w w w . ja v a 2 s. c o m*/ * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String raceFleetKeyStr = request.getParameter("RaceFleetKey"); if (raceFleetKeyStr == null) { throw new ServletException("no RaceFleetKey"); } Key raceFleetKey = KeyFactory.stringToKey(raceFleetKeyStr); Entity raceFleetEntity = datastore.get(raceFleetKey); Key raceSeriesKey = raceFleetKey.getParent(); Entity raceseriesEntity = datastore.get(raceSeriesKey); RaceSeries raceSeries = (RaceSeries) entities.newInstance(raceseriesEntity); RaceFleet raceFleet = (RaceFleet) entities.newInstance(raceFleetEntity); RaceEntry raceEntry = new RaceEntry(raceFleet); raceEntry.populate(request.getParameterMap()); String fn = request.getParameter(RaceEntry.FIRSTNAME); String ln = request.getParameter(RaceEntry.LASTNAME); raceEntry.set(RaceEntry.HELMNAME, fn + " " + ln); String sa = request.getParameter(RaceEntry.STREETADDRESS); String zc = request.getParameter(RaceEntry.ZIPCODE); String ct = request.getParameter(RaceEntry.CITY); String cn = request.getParameter(RaceEntry.COUNTRY); if (cn == null || cn.isEmpty()) { raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct); } else { raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct + ", " + cn); } Day closingDay = (Day) raceSeries.get(RaceSeries.ClosingDate); Number fee = 0.0; if (closingDay != null) { Day now = new Day(); if (closingDay.before(now)) { fee = (Number) raceFleet.get(RaceFleet.Fee2); } else { fee = (Number) raceFleet.get(RaceFleet.Fee); } } Boolean clubDiscount = (Boolean) raceSeries.get(RaceSeries.CLUBDISCOUNT); String clubname = repositoryBundle.getString("Clubname"); if (clubDiscount != null && clubDiscount && clubname.equalsIgnoreCase("" + raceEntry.get(RaceEntry.CLUB))) { fee = new Double(0); } raceEntry.set(RaceEntry.FEE, fee); raceEntry.set(RaceEntry.TIMESTAMP, new Date()); entities.put(raceEntry); String payingInstructions = ""; String payingInstructionsHtml = ""; BankingBarcode bb = races.getBarcode(raceEntry); if (bb != null) { Day dueDay = new Day(bb.getDueDate()); String payingFormat = EntityReferences.encode(msg(Messages.RACEENTRYPAYING), "UTF-8"); String bic = EntityReferences.encode(msg(Messages.RACEBIC), "UTF-8"); payingInstructions = String.format(payingFormat, bb.toString(), // 1 = barcode bb.getAccount().getIBAN(), // 2 = account bb.getReference().toFormattedRFString(), // 3 = ref dueDay, // 4 = due date String.format("%.2f", bb.getTotal()), // 5 = total bic // 6 = bic ); payingInstructionsHtml = String.format(payingFormat.replace("\n", "<br>"), "<span id='barcode'>" + bb.toString() + "</span>", // 1 = barcode "<span id='iban'>" + bb.getAccount().getIBAN() + "</span>", // 2 = account "<span id='rf'>" + bb.getReference().toFormattedRFString() + "</span>", // 3 = ref "<span id='due'>" + dueDay + "</span>", // 4 = due date "<span id='fee'>" + String.format("%.2f", bb.getTotal()) + "</span>", // 5 = total "<span id='bic'>" + bic + "</span>" // 6 = bic ); } URL base = new URL(request.getRequestURL().toString()); URL barcodeUrl = new URL(base, "/races/code128.html?ancestor=" + raceEntry.createKeyString()); String name = (String) raceEntry.get(RaceEntry.HELMNAME); String email = (String) raceEntry.get(RaceEntry.HELMEMAIL); String confirmation = msg(Messages.RACEENTRYCONFIRMATION); String plainMessage = ""; String htmlMessage = "<html><head></head><body>" + EntityReferences.encode(confirmation) + payingInstructionsHtml + raceEntry.getFieldsAsHtmlTable() + "<iframe src=" + barcodeUrl.toString() + "/>" + "</body></html>"; if (email != null) { InternetAddress recipient = new InternetAddress(email, name); String senderStr = msg(Messages.RACEENTRYFROMADDRESS); InternetAddress sender; try { sender = new InternetAddress(senderStr); plainMessage = confirmation + "\n" + payingInstructions + "\n" + raceEntry.getFields(); String subject = msg(Messages.RACEENTRYSUBJECT); mailService.sendMail(sender, subject, plainMessage, htmlMessage, recipient); } catch (Exception ex) { log(senderStr, ex); } } Cookie cookie = null; Cookie[] cookies = null; if (useCookies) { cookies = request.getCookies(); } if (cookies != null) { for (Cookie ck : cookies) { if (COOKIENAME.equals(ck.getName())) { cookie = ck; } } } JSONObject json = null; if (useCookies && cookie != null) { Base64 decoder = new Base64(); String str = new String(decoder.decode(cookie.getValue())); json = new JSONObject(str); } else { json = new JSONObject(); } for (Map.Entry<String, String[]> entry : ((Map<String, String[]>) request.getParameterMap()) .entrySet()) { String property = entry.getKey(); String[] values = entry.getValue(); if (values.length == 1) { json.put(property, values[0]); } } Base64 encoder = new Base64(); String base64 = encoder.encodeAsString(json.toString().getBytes("UTF-8")); if (useCookies) { if (cookie == null) { cookie = new Cookie(COOKIENAME, base64); cookie.setPath("/"); cookie.setMaxAge(400 * 24 * 60 * 60); } else { cookie.setValue(base64); } response.addCookie(cookie); } sendError(response, HttpServletResponse.SC_OK, "<div id=\"" + raceEntry.createKeyString() + "\">Ok</div>"); } catch (JSONException ex) { log(ex.getMessage(), ex); sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "<div id=\"eJSON\">Internal error.</div>"); } catch (EntityNotFoundException ex) { log(ex.getMessage(), ex); sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "<div id=\"eEntityNotFound\">Internal error.</div>"); } catch (NumberFormatException ex) { log(ex.getMessage(), ex); sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eNumberFormat\">Number error.</div>"); } }
From source file:com.jsmartframework.web.manager.BeanHandler.java
private Cookie getAuthenticationCookie(HttpServletRequest request, String name, String value, int age) { Cookie cookie = new Cookie(name, value); cookie.setHttpOnly(true);//from w w w . j ava2s .co m cookie.setPath("/"); cookie.setMaxAge(age); return cookie; }
From source file:com.twelve.capital.external.feed.util.HttpImpl.java
protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) { Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue()); if (!PropsValues.SESSION_COOKIE_USE_FULL_HOSTNAME) { String domain = commonsCookie.getDomain(); if (Validator.isNotNull(domain)) { cookie.setDomain(domain);/*from ww w. j a v a 2s . co m*/ } } Date expiryDate = commonsCookie.getExpiryDate(); if (expiryDate != null) { int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis()); maxAge = maxAge / 1000; if (maxAge > -1) { cookie.setMaxAge(maxAge); } } String path = commonsCookie.getPath(); if (Validator.isNotNull(path)) { cookie.setPath(path); } cookie.setSecure(commonsCookie.getSecure()); cookie.setVersion(commonsCookie.getVersion()); return cookie; }
From source file:logout2_servlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww .j a v a 2 s .com*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String access_token = ""; Cookie cookie = null; Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { Cookie cookie1 = cookies[i]; if (cookies[i].getName().equals("access_token")) { access_token = cookie1.getValue(); cookie = cookie1; } } System.out.println("TOKEN = " + access_token); String USER_AGENT = "Mozilla/5.0"; String url = "http://localhost:8082/Identity_Service/logout_servlet"; URL connection = new URL(url); HttpURLConnection con = (HttpURLConnection) connection.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "access_token=" + access_token; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder resp = new StringBuilder(); while ((inputLine = in.readLine()) != null) { resp.append(inputLine); } in.close(); JSONParser parser = new JSONParser(); JSONObject obj = null; try { obj = (JSONObject) parser.parse(resp.toString()); } catch (ParseException ex) { Logger.getLogger(logout2_servlet.class.getName()).log(Level.SEVERE, null, ex); } String status = (String) obj.get("status"); System.out.println(status); if (status.equals("ok")) { cookie.setMaxAge(0); response.sendRedirect("login.jsp"); } else { } }
From source file:com.google.gsa.Kerberos.java
/** * Setting the authentication cookie and the user session * //from w ww. j a v a 2 s. c o m * @param username username * @param creationTime creation time * @param encodedSessionID encoded session id * * @return if the setting process was successful */ private boolean settingSession(UserSession userSession, Cookie gsaAuthCookie, Credentials creds, String username, KerberosAuthenticationProcess krbAuthN, long creationTime, String encodedSessionID, Vector<Cookie> krbCookies, Vector<Cookie> nonKrbCookies) { boolean result = false; logger.debug("Creating auth cookie with value: " + encodedSessionID); // Instantiate authentication cookie with default value gsaAuthCookie = new Cookie(authCookieName, encodedSessionID); // Set cookie domain gsaAuthCookie.setDomain(authCookieDomain); // Set cookie path gsaAuthCookie.setPath(authCookiePath); // Set expiration time gsaAuthCookie.setMaxAge(authMaxAge); logger.debug("Creating Session"); userSession.setUserName(username); userSession.setSessionCreationTime(creationTime); userSession.setSessionLastAccessTime(creationTime); userSession.setUserCredentials(creds); //Cookies settingSessionCookies(krbCookies, nonKrbCookies, gsaAuthCookie, userSession); if (krbAuthN.getUserSubject() != null) { logger.debug("Kerberos Subject exists"); userSession.setKerberosCredentials(krbAuthN.getUserSubject()); result = true; } else { // Log error logger.error("Kerberos Subject has not been created properly"); // Return return result; } return result; }
From source file:org.apache.coyote.tomcat5.CoyoteRequest.java
/** * Configures the given JSESSIONID cookie. * * @param cookie The JSESSIONID cookie to be configured *//* w w w.j a va 2 s .c om*/ protected void configureSessionCookie(Cookie cookie) { cookie.setMaxAge(-1); String contextPath = null; if (getContext() != null) { contextPath = getContext().getPath(); } if ((contextPath != null) && (contextPath.length() > 0)) { cookie.setPath(contextPath); } else { cookie.setPath("/"); } if (isSecure()) { cookie.setSecure(true); } }
From source file:com.ssbusy.controller.catalog.CategoryController.java
@Override @SuppressWarnings("unchecked") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(); MyCustomer customer = (MyCustomer) CustomerState.getCustomer(); HttpSession session = request.getSession(); MyOfferCode myOfferCode = (MyOfferCode) session.getAttribute("bonusOfferCode"); Boolean w_flag = Boolean.FALSE; // cookies/*from w w w. ja v a2s . co m*/ String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()); int count = 0;// ?? Cookie cookies[] = request.getCookies(); Boolean uiv2 = null; if (cookies != null) { for (Cookie c : cookies) { if (dateTime.equals(c.getName())) { count = Integer.valueOf(c.getValue()); break; // } else if ("uiv2".equals(c.getName())) { // uiv2 = Boolean.valueOf(c.getValue()); // 2 cookie } } } if (cookies != null) { for (Cookie c : cookies) { if ("SPRING_SECURITY_REMEMBER_ME_COOKIE".equals(c.getName())) { model.addObject("rember", c.getValue()); break; } } } // String uiParam = request.getParameter("uiv2"); // if (StringUtils.isNotEmpty(uiParam)) { // 1 param // uiv2 = Boolean.valueOf(uiParam); // Cookie c = new Cookie("uiv2", uiv2.toString()); // c.setPath("/"); // c.setMaxAge(60 * 60 * 24 * 360); // response.addCookie(c); // } else if (uiv2 == null) { uiv2 = Boolean.TRUE; // 3 default. // } session.setAttribute("uiv2", uiv2); // LOG.warn("uiv2=" + uiv2); if (myOfferCode != null) { if (customer.isRegistered()) giftService.updateOwnerCustomer(customer, myOfferCode); else myOfferCode = null; } else if (count < maxoffercodeCount) { myOfferCode = giftService.getgift(customer); if (myOfferCode != null) { if (customer.isAnonymous()) { session.setAttribute("bonusOfferCode", myOfferCode); model.addObject("bonusOfferCode", myOfferCode); myOfferCode = null; } } } if (myOfferCode != null) { session.removeAttribute("bonusOfferCode"); model.addObject("bonusOfferCode", myOfferCode); Cookie c = new Cookie(dateTime, String.valueOf(count + 1)); c.setPath("/"); c.setMaxAge(60 * 60 * 24); response.addCookie(c); LOG.info("offerCode sent, id=" + myOfferCode.getId() + ", ip=" + request.getRemoteAddr()); } if (request.getParameterMap().containsKey("facetField")) { // If we receive a facetField parameter, we need to convert the // field to the // product search criteria expected format. This is used in // multi-facet selection. We // will send a redirect to the appropriate URL to maintain canonical // URLs String fieldName = request.getParameter("facetField"); List<String> activeFieldFilters = new ArrayList<String>(); Map<String, String[]> parameters = new HashMap<String, String[]>(request.getParameterMap()); for (Iterator<Entry<String, String[]>> iter = parameters.entrySet().iterator(); iter.hasNext();) { Map.Entry<String, String[]> entry = iter.next(); String key = entry.getKey(); if (key.startsWith(fieldName + "-")) { activeFieldFilters.add(key.substring(key.indexOf('-') + 1)); iter.remove(); } } parameters.remove(ProductSearchCriteria.PAGE_NUMBER); parameters.put(fieldName, activeFieldFilters.toArray(new String[activeFieldFilters.size()])); parameters.remove("facetField"); String newUrl = ProcessorUtils.getUrl(request.getRequestURL().toString(), parameters); model.setViewName("redirect:" + newUrl); } else { // Else, if we received a GET to the category URL (either the user // clicked this link or we redirected // from the POST method, we can actually process the results Category category = (Category) request .getAttribute(CategoryHandlerMapping.CURRENT_CATEGORY_ATTRIBUTE_NAME); assert (category != null); List<SearchFacetDTO> availableFacets = searchService.getCategoryFacets(category); ProductSearchCriteria searchCriteria = facetService.buildSearchCriteria(request, availableFacets); String searchTerm = request.getParameter(ProductSearchCriteria.QUERY_STRING); ProductSearchResult result; List<FulfillmentLocation> locations = null; try { // if (customer != null && customer.getRegion() != null) { InventorySolrSearchServiceExtensionHandler.customerLocation .set(locations = customer.getRegion().getFulfillmentLocations()); } if (StringUtils.isNotBlank(searchTerm)) { result = searchService.findProductsByCategoryAndQuery(category, searchTerm, searchCriteria); } else { result = searchService.findProductsByCategory(category, searchCriteria); } } finally { InventorySolrSearchServiceExtensionHandler.customerLocation.remove(); } facetService.setActiveFacetResults(result.getFacets(), request); List<Product> products = result.getProducts(); if (products != null && products.size() > 0) { List<String> prodIds = new ArrayList<String>(products.size()); for (Product product : products) { prodIds.add(String.valueOf(product.getId())); } model.addObject("ratingSums", ratingService.readRatingSummaries(prodIds, RatingType.PRODUCT)); // ?productinventories if (locations != null) { Map<Product, List<Inventory>> invs = inventoryService.listAllInventories(products, locations); model.addObject("inventories", invs); } } model.addObject(PRODUCTS_ATTRIBUTE_NAME, products); model.addObject(CATEGORY_ATTRIBUTE_NAME, category); // facets List<SearchFacetDTO> facets = result.getFacets(); if (facets != null) { _nextFact: for (Iterator<SearchFacetDTO> itr = facets.iterator(); itr.hasNext();) { SearchFacetDTO dto = itr.next(); if (dto != null && dto.getFacetValues() != null) { for (SearchFacetResultDTO searchFacetDTO : dto.getFacetValues()) { if (searchFacetDTO != null) if (searchFacetDTO.getQuantity() != null && searchFacetDTO.getQuantity() > 0) continue _nextFact; } } itr.remove(); } model.addObject(FACETS_ATTRIBUTE_NAME, result.getFacets()); } model.addObject(PRODUCT_SEARCH_RESULT_ATTRIBUTE_NAME, result); // TODO temp String view = category.getDisplayTemplate(); if (StringUtils.isEmpty(view)) view = getDefaultCategoryView(); if (request.getRequestURI().startsWith("/weixin/")) { view = "weixin/catalog/w_category_item"; w_flag = Boolean.TRUE; } if (uiv2) { if ("layout/home".equals(view)) view = "v2/home"; else { if (!view.startsWith("activity") && !view.startsWith("weixin/")) { view = "v2/" + view; } } } session.setAttribute("w_flag", w_flag); model.setViewName(view); } // if (isAjaxRequest(request)) { // model.setViewName(RETURN_PRODUCT_WATERFALL_ITEM); // model.addObject("ajax", Boolean.TRUE); // } return model; }