HeaderParser.java 8.3 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
 */

package sun.net.www;

import java.util.Iterator;

/* This is useful for the nightmare of parsing multi-part HTTP/RFC822 headers
 * sensibly:
 * From a String like: 'timeout=15, max=5'
 * create an array of Strings:
 * { {"timeout", "15"},
 *   {"max", "5"}
 * }
 * From one like: 'Basic Realm="FuzzFace" Foo="Biz Bar Baz"'
 * create one like (no quotes in literal):
 * { {"basic", null},
 *   {"realm", "FuzzFace"}
 *   {"foo", "Biz Bar Baz"}
 * }
 * keys are converted to lower case, vals are left as is....
 *
 * @author Dave Brown
 */


public class HeaderParser {

    /* table of key/val pairs */
    String raw;
    String[][] tab;
    int nkeys;
    int asize = 10; // initial size of array is 10

    public HeaderParser(String raw) {
        this.raw = raw;
        tab = new String[asize][2];
        parse();
    }

    private HeaderParser () {
    }

    /**
     * create a new HeaderParser from this, whose keys (and corresponding values)
     * range from "start" to "end-1"
     */
    public HeaderParser subsequence (int start, int end) {
        if (start == 0 && end == nkeys) {
            return this;
        }
        if (start < 0 || start >= end || end > nkeys)
            throw new IllegalArgumentException ("invalid start or end");
        HeaderParser n = new HeaderParser ();
        n.tab = new String [asize][2];
        n.asize = asize;
        System.arraycopy (tab, start, n.tab, 0, (end-start));
        n.nkeys= (end-start);
        return n;
    }

    private void parse() {

        if (raw != null) {
            raw = raw.trim();
            char[] ca = raw.toCharArray();
            int beg = 0, end = 0, i = 0;
            boolean inKey = true;
            boolean inQuote = false;
            int len = ca.length;
            while (end < len) {
                char c = ca[end];
                if ((c == '=') && !inQuote) { // end of a key
                    tab[i][0] = new String(ca, beg, end-beg).toLowerCase();
                    inKey = false;
                    end++;
                    beg = end;
                } else if (c == '\"') {
                    if (inQuote) {
                        tab[i++][1]= new String(ca, beg, end-beg);
                        inQuote=false;
                        do {
                            end++;
                        } while (end < len && (ca[end] == ' ' || ca[end] == ','));
                        inKey=true;
                        beg=end;
                    } else {
                        inQuote=true;
                        end++;
                        beg=end;
                    }
                } else if (c == ' ' || c == ',') { // end key/val, of whatever we're in
                    if (inQuote) {
                        end++;
                        continue;
                    } else if (inKey) {
                        tab[i++][0] = (new String(ca, beg, end-beg)).toLowerCase();
                    } else {
                        tab[i++][1] = (new String(ca, beg, end-beg));
                    }
                    while (end < len && (ca[end] == ' ' || ca[end] == ',')) {
                        end++;
                    }
                    inKey = true;
                    beg = end;
                } else {
                    end++;
                }
                if (i == asize) {
                    asize = asize * 2;
                    String[][] ntab = new String[asize][2];
                    System.arraycopy (tab, 0, ntab, 0, tab.length);
                    tab = ntab;
                }
            }
            // get last key/val, if any
            if (--end > beg) {
                if (!inKey) {
                    if (ca[end] == '\"') {
                        tab[i++][1] = (new String(ca, beg, end-beg));
                    } else {
                        tab[i++][1] = (new String(ca, beg, end-beg+1));
                    }
                } else {
                    tab[i++][0] = (new String(ca, beg, end-beg+1)).toLowerCase();
                }
            } else if (end == beg) {
                if (!inKey) {
                    if (ca[end] == '\"') {
                        tab[i++][1] = String.valueOf(ca[end-1]);
                    } else {
                        tab[i++][1] = String.valueOf(ca[end]);
                    }
                } else {
                    tab[i++][0] = String.valueOf(ca[end]).toLowerCase();
                }
            }
            nkeys=i;
        }

    }

    public String findKey(int i) {
        if (i < 0 || i > asize)
            return null;
        return tab[i][0];
    }

    public String findValue(int i) {
        if (i < 0 || i > asize)
            return null;
        return tab[i][1];
    }

    public String findValue(String key) {
        return findValue(key, null);
    }

    public String findValue(String k, String Default) {
        if (k == null)
            return Default;
        k = k.toLowerCase();
        for (int i = 0; i < asize; ++i) {
            if (tab[i][0] == null) {
                return Default;
            } else if (k.equals(tab[i][0])) {
                return tab[i][1];
            }
        }
        return Default;
    }

195
    class ParserIterator implements Iterator<String> {
D
duke 已提交
196 197 198 199 200 201 202 203 204
        int index;
        boolean returnsValue; // or key

        ParserIterator (boolean returnValue) {
            returnsValue = returnValue;
        }
        public boolean hasNext () {
            return index<nkeys;
        }
205
        public String next () {
D
duke 已提交
206 207 208 209 210 211 212
            return tab[index++][returnsValue?1:0];
        }
        public void remove () {
            throw new UnsupportedOperationException ("remove not supported");
        }
    }

213
    public Iterator<String> keys () {
D
duke 已提交
214 215 216
        return new ParserIterator (false);
    }

217
    public Iterator<String> values () {
D
duke 已提交
218 219 220 221
        return new ParserIterator (true);
    }

    public String toString () {
222
        Iterator<String> k = keys();
D
duke 已提交
223 224 225
        StringBuffer sbuf = new StringBuffer();
        sbuf.append ("{size="+asize+" nkeys="+nkeys+" ");
        for (int i=0; k.hasNext(); i++) {
226
            String key = k.next();
D
duke 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
            String val = findValue (i);
            if (val != null && "".equals (val)) {
                val = null;
            }
            sbuf.append (" {"+key+(val==null?"":","+val)+"}");
            if (k.hasNext()) {
                sbuf.append (",");
            }
        }
        sbuf.append (" }");
        return new String (sbuf);
    }

    public int findInt(String k, int Default) {
        try {
            return Integer.parseInt(findValue(k, String.valueOf(Default)));
        } catch (Throwable t) {
            return Default;
        }
    }
    /*
    public static void main(String[] a) throws Exception {
        System.out.print("enter line to parse> ");
        System.out.flush();
        DataInputStream dis = new DataInputStream(System.in);
        String line = dis.readLine();
        HeaderParser p = new HeaderParser(line);
        for (int i = 0; i < asize; ++i) {
            if (p.findKey(i) == null) break;
            String v = p.findValue(i);
            System.out.println(i + ") " +p.findKey(i) + "="+v);
        }
        System.out.println("Done!");

    }
    */
}