01: /*
02: * Copyright 2001 Sun Microsystems, Inc. All rights reserved.
03: * PROPRIETARY/CONFIDENTIAL. Use of this product is subject to license terms.
04: */
05: package com.sun.portal.desktop.encode;
06:
07: import java.net.URLDecoder;
08:
09: import com.sun.portal.desktop.util.Integers;
10:
11: class CookieEncoderDecoder implements TypeEncoder, TypeDecoder {
12: /**
13: * special characters that need to be escaped when setting cookie value.
14: */
15: public static final char[] cookieEscapeChars = { ';', ',', ' ',
16: '[', ']', '{', '}', '=', '"', '/', '\\', '?', '@', ':',
17: '\n', '\r' };
18:
19: /**
20: * Checks for special characters that cannot be used as a cookie value
21: */
22: private static boolean isCookieEscChar(char ch) {
23: boolean result = false;
24: for (int i = 0; i < cookieEscapeChars.length; i++) {
25: if (ch == cookieEscapeChars[i]) {
26: result = true;
27: break;
28: }
29: }
30: return result;
31: }
32:
33: /**
34: * Encodes a string to be used for a cookie value. Translates any
35: * special characters defined in the static arrays cookieEscapeChars
36: * and encodes the special characters using the following algorithm:
37: *
38: * The algorithm translates, for example, ',' the comma character into
39: * '%2c' where 2c is the hex equivalent of the comma character's
40: * numeric value.
41: *
42: */
43: public String encode(String value) {
44: StringBuffer buf = new StringBuffer();
45: for (int i = 0; i < value.length(); i++) {
46: char ch = value.charAt(i);
47: if (isCookieEscChar(ch)) {
48: int j = (int) ch;
49: buf.append("%").append(Integers.getHex(j));
50: } else {
51: buf.append(ch);
52: }
53: }
54: return buf.toString();
55: }
56:
57: /**
58: * Decodes a cookie cncoded string. A cookie encoded string is one that has had
59: * special characters excaped as %XY where XY is the hex equivalent of the
60: * character's numeric value. The specific characters to be escaped are contained
61: * in the static array cookieEscapeChars.
62: *
63: * This method calls java.net.URLDecoder to decode the string. A URL encoded string
64: * is of the same format as a cookie encoded one, with different escape characters.
65: * The implementation of URLDecoder.decode() simply translates all %SY into the
66: * character equivalent, not paying special attention to whether the character represents
67: * something that would have been URL encoded. The implementation here is therefore
68: * dependent upon the implementation of java.net.URLDecoder and may need to be
69: * changed as the JDK implementation changes.
70: *
71: */
72: public String decode(String value) {
73: return java.net.URLDecoder.decode(value);
74: }
75: }
|