/* * $Id$ * * Copyright 1999 Integrated Computer Solutions, Inc. All Rights Reserved * * This source code is protected by copyright law and international treaties. * Unauthorized reproduction or distribution of this source code module or any * portion of it, may result in severe civil and criminal penalties, and will * be prosecuted to the maximum extent possible under law. */ package com.ics.lib; import com.ics.util.*; import java.io.*; import java.net.*; /** HTTPInput provides the right kind of input stream for HTTP reading */ public class HTTPInputStream extends BufferedInputStream { /** One character lookahead */ int pushback = -1; /** flag that fakes an EOF on next read */ boolean atEnd = false; public HTTPInputStream(InputStream in) { super(in, 2048); } public HTTPInputStream(InputStream in, int size) { super(in, size); } /** Calling signalEOF will make the next read return an eof */ public void signalEOF() { atEnd = true; } /** emulate the InputStream read call */ public int read() throws IOException { if(atEnd) { atEnd = false; return -1; } if(pushback >= 0) { int ret = pushback; pushback = -1; return ret; } return super.read(); } /** emulate the InputStream read call */ public int read(byte b[], int off, int len) throws IOException { // System.out.println("called HTTPInputStream.read(b, o, l)"); if(atEnd) { atEnd = false; return -1; } if(pushback >= 0) { b[off] = (byte) pushback; off += 1; pushback = -1; } int ret = super.read(b, off, len); // System.out.print("read->>"); // for(int i = 0; i < ret; i++) { // System.out.print((char) b[off+i]); // } // System.out.println("<<"); return ret; } /** read bytes from the input stream until an end of line. * CRLF -s * */ public String readLine() throws IOException { StringBuffer ret = new StringBuffer(); int c; if(atEnd) { atEnd = false; return null; } if(pushback >= 0) { ret.append((char)pushback); pushback = -1; } while(true) { c = super.read(); if(c <= 0) break; // Either LF or CR or CRLF ends line if(c == '\n') break; if(c == '\r') { c = super.read(); // CRxx results in re-read of xx if(c != '\n') pushback = c; break; } ret.append((char)c); } // System.out.println("readLine: ret >>" + ret.toString()+"<<"); return new String(ret); } /** close is needed to compensate for a bug in the XML4J parser. * It thinks it should close the stream when it has got the eof. */ public void close() throws IOException { // LogManager.danger("HTTP","Who called HTTPInputStream.close"); } }