00001
package com.quadcap.io;
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
import java.util.Enumeration;
00042
import java.util.Map;
00043
import java.util.NoSuchElementException;
00044
00045
import java.io.IOException;
00046
import java.io.InputStream;
00047
import java.io.PushbackInputStream;
00048
00049
import com.quadcap.util.Debug;
00050
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060
00061
00062 public class HeaderEnumeration implements Enumeration {
00063 String
next;
00064 PushbackInputStream
is;
00065 StringBuffer
sb =
new StringBuffer();
00066
00067 static final byte
CR = 0x0d;
00068 static final byte
LF = 0x0a;
00069
00070 public HeaderEnumeration(InputStream is) {
00071
this.is =
new PushbackInputStream(is);
00072 }
00073
00074
00075
00076
00077
00078
00079
00080 public boolean hasMoreElements() {
00081
if (
next == null)
getNext();
00082
return (
next != null);
00083 }
00084
00085
00086
00087
00088
00089
00090
00091 public Object
nextElement() {
00092
if (
next == null)
getNext();
00093
if (
next == null)
throw new NoSuchElementException(
"no more elements");
00094 Object ret =
next;
00095 next = null;
00096
return ret;
00097 }
00098
00099
00100
00101
00102 void getNext() {
00103
sb.setLength(0);
00104
00105
int c;
00106
int state = 0;
00107
00108
try {
00109
while ((c =
is.read()) >= 0) {
00110
switch (state) {
00111
case 0:
00112
if (c ==
CR) {
00113 state = 1;
00114 }
else {
00115
sb.append((
char)c);
00116 }
00117
break;
00118
case 1:
00119
if (c ==
LF) {
00120 state = 2;
00121 }
else if (c !=
CR) {
00122
sb.append((
char)c);
00123 state = 0;
00124 }
00125
break;
00126
case 2:
00127 state = 0;
00128
if (c ==
' ' || c ==
'\t') {
00129
sb.append(
' ');
00130 }
else {
00131
is.unread(c);
00132
next =
sb.toString();
00133
sb.setLength(0);
00134
return;
00135 }
00136
break;
00137 }
00138 }
00139
if (state == 2 &&
sb.toString().trim().length() > 0) {
00140
next =
sb.toString().trim();
00141
sb.setLength(0);
00142 }
00143 }
catch (IOException e) {
00144
Debug.print(e);
00145 }
00146 }
00147
00148
00149
00150
00151
00152
00153 public void getHeaderMap(Map headerMap)
throws IOException {
00154
while (
hasMoreElements()) {
00155 String header = (String)
nextElement();
00156
int idx = header.indexOf(
':');
00157
if (idx >= 0) {
00158 String headerName = header.substring(0, idx).trim();
00159 String headerVal = header.substring(idx+1).trim();
00160 headerMap.put(headerName.toLowerCase(), headerVal);
00161 }
else {
00162
throw new IOException(
"Bad header: '" + header +
"'");
00163 }
00164 }
00165 }
00166
00167 }