1 17 18 19 package org.apache.catalina.util; 20 21 import java.text.*; 22 import java.util.*; 23 24 import javax.servlet.http.Cookie ; 25 26 28 34 public class CookieTools { 35 36 39 public static String getCookieHeaderName(Cookie cookie) { 40 int version = cookie.getVersion(); 41 42 if (version == 1) { 43 return "Set-Cookie2"; 44 } else { 45 return "Set-Cookie"; 46 } 47 } 48 49 52 public static String getCookieHeaderValue(Cookie cookie) { 53 StringBuffer buf = new StringBuffer (); 54 getCookieHeaderValue( cookie, buf ); 55 return buf.toString(); 56 } 57 58 60 public static void getCookieHeaderValue(Cookie cookie, StringBuffer buf) { 61 int version = cookie.getVersion(); 62 63 65 String name = cookie.getName(); if (name == null) 67 name = ""; 68 String value = cookie.getValue(); 69 if (value == null) 70 value = ""; 71 72 buf.append(name); 73 buf.append("="); 74 maybeQuote(version, buf, value); 75 76 if (version == 1) { 78 buf.append ("; Version=1"); 80 81 if (cookie.getComment() != null) { 83 buf.append ("; Comment="); 84 maybeQuote (version, buf, cookie.getComment()); 85 } 86 } 87 88 90 if (cookie.getDomain() != null) { 91 buf.append("; Domain="); 92 maybeQuote (version, buf, cookie.getDomain()); 93 } 94 95 if (cookie.getMaxAge() >= 0) { 97 if (version == 0) { 98 buf.append ("; Expires="); 99 if (cookie.getMaxAge() == 0) 100 DateTool.oldCookieFormat.format(new Date(10000), buf, 101 new FieldPosition(0)); 102 else 103 DateTool.oldCookieFormat.format 104 (new Date( System.currentTimeMillis() + 105 cookie.getMaxAge() *1000L), buf, 106 new FieldPosition(0)); 107 } else { 108 buf.append ("; Max-Age="); 109 buf.append (cookie.getMaxAge()); 110 } 111 } else if (version == 1) 112 buf.append ("; Discard"); 113 114 if (cookie.getPath() != null) { 116 buf.append ("; Path="); 117 maybeQuote (version, buf, cookie.getPath()); 118 } 119 120 if (cookie.getSecure()) { 122 buf.append ("; Secure"); 123 } 124 } 125 126 static void maybeQuote (int version, StringBuffer buf, 127 String value) 128 { 129 if (version == 0 || isToken (value)) 130 buf.append (value); 131 else { 132 buf.append ('"'); 133 buf.append (value); 134 buf.append ('"'); 135 } 136 } 137 138 private static final String tspecials = "()<>@,;:\\\"/[]?={} \t"; 142 143 146 private static boolean isToken (String value) { 147 int len = value.length (); 148 149 for (int i = 0; i < len; i++) { 150 char c = value.charAt (i); 151 152 if (c < 0x20 || c >= 0x7f || tspecials.indexOf (c) != -1) 153 return false; 154 } 155 return true; 156 } 157 158 159 } 160 | Popular Tags |