下面列出了javax.servlet.http.Cookie#setComment() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Clears cookie, session, context and sets response code
*
* @param httpServletRequest Http request
* @param httpServletResponse Http response
* @param authentication Valid authentication
*/
@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Authentication authentication) {
HttpSession session = httpServletRequest.getSession(false);
if (session != null) {
session.invalidate();
}
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
// Set the cookie to null and expired
Cookie tokenCookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), null);
tokenCookie.setPath(authConfigurationProperties.getCookieProperties().getCookiePath());
tokenCookie.setComment(authConfigurationProperties.getCookieProperties().getCookieComment());
tokenCookie.setSecure(true);
tokenCookie.setHttpOnly(true);
tokenCookie.setMaxAge(0);
httpServletResponse.addCookie(tokenCookie);
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(null);
SecurityContextHolder.clearContext();
}
@Override
public Cookie[] getCookies() {
String cookieString = this.request.headers().get(COOKIE);
if (cookieString != null) {
Set<io.netty.handler.codec.http.Cookie> cookies = CookieDecoder.decode(cookieString);
if (!cookies.isEmpty()) {
Cookie[] cookiesArray = new Cookie[cookies.size()];
int indx = 0;
for (io.netty.handler.codec.http.Cookie c : cookies) {
Cookie cookie = new Cookie(c.getName(), c.getValue());
cookie.setComment(c.getComment());
cookie.setDomain(c.getDomain());
cookie.setMaxAge((int) c.getMaxAge());
cookie.setPath(c.getPath());
cookie.setSecure(c.isSecure());
cookie.setVersion(c.getVersion());
cookiesArray[indx] = cookie;
indx++;
}
return cookiesArray;
}
}
return new Cookie[0];
}
/**
* Copy cookie from the proxy to the servlet client. Replaces cookie path to local path and renames cookie to avoid
* collisions.
*/
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);
}
}
/**
* Copy cookie from the proxy to the servlet client.
* Replaces cookie path to local path and renames cookie to avoid collisions.
*/
@Override
protected void copyProxyCookie(HttpServletRequest servletRequest,
HttpServletResponse servletResponse, String headerValue) {
List<HttpCookie> cookies = HttpCookie.parse(headerValue);
String path = servletRequest.getContextPath(); // path starts with / or is empty string
path += servletRequest.getServletPath(); // servlet path starts with / or is empty string
if (path.isEmpty()) {
path = "/";
}
for (HttpCookie cookie : cookies) {
//set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
String cookieName = doPreserveCookies ? cookie.getName() : getCookieNamePrefix(cookie.getName()) + cookie.getName();
Cookie servletCookie = new Cookie(cookieName, cookie.getValue());
servletCookie.setComment(cookie.getComment());
servletCookie.setMaxAge((int) cookie.getMaxAge());
//fix: preserve path when preserving cookies
String cookiePath = doPreserveCookies ? cookie.getPath() : path;
servletCookie.setPath(cookiePath); //set to the path of the proxy servlet
// don't set cookie domain
servletCookie.setSecure(cookie.getSecure());
servletCookie.setVersion(cookie.getVersion());
servletResponse.addCookie(servletCookie);
}
}
protected Cookie createSnapshotCookie(Cookie src) {
// not use close() to avoid dependency to ServletContainer
final Cookie snapshot = new Cookie(src.getName(), src.getValue());
snapshot.setPath(src.getPath());
snapshot.setMaxAge(src.getMaxAge());
final String domain = src.getDomain();
if (domain != null) { // the setter has filter process
snapshot.setDomain(domain);
}
snapshot.setSecure(src.getSecure());
final String comment = src.getComment();
if (comment != null) { // just in case
snapshot.setComment(comment);
}
snapshot.setVersion(src.getVersion());
snapshot.setHttpOnly(src.isHttpOnly());
return snapshot;
}
public static Cookie convert(org.jboss.netty.handler.codec.http.Cookie nettyCookie){
Cookie servletCookie = new Cookie(nettyCookie.getName(),nettyCookie.getValue());
servletCookie.setDomain(nettyCookie.getDomain());
servletCookie.setMaxAge(nettyCookie.getMaxAge());
servletCookie.setHttpOnly(nettyCookie.isHttpOnly());
servletCookie.setPath(nettyCookie.getPath());
servletCookie.setSecure(nettyCookie.isSecure());
servletCookie.setVersion(nettyCookie.getVersion());
servletCookie.setComment(nettyCookie.getComment());
return servletCookie;
}
/**
* Add the cookie to the response
*
* @param token the authentication token
* @param response send back this response
*/
private void setCookie(String token, HttpServletResponse response) {
Cookie tokenCookie = new Cookie(authConfigurationProperties.getCookieProperties().getCookieName(), token);
tokenCookie.setComment(authConfigurationProperties.getCookieProperties().getCookieComment());
tokenCookie.setPath(authConfigurationProperties.getCookieProperties().getCookiePath());
tokenCookie.setHttpOnly(true);
tokenCookie.setMaxAge(authConfigurationProperties.getCookieProperties().getCookieMaxAge());
tokenCookie.setSecure(authConfigurationProperties.getCookieProperties().isCookieSecure());
response.addCookie(tokenCookie);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
Cookie[] requestCookies = request.getCookies();
out.write("<html><head></head><body>");
out.write("<h3>Hello Browser!!</h3>");
if(requestCookies != null){
out.write("<h3>Request Cookies:</h3>");
for(Cookie c : requestCookies){
out.write("Name="+c.getName()+", Value="+c.getValue()+", Comment="+c.getComment()
+", Domain="+c.getDomain()+", MaxAge="+c.getMaxAge()+", Path="+c.getPath()
+", Version="+c.getVersion());
out.write("<br>");
}
}
//Set cookies for counter, accessible to only this servlet
count++;
Cookie counterCookie = new Cookie("Counter", String.valueOf(count));
//add some description to be viewed in browser cookie viewer
counterCookie.setComment("SetCookie Counter");
//setting max age to be 1 day
counterCookie.setMaxAge(24*60*60);
//set path to make it accessible to only this servlet
counterCookie.setPath("/ServletCookie/cookie/SetCookie");
//adding cookie to the response
response.addCookie(counterCookie);
//set a domain specific cookie
Cookie domainCookie = new Cookie("Test", "Test Cookie"+String.valueOf(count));
domainCookie.setComment("Test Cookie");
response.addCookie(domainCookie);
out.write("</body></html>");
}
protected void addCookie(final HttpServletResponse resp, final Map.Entry<String, NewCookie> cookie) {
final NewCookie nc = cookie.getValue();
final Cookie servletCookie = new Cookie(cookie.getKey(), nc.getValue());
servletCookie.setComment(nc.getComment());
if (nc.getDomain() != null) {
servletCookie.setDomain(nc.getDomain());
}
servletCookie.setHttpOnly(nc.isHttpOnly());
servletCookie.setSecure(nc.isSecure());
servletCookie.setMaxAge(nc.getMaxAge());
servletCookie.setPath(nc.getPath());
servletCookie.setVersion(nc.getVersion());
resp.addCookie(servletCookie);
}
private static Cookie mapCookie ( final Map.Entry<String, NewCookie> entry )
{
final String name = entry.getKey ();
final NewCookie nc = entry.getValue ();
final Cookie cookie = new Cookie ( name, nc.getValue () );
cookie.setComment ( nc.getComment () );
cookie.setDomain ( nc.getDomain () );
cookie.setHttpOnly ( nc.isHttpOnly () );
cookie.setMaxAge ( nc.getMaxAge () );
cookie.setPath ( nc.getPath () );
cookie.setSecure ( nc.isSecure () );
cookie.setVersion ( nc.getVersion () );
return cookie;
}
/**
* Converts the parsed cookies (parsing the Cookie headers first if they
* have not been parsed) into Cookie objects.
*/
protected void convertCookies() {
if (cookiesConverted) {
return;
}
cookiesConverted = true;
if (getContext() == null) {
return;
}
parseCookies();
ServerCookies serverCookies = coyoteRequest.getCookies();
CookieProcessor cookieProcessor = getContext().getCookieProcessor();
int count = serverCookies.getCookieCount();
if (count <= 0) {
return;
}
cookies = new Cookie[count];
int idx=0;
for (int i = 0; i < count; i++) {
ServerCookie scookie = serverCookies.getCookie(i);
try {
// We must unescape the '\\' escape character
Cookie cookie = new Cookie(scookie.getName().toString(),null);
int version = scookie.getVersion();
cookie.setVersion(version);
scookie.getValue().getByteChunk().setCharset(cookieProcessor.getCharset());
cookie.setValue(unescape(scookie.getValue().toString()));
cookie.setPath(unescape(scookie.getPath().toString()));
String domain = scookie.getDomain().toString();
if (domain!=null) {
cookie.setDomain(unescape(domain));//avoid NPE
}
String comment = scookie.getComment().toString();
cookie.setComment(version==1?unescape(comment):null);
cookies[idx++] = cookie;
} catch(IllegalArgumentException e) {
// Ignore bad cookie
}
}
if( idx < count ) {
Cookie [] ncookies = new Cookie[idx];
System.arraycopy(cookies, 0, ncookies, 0, idx);
cookies = ncookies;
}
}
/**
* Creates a new session cookie for the given session ID
*
* @param context The Context for the web application
* @param sessionId The ID of the session for which the cookie will be
* created
* @param secure Should session cookie be configured as secure
* @return the cookie for the session
*/
public static Cookie createSessionCookie(Context context,
String sessionId, boolean secure) {
SessionCookieConfig scc =
context.getServletContext().getSessionCookieConfig();
// NOTE: The priority order for session cookie configuration is:
// 1. Context level configuration
// 2. Values from SessionCookieConfig
// 3. Defaults
Cookie cookie = new Cookie(
SessionConfig.getSessionCookieName(context), sessionId);
// Just apply the defaults.
cookie.setMaxAge(scc.getMaxAge());
cookie.setComment(scc.getComment());
if (context.getSessionCookieDomain() == null) {
// Avoid possible NPE
if (scc.getDomain() != null) {
cookie.setDomain(scc.getDomain());
}
} else {
cookie.setDomain(context.getSessionCookieDomain());
}
// Always set secure if the request is secure
if (scc.isSecure() || secure) {
cookie.setSecure(true);
}
// Always set httpOnly if the context is configured for that
if (scc.isHttpOnly() || context.getUseHttpOnly()) {
cookie.setHttpOnly(true);
}
cookie.setPath(SessionConfig.getSessionCookiePath(context));
return cookie;
}
@Test
@SuppressWarnings("deprecation")
public void printResponse() throws Exception {
Cookie enigmaCookie = new Cookie("enigma", "42");
enigmaCookie.setComment("This is a comment");
enigmaCookie.setHttpOnly(true);
enigmaCookie.setMaxAge(1234);
enigmaCookie.setDomain(".example.com");
enigmaCookie.setPath("/crumbs");
enigmaCookie.setSecure(true);
this.response.setStatus(400, "error");
this.response.addHeader("header", "headerValue");
this.response.setContentType("text/plain");
this.response.getWriter().print("content");
this.response.setForwardedUrl("redirectFoo");
this.response.sendRedirect("/redirectFoo");
this.response.addCookie(new Cookie("cookie", "cookieValue"));
this.response.addCookie(enigmaCookie);
this.handler.handle(this.mvcResult);
// Manually validate cookie values since maxAge changes...
List<String> cookieValues = this.response.getHeaders("Set-Cookie");
assertEquals(2, cookieValues.size());
assertEquals("cookie=cookieValue", cookieValues.get(0));
assertTrue("Actual: " + cookieValues.get(1), cookieValues.get(1).startsWith(
"enigma=42; Path=/crumbs; Domain=.example.com; Max-Age=1234; Expires="));
HttpHeaders headers = new HttpHeaders();
headers.set("header", "headerValue");
headers.setContentType(MediaType.TEXT_PLAIN);
headers.setLocation(new URI("/redirectFoo"));
headers.put("Set-Cookie", cookieValues);
String heading = "MockHttpServletResponse";
assertValue(heading, "Status", this.response.getStatus());
assertValue(heading, "Error message", response.getErrorMessage());
assertValue(heading, "Headers", headers);
assertValue(heading, "Content type", this.response.getContentType());
assertValue(heading, "Body", this.response.getContentAsString());
assertValue(heading, "Forwarded URL", this.response.getForwardedUrl());
assertValue(heading, "Redirected URL", this.response.getRedirectedUrl());
Map<String, Map<String, Object>> printedValues = this.handler.getPrinter().printedValues;
String[] cookies = (String[]) printedValues.get(heading).get("Cookies");
assertEquals(2, cookies.length);
String cookie1 = cookies[0];
String cookie2 = cookies[1];
assertTrue(cookie1.startsWith("[" + Cookie.class.getSimpleName()));
assertTrue(cookie1.contains("name = 'cookie', value = 'cookieValue'"));
assertTrue(cookie1.endsWith("]"));
assertTrue(cookie2.startsWith("[" + Cookie.class.getSimpleName()));
assertTrue(cookie2.contains("name = 'enigma', value = '42', " +
"comment = 'This is a comment', domain = '.example.com', maxAge = 1234, " +
"path = '/crumbs', secure = true, version = 0, httpOnly = true"));
assertTrue(cookie2.endsWith("]"));
}
@Test
@SuppressWarnings("deprecation")
public void printResponse() throws Exception {
Cookie enigmaCookie = new Cookie("enigma", "42");
enigmaCookie.setComment("This is a comment");
enigmaCookie.setHttpOnly(true);
enigmaCookie.setMaxAge(1234);
enigmaCookie.setDomain(".example.com");
enigmaCookie.setPath("/crumbs");
enigmaCookie.setSecure(true);
this.response.setStatus(400, "error");
this.response.addHeader("header", "headerValue");
this.response.setContentType("text/plain");
this.response.getWriter().print("content");
this.response.setForwardedUrl("redirectFoo");
this.response.sendRedirect("/redirectFoo");
this.response.addCookie(new Cookie("cookie", "cookieValue"));
this.response.addCookie(enigmaCookie);
this.handler.handle(this.mvcResult);
// Manually validate cookie values since maxAge changes...
List<String> cookieValues = this.response.getHeaders("Set-Cookie");
assertEquals(2, cookieValues.size());
assertEquals("cookie=cookieValue", cookieValues.get(0));
assertTrue("Actual: " + cookieValues.get(1), cookieValues.get(1).startsWith(
"enigma=42; Path=/crumbs; Domain=.example.com; Max-Age=1234; Expires="));
HttpHeaders headers = new HttpHeaders();
headers.set("header", "headerValue");
headers.setContentType(MediaType.TEXT_PLAIN);
headers.setLocation(new URI("/redirectFoo"));
headers.put("Set-Cookie", cookieValues);
String heading = "MockHttpServletResponse";
assertValue(heading, "Status", this.response.getStatus());
assertValue(heading, "Error message", response.getErrorMessage());
assertValue(heading, "Headers", headers);
assertValue(heading, "Content type", this.response.getContentType());
assertValue(heading, "Body", this.response.getContentAsString());
assertValue(heading, "Forwarded URL", this.response.getForwardedUrl());
assertValue(heading, "Redirected URL", this.response.getRedirectedUrl());
Map<String, Map<String, Object>> printedValues = this.handler.getPrinter().printedValues;
String[] cookies = (String[]) printedValues.get(heading).get("Cookies");
assertEquals(2, cookies.length);
String cookie1 = cookies[0];
String cookie2 = cookies[1];
assertTrue(cookie1.startsWith("[" + Cookie.class.getSimpleName()));
assertTrue(cookie1.contains("name = 'cookie', value = 'cookieValue'"));
assertTrue(cookie1.endsWith("]"));
assertTrue(cookie2.startsWith("[" + Cookie.class.getSimpleName()));
assertTrue(cookie2.contains("name = 'enigma', value = '42', " +
"comment = 'This is a comment', domain = '.example.com', maxAge = 1234, " +
"path = '/crumbs', secure = true, version = 0, httpOnly = true"));
assertTrue(cookie2.endsWith("]"));
}
/**
* Parse cookies.
*/
protected void parseCookies() {
cookiesParsed = true;
Cookies serverCookies = coyoteRequest.getCookies();
int count = serverCookies.getCookieCount();
if (count <= 0) {
return;
}
cookies = new Cookie[count];
int idx=0;
for (int i = 0; i < count; i++) {
ServerCookie scookie = serverCookies.getCookie(i);
try {
/*
we must unescape the '\\' escape character
*/
Cookie cookie = new Cookie(scookie.getName().toString(),null);
int version = scookie.getVersion();
cookie.setVersion(version);
cookie.setValue(unescape(scookie.getValue().toString()));
cookie.setPath(unescape(scookie.getPath().toString()));
String domain = scookie.getDomain().toString();
if (domain!=null)
{
cookie.setDomain(unescape(domain));//avoid NPE
}
String comment = scookie.getComment().toString();
cookie.setComment(version==1?unescape(comment):null);
cookies[idx++] = cookie;
} catch(IllegalArgumentException e) {
// Ignore bad cookie
}
}
if( idx < count ) {
Cookie [] ncookies = new Cookie[idx];
System.arraycopy(cookies, 0, ncookies, 0, idx);
cookies = ncookies;
}
}
/**
* Creates a new session cookie for the given session ID
*
* @param context The Context for the web application
* @param sessionId The ID of the session for which the cookie will be
* created
* @param secure Should session cookie be configured as secure
*/
public static Cookie createSessionCookie(Context context,
String sessionId, boolean secure) {
SessionCookieConfig scc =
context.getServletContext().getSessionCookieConfig();
// NOTE: The priority order for session cookie configuration is:
// 1. Context level configuration
// 2. Values from SessionCookieConfig
// 3. Defaults
Cookie cookie = new Cookie(
SessionConfig.getSessionCookieName(context), sessionId);
// Just apply the defaults.
cookie.setMaxAge(scc.getMaxAge());
cookie.setComment(scc.getComment());
if (context.getSessionCookieDomain() == null) {
// Avoid possible NPE
if (scc.getDomain() != null) {
cookie.setDomain(scc.getDomain());
}
} else {
cookie.setDomain(context.getSessionCookieDomain());
}
// Always set secure if the request is secure
if (scc.isSecure() || secure) {
cookie.setSecure(true);
}
// Always set httpOnly if the context is configured for that
if (scc.isHttpOnly() || context.getUseHttpOnly()) {
cookie.setHttpOnly(true);
}
String contextPath = context.getSessionCookiePath();
if (contextPath == null || contextPath.length() == 0) {
contextPath = scc.getPath();
}
if (contextPath == null || contextPath.length() == 0) {
contextPath = context.getEncodedPath();
}
if (context.getSessionCookiePathUsesTrailingSlash()) {
// Handle special case of ROOT context where cookies require a path of
// '/' but the servlet spec uses an empty string
// Also ensure the cookies for a context with a path of /foo don't get
// sent for requests with a path of /foobar
if (!contextPath.endsWith("/")) {
contextPath = contextPath + "/";
}
} else {
// Only handle special case of ROOT context where cookies require a
// path of '/' but the servlet spec uses an empty string
if (contextPath.length() == 0) {
contextPath = "/";
}
}
cookie.setPath(contextPath);
return cookie;
}
protected void replaceCookie(Request request, Response response, Cookie cookie) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
// copy the existing session cookie, but use a different domain (only if domain is valid)
String cookieDomain = null;
cookieDomain = EntityUtilProperties.getPropertyValue("url", "cookie.domain", "", delegator);
if (UtilValidate.isEmpty(cookieDomain)) {
String serverName = request.getServerName();
String[] domainArray = serverName.split("\\.");
// check that the domain isn't an IP address
if (domainArray.length == 4) {
boolean isIpAddress = true;
for (String domainSection : domainArray) {
if (!UtilValidate.isIntegerInRange(domainSection, 0, 255)) {
isIpAddress = false;
break;
}
}
if (isIpAddress) {
return;
}
}
if (domainArray.length > 2) {
cookieDomain = "." + domainArray[domainArray.length - 2] + "." + domainArray[domainArray.length - 1];
}
}
if (UtilValidate.isNotEmpty(cookieDomain)) {
Cookie newCookie = new Cookie(cookie.getName(), cookie.getValue());
if (cookie.getPath() != null) {
newCookie.setPath(cookie.getPath());
}
newCookie.setDomain(cookieDomain);
newCookie.setMaxAge(cookie.getMaxAge());
newCookie.setVersion(cookie.getVersion());
if (cookie.getComment() != null) {
newCookie.setComment(cookie.getComment());
}
newCookie.setSecure(cookie.getSecure());
newCookie.setHttpOnly(cookie.isHttpOnly());
// if the response has already been committed, our replacement strategy will have no effect
if (response.isCommitted()) {
Debug.logError("CrossSubdomainSessionValve: response was already committed!", module);
}
// find the Set-Cookie header for the existing cookie and replace its value with new cookie
MimeHeaders mimeHeaders = request.getCoyoteRequest().getMimeHeaders();
for (int i = 0, size = mimeHeaders.size(); i < size; i++) {
if (mimeHeaders.getName(i).equals("Set-Cookie")) {
MessageBytes value = mimeHeaders.getValue(i);
if (value.indexOf(cookie.getName()) >= 0) {
String newCookieValue = request.getContext().getCookieProcessor().generateHeader(newCookie);
if (Debug.verboseOn()) Debug.logVerbose("CrossSubdomainSessionValve: old Set-Cookie value: " + value.toString(), module);
if (Debug.verboseOn()) Debug.logVerbose("CrossSubdomainSessionValve: new Set-Cookie value: " + newCookieValue, module);
value.setString(newCookieValue);
}
}
}
}
}
@Test
@SuppressWarnings("deprecation")
public void printResponse() throws Exception {
Cookie enigmaCookie = new Cookie("enigma", "42");
enigmaCookie.setComment("This is a comment");
enigmaCookie.setHttpOnly(true);
enigmaCookie.setMaxAge(1234);
enigmaCookie.setDomain(".example.com");
enigmaCookie.setPath("/crumbs");
enigmaCookie.setSecure(true);
this.response.setStatus(400, "error");
this.response.addHeader("header", "headerValue");
this.response.setContentType("text/plain");
this.response.getWriter().print("content");
this.response.setForwardedUrl("redirectFoo");
this.response.sendRedirect("/redirectFoo");
this.response.addCookie(new Cookie("cookie", "cookieValue"));
this.response.addCookie(enigmaCookie);
this.handler.handle(this.mvcResult);
HttpHeaders headers = new HttpHeaders();
headers.set("header", "headerValue");
headers.setContentType(MediaType.TEXT_PLAIN);
headers.setLocation(new URI("/redirectFoo"));
String heading = "MockHttpServletResponse";
assertValue(heading, "Status", this.response.getStatus());
assertValue(heading, "Error message", response.getErrorMessage());
assertValue(heading, "Headers", headers);
assertValue(heading, "Content type", this.response.getContentType());
assertValue(heading, "Body", this.response.getContentAsString());
assertValue(heading, "Forwarded URL", this.response.getForwardedUrl());
assertValue(heading, "Redirected URL", this.response.getRedirectedUrl());
Map<String, Map<String, Object>> printedValues = this.handler.getPrinter().printedValues;
String[] cookies = (String[]) printedValues.get(heading).get("Cookies");
assertEquals(2, cookies.length);
String cookie1 = cookies[0];
String cookie2 = cookies[1];
assertTrue(cookie1.startsWith("[" + Cookie.class.getSimpleName()));
assertTrue(cookie1.contains("name = 'cookie', value = 'cookieValue'"));
assertTrue(cookie1.endsWith("]"));
assertTrue(cookie2.startsWith("[" + Cookie.class.getSimpleName()));
assertTrue(cookie2.contains("name = 'enigma', value = '42', comment = 'This is a comment', domain = '.example.com', maxAge = 1234, path = '/crumbs', secure = true, version = 0, httpOnly = true"));
assertTrue(cookie2.endsWith("]"));
}
/**
* Parse cookies.
*/
protected void parseCookies() {
cookiesParsed = true;
Cookies serverCookies = coyoteRequest.getCookies();
int count = serverCookies.getCookieCount();
if (count <= 0) {
return;
}
cookies = new Cookie[count];
int idx=0;
for (int i = 0; i < count; i++) {
ServerCookie scookie = serverCookies.getCookie(i);
try {
/*
we must unescape the '\\' escape character
*/
Cookie cookie = new Cookie(scookie.getName().toString(),null);
int version = scookie.getVersion();
cookie.setVersion(version);
cookie.setValue(unescape(scookie.getValue().toString()));
cookie.setPath(unescape(scookie.getPath().toString()));
String domain = scookie.getDomain().toString();
if (domain!=null)
{
cookie.setDomain(unescape(domain));//avoid NPE
}
String comment = scookie.getComment().toString();
cookie.setComment(version==1?unescape(comment):null);
cookies[idx++] = cookie;
} catch(IllegalArgumentException e) {
// Ignore bad cookie
}
}
if( idx < count ) {
Cookie [] ncookies = new Cookie[idx];
System.arraycopy(cookies, 0, ncookies, 0, idx);
cookies = ncookies;
}
}
/**
* Creates a new session cookie for the given session ID
*
* @param context The Context for the web application
* @param sessionId The ID of the session for which the cookie will be
* created
* @param secure Should session cookie be configured as secure
*/
public static Cookie createSessionCookie(Context context,
String sessionId, boolean secure) {
SessionCookieConfig scc =
context.getServletContext().getSessionCookieConfig();
// NOTE: The priority order for session cookie configuration is:
// 1. Context level configuration
// 2. Values from SessionCookieConfig
// 3. Defaults
Cookie cookie = new Cookie(
SessionConfig.getSessionCookieName(context), sessionId);
// Just apply the defaults.
cookie.setMaxAge(scc.getMaxAge());
cookie.setComment(scc.getComment());
if (context.getSessionCookieDomain() == null) {
// Avoid possible NPE
if (scc.getDomain() != null) {
cookie.setDomain(scc.getDomain());
}
} else {
cookie.setDomain(context.getSessionCookieDomain());
}
// Always set secure if the request is secure
if (scc.isSecure() || secure) {
cookie.setSecure(true);
}
// Always set httpOnly if the context is configured for that
if (scc.isHttpOnly() || context.getUseHttpOnly()) {
cookie.setHttpOnly(true);
}
String contextPath = context.getSessionCookiePath();
if (contextPath == null || contextPath.length() == 0) {
contextPath = scc.getPath();
}
if (contextPath == null || contextPath.length() == 0) {
contextPath = context.getEncodedPath();
}
if (context.getSessionCookiePathUsesTrailingSlash()) {
// Handle special case of ROOT context where cookies require a path of
// '/' but the servlet spec uses an empty string
// Also ensure the cookies for a context with a path of /foo don't get
// sent for requests with a path of /foobar
if (!contextPath.endsWith("/")) {
contextPath = contextPath + "/";
}
} else {
// Only handle special case of ROOT context where cookies require a
// path of '/' but the servlet spec uses an empty string
if (contextPath.length() == 0) {
contextPath = "/";
}
}
cookie.setPath(contextPath);
return cookie;
}