Java Code Examples for javax.servlet.http.Cookie#getMaxAge()
The following examples show how to use
javax.servlet.http.Cookie#getMaxAge() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestCookieProcessorGeneration.java From Tomcat8-Source-Read with MIT License | 6 votes |
private void doTest(Cookie cookie, CookieProcessor cookieProcessor, String expected) { if (expected == null) { IllegalArgumentException e = null; try { cookieProcessor.generateHeader(cookie); } catch (IllegalArgumentException iae) { e = iae; } Assert.assertNotNull("Failed to throw IAE", e); } else { if (cookieProcessor instanceof Rfc6265CookieProcessor && cookie.getMaxAge() > 0) { // Expires attribute will depend on time cookie is generated so // use a modified test Assert.assertTrue(cookieProcessor.generateHeader(cookie).startsWith(expected)); } else { Assert.assertEquals(expected, cookieProcessor.generateHeader(cookie)); } } }
Example 2
Source File: CookieTokenGeneratorDefault.java From stategen with GNU Affero General Public License v3.0 | 6 votes |
/*** * 根据配置的混淆码,以及cookie排序后的值,算出令牌 * @see cn.org.rapid_framework.http.CookieTokenGenerator#genToken(cn.org.rapid_framework.web.AntiCookieFakeResponseWrapper) */ @Override public String genToken(Map<String, Cookie> reuestCookieMap) { StringBuffer sb = new StringBuffer(); int filteredCount =0; if (CollectionUtil.isNotEmpty(reuestCookieMap)){ for (Cookie cookie : reuestCookieMap.values()) { int cookieMaxAge = cookie.getMaxAge(); if (NumberUtil.isNullOrZero(cookieMaxAge)) { continue; } filteredCount++; String cookieValue = cookie.getValue(); sb.append(cookieValue); } } if (NumberUtil.isGreatZero(filteredCount)){ sb.append(Configration.COOKIE_TOKEN_MIX); String tokenValue = MD5Util.md5(sb.toString()); return tokenValue; } return null; }
Example 3
Source File: CookieUtil.java From khan-session with GNU Lesser General Public License v2.1 | 6 votes |
/** * Create Cookie header * * @param cookie * @param isHttpOnly * @return */ public static String createCookieHeader(Cookie cookie, boolean isHttpOnly) { StringBuilder sb = new StringBuilder(); sb = sb.append(cookie.getName()).append("=").append(cookie.getValue()); if (cookie.getDomain() != null && !cookie.getDomain().equals("") ) { sb.append(";Domain=").append(cookie.getDomain()); } if (cookie.getPath() != null && !cookie.getPath().equals("")) { sb.append(";Path=").append(cookie.getPath()); } if (cookie.getComment() != null && !cookie.getComment().equals("")) { sb.append(";Comment=").append(cookie.getComment()); } if (cookie.getMaxAge() > -1) { sb.append(";Max-Age=").append(cookie.getMaxAge()); } if (cookie.getSecure()) { sb.append(";Secure"); } if (isHttpOnly) { sb.append(";HttpOnly"); } return sb.toString(); }
Example 4
Source File: MockHttpServletResponse.java From spring-analysis-note with MIT License | 5 votes |
private String getCookieHeader(Cookie cookie) { StringBuilder buf = new StringBuilder(); buf.append(cookie.getName()).append('=').append(cookie.getValue() == null ? "" : cookie.getValue()); if (StringUtils.hasText(cookie.getPath())) { buf.append("; Path=").append(cookie.getPath()); } if (StringUtils.hasText(cookie.getDomain())) { buf.append("; Domain=").append(cookie.getDomain()); } int maxAge = cookie.getMaxAge(); if (maxAge >= 0) { buf.append("; Max-Age=").append(maxAge); buf.append("; Expires="); HttpHeaders headers = new HttpHeaders(); headers.setExpires(maxAge > 0 ? System.currentTimeMillis() + 1000L * maxAge : 0); buf.append(headers.getFirst(HttpHeaders.EXPIRES)); } if (cookie.getSecure()) { buf.append("; Secure"); } if (cookie.isHttpOnly()) { buf.append("; HttpOnly"); } if (cookie instanceof MockCookie) { MockCookie mockCookie = (MockCookie) cookie; if (StringUtils.hasText(mockCookie.getSameSite())) { buf.append("; SameSite=").append(mockCookie.getSameSite()); } } return buf.toString(); }
Example 5
Source File: ResponseAdaptor.java From velocity-tools with Apache License 2.0 | 5 votes |
protected Object response(Object proxy, Method method, Object[] args) { String methodName = method.getName(); if("encodeURL".equals(methodName) || "encodeUrl".equals(methodName)) { // Don't worry about adding ";jsessionid" or anything. return args[0]; } else if ("addCookie".equals(methodName)) { Cookie c = (Cookie)args[0]; if (c.getMaxAge() == 0) { _params.remove(c.getName()); } else { _params.put(c.getName(), c); } return null; } else if ("getCharacterEncoding".equals(methodName)) { return "UTF-8"; } else if ("toString".equals(methodName)) { return toString(); } else { throw new IllegalStateException("Unexpected method call: " + method); } }
Example 6
Source File: MockHttpServletResponse.java From java-technology-stack with MIT License | 5 votes |
private String getCookieHeader(Cookie cookie) { StringBuilder buf = new StringBuilder(); buf.append(cookie.getName()).append('=').append(cookie.getValue() == null ? "" : cookie.getValue()); if (StringUtils.hasText(cookie.getPath())) { buf.append("; Path=").append(cookie.getPath()); } if (StringUtils.hasText(cookie.getDomain())) { buf.append("; Domain=").append(cookie.getDomain()); } int maxAge = cookie.getMaxAge(); if (maxAge >= 0) { buf.append("; Max-Age=").append(maxAge); buf.append("; Expires="); HttpHeaders headers = new HttpHeaders(); headers.setExpires(maxAge > 0 ? System.currentTimeMillis() + 1000L * maxAge : 0); buf.append(headers.getFirst(HttpHeaders.EXPIRES)); } if (cookie.getSecure()) { buf.append("; Secure"); } if (cookie.isHttpOnly()) { buf.append("; HttpOnly"); } if (cookie instanceof MockCookie) { MockCookie mockCookie = (MockCookie) cookie; if (StringUtils.hasText(mockCookie.getSameSite())) { buf.append("; SameSite=").append(mockCookie.getSameSite()); } } return buf.toString(); }
Example 7
Source File: MockHttpServletResponse.java From java-technology-stack with MIT License | 5 votes |
private String getCookieHeader(Cookie cookie) { StringBuilder buf = new StringBuilder(); buf.append(cookie.getName()).append('=').append(cookie.getValue() == null ? "" : cookie.getValue()); if (StringUtils.hasText(cookie.getPath())) { buf.append("; Path=").append(cookie.getPath()); } if (StringUtils.hasText(cookie.getDomain())) { buf.append("; Domain=").append(cookie.getDomain()); } int maxAge = cookie.getMaxAge(); if (maxAge >= 0) { buf.append("; Max-Age=").append(maxAge); buf.append("; Expires="); HttpHeaders headers = new HttpHeaders(); headers.setExpires(maxAge > 0 ? System.currentTimeMillis() + 1000L * maxAge : 0); buf.append(headers.getFirst(HttpHeaders.EXPIRES)); } if (cookie.getSecure()) { buf.append("; Secure"); } if (cookie.isHttpOnly()) { buf.append("; HttpOnly"); } if (cookie instanceof MockCookie) { MockCookie mockCookie = (MockCookie) cookie; if (StringUtils.hasText(mockCookie.getSameSite())) { buf.append("; SameSite=").append(mockCookie.getSameSite()); } } return buf.toString(); }
Example 8
Source File: WebUtil.java From bbs with GNU Affero General Public License v3.0 | 5 votes |
/** * 获取cookie的存活时间 * @param request * @param name cookie的名称 * @return */ public static int getCookieMaxAge(HttpServletRequest request, String name) { Map<String, Cookie> cookieMap = WebUtil.readCookieMap(request); if(cookieMap.containsKey(name)){//如果存在cookie键的名称 Cookie cookie = (Cookie)cookieMap.get(name);//取得cookie return cookie.getMaxAge(); }else{ return 0; } }
Example 9
Source File: AwsHttpServletResponse.java From aws-serverless-java-container with Apache License 2.0 | 5 votes |
@SuppressFBWarnings("COOKIE_USAGE") @Override public void addCookie(Cookie cookie) { if (request != null && request.getDispatcherType() == DispatcherType.INCLUDE && isCommitted()) { throw new IllegalStateException("Cannot add Cookies for include request when response is committed"); } String cookieData = cookie.getName() + "=" + cookie.getValue(); if (cookie.getPath() != null) { cookieData += "; Path=" + cookie.getPath(); } if (cookie.getSecure()) { cookieData += "; Secure"; } if (cookie.isHttpOnly()) { cookieData += "; HttpOnly"; } if (cookie.getDomain() != null && !"".equals(cookie.getDomain().trim())) { cookieData += "; Domain=" + cookie.getDomain(); } if (cookie.getMaxAge() > 0) { cookieData += "; Max-Age=" + cookie.getMaxAge(); // we always set the timezone to GMT TimeZone gmtTimeZone = TimeZone.getTimeZone(COOKIE_DEFAULT_TIME_ZONE); Calendar currentTimestamp = Calendar.getInstance(gmtTimeZone); currentTimestamp.add(Calendar.SECOND, cookie.getMaxAge()); SimpleDateFormat cookieDateFormatter = new SimpleDateFormat(HEADER_DATE_PATTERN); cookieDateFormatter.setTimeZone(gmtTimeZone); cookieData += "; Expires=" + cookieDateFormatter.format(currentTimestamp.getTime()); } setHeader(HttpHeaders.SET_COOKIE, cookieData, false); }
Example 10
Source File: CookieHelper.java From kisso with Apache License 2.0 | 5 votes |
/** * <p> * 解决 servlet 3.0 以下版本不支持 HttpOnly * </p> * * @param response HttpServletResponse类型的响应 * @param cookie 要设置httpOnly的cookie对象 */ public static void addHttpOnlyCookie(HttpServletResponse response, Cookie cookie) { if (cookie == null) { return; } /** * 依次取得cookie中的名称、值、 最大生存时间、路径、域和是否为安全协议信息 */ String cookieName = cookie.getName(); String cookieValue = cookie.getValue(); int maxAge = cookie.getMaxAge(); String path = cookie.getPath(); String domain = cookie.getDomain(); boolean isSecure = cookie.getSecure(); StringBuffer sf = new StringBuffer(); sf.append(cookieName + "=" + cookieValue + ";"); if (maxAge >= 0) { sf.append("Max-Age=" + cookie.getMaxAge() + ";"); } if (domain != null) { sf.append("domain=" + domain + ";"); } if (path != null) { sf.append("path=" + path + ";"); } if (isSecure) { sf.append("secure;HTTPOnly;"); } else { sf.append("HTTPOnly;"); } response.addHeader("Set-Cookie", sf.toString()); }
Example 11
Source File: CookieSerializer.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
@SuppressWarnings("RedundantIfStatement") static boolean equals(final Cookie thisCookie, final Cookie thatCookie) { if (thisCookie.getMaxAge() != thatCookie.getMaxAge()) { return false; } if (thisCookie.getSecure() != thatCookie.getSecure()) { return false; } if (thisCookie.getVersion() != thatCookie.getVersion()) { return false; } if (thisCookie.getName() != null ? !thisCookie.getName().equals( thatCookie.getName()) : thatCookie.getName() != null) { return false; } if (thisCookie.getValue() != null ? !thisCookie.getValue().equals( thatCookie.getValue()) : thatCookie.getValue() != null) { return false; } if (thisCookie.getComment() != null ? !thisCookie.getComment().equals( thatCookie.getComment()) : thatCookie.getComment() != null) { return false; } if (thisCookie.getDomain() != null ? !thisCookie.getDomain().equals( thatCookie.getDomain()) : thatCookie.getDomain() != null) { return false; } if (thisCookie.getPath() != null ? !thisCookie.getPath().equals( thatCookie.getPath()) : thatCookie.getPath() != null) { return false; } return true; }
Example 12
Source File: ResponseImpl.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 5 votes |
public void setCookieHeader(Cookie cookie) { if (cookie == null) { return; } final StringBuffer header = new StringBuffer(32); String attrValue; int maxAge; header.append(cookie.getName() + "=" + cookie.getValue()); if ((attrValue = cookie.getComment()) != null) { header.append(";Comment=" + attrValue); } if ((attrValue = cookie.getDomain()) != null) { header.append(";Domain=" + attrValue); } if ((maxAge = cookie.getMaxAge()) != -1) { if (maxAge > 0) { appendCookieExpires(header, maxAge); } header.append(";Max-Age=" + maxAge); } if ((attrValue = cookie.getPath()) != null) { header.append(";Path=" + attrValue); } else { header.append(";Path=/"); } if (cookie.getSecure()) { header.append(";Secure"); } header.append(";Version=" + cookie.getVersion()); setHeader("Set-Cookie", header.toString()); }
Example 13
Source File: HttpRequest.java From ICERest with Apache License 2.0 | 4 votes |
public boolean isPersistentCookie(String cookie) { Cookie c = getCookie(request.getCookies(), cookie); return c != null && c.getMaxAge() > 0; }
Example 14
Source File: PxtSessionDelegateImplTest.java From spacewalk with GNU General Public License v2.0 | 4 votes |
@Override protected boolean matchesSafely(Cookie cookie) { return cookie.getMaxAge() == 0; }
Example 15
Source File: RequestUtil.java From olat with Apache License 2.0 | 4 votes |
/** * Encode a cookie as per RFC 2109. The resulting string can be used as the value for a <code>Set-Cookie</code> header. * * @param cookie * The cookie to encode. * @return A string following RFC 2109. */ public static String encodeCookie(Cookie cookie) { StringBuilder buf = new StringBuilder(cookie.getName()); buf.append("="); buf.append(cookie.getValue()); if (cookie.getComment() != null) { buf.append("; Comment=\""); buf.append(cookie.getComment()); buf.append("\""); } if (cookie.getDomain() != null) { buf.append("; Domain=\""); buf.append(cookie.getDomain()); buf.append("\""); } if (cookie.getMaxAge() >= 0) { buf.append("; Max-Age=\""); buf.append(cookie.getMaxAge()); buf.append("\""); } if (cookie.getPath() != null) { buf.append("; Path=\""); buf.append(cookie.getPath()); buf.append("\""); } if (cookie.getSecure()) { buf.append("; Secure"); } if (cookie.getVersion() > 0) { buf.append("; Version=\""); buf.append(cookie.getVersion()); buf.append("\""); } return (buf.toString()); }
Example 16
Source File: RequestUtil.java From olat with Apache License 2.0 | 4 votes |
/** * Encode a cookie as per RFC 2109. The resulting string can be used as the value for a <code>Set-Cookie</code> header. * * @param cookie * The cookie to encode. * @return A string following RFC 2109. */ public static String encodeCookie(Cookie cookie) { StringBuilder buf = new StringBuilder(cookie.getName()); buf.append("="); buf.append(cookie.getValue()); if (cookie.getComment() != null) { buf.append("; Comment=\""); buf.append(cookie.getComment()); buf.append("\""); } if (cookie.getDomain() != null) { buf.append("; Domain=\""); buf.append(cookie.getDomain()); buf.append("\""); } if (cookie.getMaxAge() >= 0) { buf.append("; Max-Age=\""); buf.append(cookie.getMaxAge()); buf.append("\""); } if (cookie.getPath() != null) { buf.append("; Path=\""); buf.append(cookie.getPath()); buf.append("\""); } if (cookie.getSecure()) { buf.append("; Secure"); } if (cookie.getVersion() > 0) { buf.append("; Version=\""); buf.append(cookie.getVersion()); buf.append("\""); } return (buf.toString()); }
Example 17
Source File: RequestUtil.java From openbd-core with GNU General Public License v3.0 | 4 votes |
/** * Encode a cookie as per RFC 2109. The resulting string can be used as the value for a <code>Set-Cookie</code> header. * * @param cookie * The cookie to encode. * @return A string following RFC 2109. */ public static String encodeCookie(Cookie cookie) { StringBuilder buf = new StringBuilder(cookie.getName()); buf.append("="); buf.append(cookie.getValue()); if (cookie.getComment() != null) { buf.append("; Comment=\""); buf.append(cookie.getComment()); buf.append("\""); } if (cookie.getDomain() != null) { buf.append("; Domain=\""); buf.append(cookie.getDomain()); buf.append("\""); } long age = cookie.getMaxAge(); if (cookie.getMaxAge() >= 0) { buf.append("; Max-Age=\""); buf.append(age); buf.append("\""); } if (cookie.getPath() != null) { buf.append("; Path=\""); buf.append(cookie.getPath()); buf.append("\""); } if (cookie.getSecure()) { buf.append("; Secure"); } if (cookie.getVersion() > 0) { buf.append("; Version=\""); buf.append(cookie.getVersion()); buf.append("\""); } return (buf.toString()); }
Example 18
Source File: ApplicationPushBuilder.java From Tomcat8-Source-Read with MIT License | 4 votes |
public ApplicationPushBuilder(Request catalinaRequest, HttpServletRequest request) { baseRequest = request; this.catalinaRequest = catalinaRequest; coyoteRequest = catalinaRequest.getCoyoteRequest(); // Populate the initial list of HTTP headers Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); List<String> values = new ArrayList<>(); headers.put(headerName, values); Enumeration<String> headerValues = request.getHeaders(headerName); while (headerValues.hasMoreElements()) { values.add(headerValues.nextElement()); } } // Remove the headers headers.remove("if-match"); headers.remove("if-none-match"); headers.remove("if-modified-since"); headers.remove("if-unmodified-since"); headers.remove("if-range"); headers.remove("range"); headers.remove("expect"); headers.remove("authorization"); headers.remove("referer"); // Also remove the cookie header since it will be regenerated headers.remove("cookie"); // set the referer header StringBuffer referer = request.getRequestURL(); if (request.getQueryString() != null) { referer.append('?'); referer.append(request.getQueryString()); } addHeader("referer", referer.toString()); // Session Context context = catalinaRequest.getContext(); sessionCookieName = SessionConfig.getSessionCookieName(context); sessionPathParameterName = SessionConfig.getSessionUriParamName(context); HttpSession session = request.getSession(false); if (session != null) { sessionId = session.getId(); } if (sessionId == null) { sessionId = request.getRequestedSessionId(); } if (!request.isRequestedSessionIdFromCookie() && !request.isRequestedSessionIdFromURL() && sessionId != null) { Set<SessionTrackingMode> sessionTrackingModes = request.getServletContext().getEffectiveSessionTrackingModes(); addSessionCookie = sessionTrackingModes.contains(SessionTrackingMode.COOKIE); addSessionPathParameter = sessionTrackingModes.contains(SessionTrackingMode.URL); } else { addSessionCookie = request.isRequestedSessionIdFromCookie(); addSessionPathParameter = request.isRequestedSessionIdFromURL(); } // Cookies if (request.getCookies() != null) { for (Cookie requestCookie : request.getCookies()) { cookies.add(requestCookie); } } for (Cookie responseCookie : catalinaRequest.getResponse().getCookies()) { if (responseCookie.getMaxAge() < 0) { // Path information not available so can only remove based on // name. Iterator<Cookie> cookieIterator = cookies.iterator(); while (cookieIterator.hasNext()) { Cookie cookie = cookieIterator.next(); if (cookie.getName().equals(responseCookie.getName())) { cookieIterator.remove(); } } } else { cookies.add(new Cookie(responseCookie.getName(), responseCookie.getValue())); } } List<String> cookieValues = new ArrayList<>(1); cookieValues.add(generateCookieHeader(cookies, catalinaRequest.getContext().getCookieProcessor())); headers.put("cookie", cookieValues); // Authentication if (catalinaRequest.getPrincipal() != null) { if ((session == null) || catalinaRequest.getSessionInternal(false).getPrincipal() == null || !(context.getAuthenticator() instanceof AuthenticatorBase) || !((AuthenticatorBase) context.getAuthenticator()).getCache()) { // Set a username only if there is no session cache for the principal userName = catalinaRequest.getPrincipal().getName(); } setHeader("authorization", "x-push"); } }
Example 19
Source File: PxtSessionDelegateImplTest.java From uyuni with GNU General Public License v2.0 | 4 votes |
@Override protected boolean matchesSafely(Cookie cookie) { return cookie.getMaxAge() == 0; }
Example 20
Source File: LegacyCookieProcessor.java From Tomcat8-Source-Read with MIT License | 4 votes |
@Override public String generateHeader(Cookie cookie) { /* * The spec allows some latitude on when to send the version attribute * with a Set-Cookie header. To be nice to clients, we'll make sure the * version attribute is first. That means checking the various things * that can cause us to switch to a v1 cookie first. * * Note that by checking for tokens we will also throw an exception if a * control character is encountered. */ int version = cookie.getVersion(); String value = cookie.getValue(); String path = cookie.getPath(); String domain = cookie.getDomain(); String comment = cookie.getComment(); if (version == 0) { // Check for the things that require a v1 cookie if (needsQuotes(value, 0) || comment != null || needsQuotes(path, 0) || needsQuotes(domain, 0)) { version = 1; } } // Now build the cookie header StringBuffer buf = new StringBuffer(); // can't use StringBuilder due to DateFormat // Just use the name supplied in the Cookie buf.append(cookie.getName()); buf.append("="); // Value maybeQuote(buf, value, version); // Add version 1 specific information if (version == 1) { // Version=1 ... required buf.append ("; Version=1"); // Comment=comment if (comment != null) { buf.append ("; Comment="); maybeQuote(buf, comment, version); } } // Add domain information, if present if (domain != null) { buf.append("; Domain="); maybeQuote(buf, domain, version); } // Max-Age=secs ... or use old "Expires" format int maxAge = cookie.getMaxAge(); if (maxAge >= 0) { if (version > 0) { buf.append ("; Max-Age="); buf.append (maxAge); } // IE6, IE7 and possibly other browsers don't understand Max-Age. // They do understand Expires, even with V1 cookies! if (version == 0 || getAlwaysAddExpires()) { // Wdy, DD-Mon-YY HH:MM:SS GMT ( Expires Netscape format ) buf.append ("; Expires="); // To expire immediately we need to set the time in past if (maxAge == 0) { buf.append( ANCIENT_DATE ); } else { COOKIE_DATE_FORMAT.get().format( new Date(System.currentTimeMillis() + maxAge * 1000L), buf, new FieldPosition(0)); } } } // Path=path if (path!=null) { buf.append ("; Path="); maybeQuote(buf, path, version); } // Secure if (cookie.getSecure()) { buf.append ("; Secure"); } // HttpOnly if (cookie.isHttpOnly()) { buf.append("; HttpOnly"); } SameSiteCookies sameSiteCookiesValue = getSameSiteCookies(); if (!sameSiteCookiesValue.equals(SameSiteCookies.UNSET)) { buf.append("; SameSite="); buf.append(sameSiteCookiesValue.getValue()); } return buf.toString(); }