001package org.json;
002
003/*
004Copyright (c) 2002 JSON.org
005
006Permission is hereby granted, free of charge, to any person obtaining a copy
007of this software and associated documentation files (the "Software"), to deal
008in the Software without restriction, including without limitation the rights
009to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
010copies of the Software, and to permit persons to whom the Software is
011furnished to do so, subject to the following conditions:
012
013The above copyright notice and this permission notice shall be included in all
014copies or substantial portions of the Software.
015
016The Software shall be used for Good, not Evil.
017
018THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
019IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
020FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
021AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
022LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
023OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
024SOFTWARE.
025 */
026
027/**
028 * Convert a web browser cookie specification to a JSONObject and back.
029 * JSON and Cookies are both notations for name/value pairs.
030 * @author JSON.org
031@version $Id$
032@since Ptolemy II 10.0
033 * @version 2008-09-18
034 */
035public class Cookie {
036
037    /**
038     * Produce a copy of a string in which the characters '+', '%', '=', ';'
039     * and control characters are replaced with "%hh". This is a gentle form
040     * of URL encoding, attempting to cause as little distortion to the
041     * string as possible. The characters '=' and ';' are meta characters in
042     * cookies. By convention, they are escaped using the URL-encoding. This is
043     * only a convention, not a standard. Often, cookies are expected to have
044     * encoded values. We encode '=' and ';' because we must. We encode '%' and
045     * '+' because they are meta characters in URL encoding.
046     * @param string The source string.
047     * @return       The escaped result.
048     */
049    public static String escape(String string) {
050        char c;
051        String s = string.trim();
052        StringBuffer sb = new StringBuffer();
053        int len = s.length();
054        for (int i = 0; i < len; i += 1) {
055            c = s.charAt(i);
056            if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
057                sb.append('%');
058                sb.append(Character.forDigit((char) (c >>> 4 & 0x0f), 16));
059                sb.append(Character.forDigit((char) (c & 0x0f), 16));
060            } else {
061                sb.append(c);
062            }
063        }
064        return sb.toString();
065    }
066
067    /**
068     * Convert a cookie specification string into a JSONObject. The string
069     * will contain a name value pair separated by '='. The name and the value
070     * will be unescaped, possibly converting '+' and '%' sequences. The
071     * cookie properties may follow, separated by ';', also represented as
072     * name=value (except the secure property, which does not have a value).
073     * The name will be stored under the key "name", and the value will be
074     * stored under the key "value". This method does not do checking or
075     * validation of the parameters. It only converts the cookie string into
076     * a JSONObject.
077     * @param string The cookie specification string.
078     * @return A JSONObject containing "name", "value", and possibly other
079     *  members.
080     * @exception JSONException
081     */
082    public static JSONObject toJSONObject(String string) throws JSONException {
083        String n;
084        JSONObject o = new JSONObject();
085        Object v;
086        JSONTokener x = new JSONTokener(string);
087        o.put("name", x.nextTo('='));
088        x.next('=');
089        o.put("value", x.nextTo(';'));
090        x.next();
091        while (x.more()) {
092            n = unescape(x.nextTo("=;"));
093            if (x.next() != '=') {
094                if (n.equals("secure")) {
095                    v = Boolean.TRUE;
096                } else {
097                    throw x.syntaxError("Missing '=' in cookie parameter.");
098                }
099            } else {
100                v = unescape(x.nextTo(';'));
101                x.next();
102            }
103            o.put(n, v);
104        }
105        return o;
106    }
107
108    /**
109     * Convert a JSONObject into a cookie specification string. The JSONObject
110     * must contain "name" and "value" members.
111     * If the JSONObject contains "expires", "domain", "path", or "secure"
112     * members, they will be appended to the cookie specification string.
113     * All other members are ignored.
114     * @param o A JSONObject
115     * @return A cookie specification string
116     * @exception JSONException
117     */
118    public static String toString(JSONObject o) throws JSONException {
119        StringBuffer sb = new StringBuffer();
120
121        sb.append(escape(o.getString("name")));
122        sb.append("=");
123        sb.append(escape(o.getString("value")));
124        if (o.has("expires")) {
125            sb.append(";expires=");
126            sb.append(o.getString("expires"));
127        }
128        if (o.has("domain")) {
129            sb.append(";domain=");
130            sb.append(escape(o.getString("domain")));
131        }
132        if (o.has("path")) {
133            sb.append(";path=");
134            sb.append(escape(o.getString("path")));
135        }
136        if (o.optBoolean("secure")) {
137            sb.append(";secure");
138        }
139        return sb.toString();
140    }
141
142    /**
143     * Convert <code>%</code><i>hh</i> sequences to single characters, and
144     * convert plus to space.
145     * @param s A string that may contain
146     *      <code>+</code>&nbsp;<small>(plus)</small> and
147     *      <code>%</code><i>hh</i> sequences.
148     * @return The unescaped string.
149     */
150    public static String unescape(String s) {
151        int len = s.length();
152        StringBuffer b = new StringBuffer();
153        for (int i = 0; i < len; ++i) {
154            char c = s.charAt(i);
155            if (c == '+') {
156                c = ' ';
157            } else if (c == '%' && i + 2 < len) {
158                int d = JSONTokener.dehexchar(s.charAt(i + 1));
159                int e = JSONTokener.dehexchar(s.charAt(i + 2));
160                if (d >= 0 && e >= 0) {
161                    c = (char) (d * 16 + e);
162                    i += 2;
163                }
164            }
165            b.append(c);
166        }
167        return b.toString();
168    }
169}