Path: blob/master/src/java.base/share/classes/sun/net/www/HeaderParser.java
41159 views
/*1* Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.net.www;2627import java.util.Iterator;2829/* This is useful for the nightmare of parsing multi-part HTTP/RFC822 headers30* sensibly:31* From a String like: 'timeout=15, max=5'32* create an array of Strings:33* { {"timeout", "15"},34* {"max", "5"}35* }36* From one like: 'Basic Realm="FuzzFace" Foo="Biz Bar Baz"'37* create one like (no quotes in literal):38* { {"basic", null},39* {"realm", "FuzzFace"}40* {"foo", "Biz Bar Baz"}41* }42* keys are converted to lower case, vals are left as is....43*44* @author Dave Brown45*/464748public class HeaderParser {4950/* table of key/val pairs */51String raw;52String[][] tab;53int nkeys;54int asize = 10; // initial size of array is 105556public HeaderParser(String raw) {57this.raw = raw;58tab = new String[asize][2];59parse();60}6162private HeaderParser () {63}6465/**66* create a new HeaderParser from this, whose keys (and corresponding values)67* range from "start" to "end-1"68*/69public HeaderParser subsequence (int start, int end) {70if (start == 0 && end == nkeys) {71return this;72}73if (start < 0 || start >= end || end > nkeys)74throw new IllegalArgumentException ("invalid start or end");75HeaderParser n = new HeaderParser ();76n.tab = new String [asize][2];77n.asize = asize;78System.arraycopy (tab, start, n.tab, 0, (end-start));79n.nkeys= (end-start);80return n;81}8283private void parse() {8485if (raw != null) {86raw = raw.trim();87char[] ca = raw.toCharArray();88int beg = 0, end = 0, i = 0;89boolean inKey = true;90boolean inQuote = false;91int len = ca.length;92while (end < len) {93char c = ca[end];94if ((c == '=') && !inQuote) { // end of a key95tab[i][0] = new String(ca, beg, end-beg).toLowerCase();96inKey = false;97end++;98beg = end;99} else if (c == '\"') {100if (inQuote) {101tab[i++][1]= new String(ca, beg, end-beg);102inQuote=false;103do {104end++;105} while (end < len && (ca[end] == ' ' || ca[end] == ','));106inKey=true;107beg=end;108} else {109inQuote=true;110end++;111beg=end;112}113} else if (c == ' ' || c == ',') { // end key/val, of whatever we're in114if (inQuote) {115end++;116continue;117} else if (inKey) {118tab[i++][0] = (new String(ca, beg, end-beg)).toLowerCase();119} else {120tab[i++][1] = (new String(ca, beg, end-beg));121}122while (end < len && (ca[end] == ' ' || ca[end] == ',')) {123end++;124}125inKey = true;126beg = end;127} else {128end++;129}130if (i == asize) {131asize = asize * 2;132String[][] ntab = new String[asize][2];133System.arraycopy (tab, 0, ntab, 0, tab.length);134tab = ntab;135}136}137// get last key/val, if any138if (--end > beg) {139if (!inKey) {140if (ca[end] == '\"') {141tab[i++][1] = (new String(ca, beg, end-beg));142} else {143tab[i++][1] = (new String(ca, beg, end-beg+1));144}145} else {146tab[i++][0] = (new String(ca, beg, end-beg+1)).toLowerCase();147}148} else if (end == beg) {149if (!inKey) {150if (ca[end] == '\"') {151tab[i++][1] = String.valueOf(ca[end-1]);152} else {153tab[i++][1] = String.valueOf(ca[end]);154}155} else {156tab[i++][0] = String.valueOf(ca[end]).toLowerCase();157}158}159nkeys=i;160}161162}163164public String findKey(int i) {165if (i < 0 || i > asize)166return null;167return tab[i][0];168}169170public String findValue(int i) {171if (i < 0 || i > asize)172return null;173return tab[i][1];174}175176public String findValue(String key) {177return findValue(key, null);178}179180public String findValue(String k, String Default) {181if (k == null)182return Default;183k = k.toLowerCase();184for (int i = 0; i < asize; ++i) {185if (tab[i][0] == null) {186return Default;187} else if (k.equals(tab[i][0])) {188return tab[i][1];189}190}191return Default;192}193194class ParserIterator implements Iterator<String> {195int index;196boolean returnsValue; // or key197198ParserIterator (boolean returnValue) {199returnsValue = returnValue;200}201public boolean hasNext () {202return index<nkeys;203}204public String next () {205return tab[index++][returnsValue?1:0];206}207public void remove () {208throw new UnsupportedOperationException ("remove not supported");209}210}211212public Iterator<String> keys () {213return new ParserIterator (false);214}215216public Iterator<String> values () {217return new ParserIterator (true);218}219220public String toString () {221Iterator<String> k = keys();222StringBuilder sb = new StringBuilder();223sb.append("{size=").append(asize).append(" nkeys=").append(nkeys)224.append(' ');225for (int i=0; k.hasNext(); i++) {226String key = k.next();227String val = findValue (i);228if (val != null && val.isEmpty()) {229val = null;230}231sb.append(" {").append(key).append(val == null ? "" : "," + val)232.append('}');233if (k.hasNext()) {234sb.append (',');235}236}237sb.append (" }");238return sb.toString();239}240241public int findInt(String k, int Default) {242try {243return Integer.parseInt(findValue(k, String.valueOf(Default)));244} catch (Throwable t) {245return Default;246}247}248/*249public static void main(String[] a) throws Exception {250System.out.print("enter line to parse> ");251System.out.flush();252DataInputStream dis = new DataInputStream(System.in);253String line = dis.readLine();254HeaderParser p = new HeaderParser(line);255for (int i = 0; i < asize; ++i) {256if (p.findKey(i) == null) break;257String v = p.findValue(i);258System.out.println(i + ") " +p.findKey(i) + "="+v);259}260System.out.println("Done!");261262}263*/264}265266267