1 package com.quadcap.io; 2 3 40 41 import java.util.Enumeration ; 42 import java.util.Map ; 43 import java.util.NoSuchElementException ; 44 45 import java.io.IOException ; 46 import java.io.InputStream ; 47 import java.io.PushbackInputStream ; 48 49 import com.quadcap.util.Debug; 50 51 62 public class HeaderEnumeration implements Enumeration { 63 String next; 64 PushbackInputStream is; 65 StringBuffer sb = new StringBuffer (); 66 67 static final byte CR = 0x0d; 68 static final byte LF = 0x0a; 69 70 public HeaderEnumeration(InputStream is) { 71 this.is = new PushbackInputStream (is); 72 } 73 74 80 public boolean hasMoreElements() { 81 if (next == null) getNext(); 82 return (next != null); 83 } 84 85 91 public Object nextElement() { 92 if (next == null) getNext(); 93 if (next == null) throw new NoSuchElementException ("no more elements"); 94 Object ret = next; 95 next = null; 96 return ret; 97 } 98 99 102 void getNext() { 103 sb.setLength(0); 104 105 int c; 106 int state = 0; 107 108 try { 109 while ((c = is.read()) >= 0) { 110 switch (state) { 111 case 0: 112 if (c == CR) { 113 state = 1; 114 } else { 115 sb.append((char)c); 116 } 117 break; 118 case 1: 119 if (c == LF) { 120 state = 2; 121 } else if (c != CR) { 122 sb.append((char)c); 123 state = 0; 124 } 125 break; 126 case 2: 127 state = 0; 128 if (c == ' ' || c == '\t') { 129 sb.append(' '); 130 } else { 131 is.unread(c); 132 next = sb.toString(); 133 sb.setLength(0); 134 return; 135 } 136 break; 137 } 138 } 139 if (state == 2 && sb.toString().trim().length() > 0) { 140 next = sb.toString().trim(); 141 sb.setLength(0); 142 } 143 } catch (IOException e) { 144 Debug.print(e); 145 } 146 } 147 148 153 public void getHeaderMap(Map headerMap) throws IOException { 154 while (hasMoreElements()) { 155 String header = (String )nextElement(); 156 int idx = header.indexOf(':'); 157 if (idx >= 0) { 158 String headerName = header.substring(0, idx).trim(); 159 String headerVal = header.substring(idx+1).trim(); 160 headerMap.put(headerName.toLowerCase(), headerVal); 161 } else { 162 throw new IOException ("Bad header: '" + header + "'"); 163 } 164 } 165 } 166 167 } 168 | Popular Tags |