1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
10 import java.util.zip.*;
11 import org.ibex.util.*;
13 /** plays the role of InputStream, OutputStream, Reader and Writer, with logging and unchecked exceptions */
16 protected final In in;
17 protected final Out out;
18 private StringBuffer log = loggingEnabled ? new StringBuffer(16 * 1024) : null;
19 private String newLine = "\r\n";
20 private Stream in_next = null;
22 public Stream append(String in_next) { return appendStream(new Stream(in_next)); }
23 public Stream appendStream(Stream in_next) {
24 if (this.in_next != null)
25 this.in_next.appendStream(in_next);
27 this.in_next = in_next;
31 //public static boolean loggingEnabled = "true".equals(System.getProperty("ibex.io.stream.logEnabled", "false"));
32 public static boolean loggingEnabled = true;
34 public void transcribe(Stream out) { transcribe(out, false); }
35 public void transcribe(Stream out, boolean close) {
37 byte[] buf = new byte[1024];
39 int numread = in.read(buf, 0, buf.length);
40 if (numread==-1) { in.close(); break; }
41 out.out.write(buf, 0, numread);
43 if (close) out.close();
44 } catch (IOException ioe) { ioe(ioe); }
47 public void transcribe(StringBuffer out) {
49 char[] buf = new char[1024];
51 int numread = in.read(buf, 0, buf.length);
52 if (numread==-1) { in.close(); return; }
53 out.append(buf, 0, numread);
55 //} catch (IOException ioe) { ioe(ioe); }
58 public static int countLines(Stream s) {
60 while(s.readln() != null) ret++;
65 public Stream(byte[] b, int off, int len) { this.in = new Stream.In(new ByteArrayInputStream(b, off, len)); this.out=null; }
66 public Stream(InputStream in) { this.in = new Stream.In(in); this.out = null; }
67 public Stream( OutputStream out) { this.in = null; this.out = new Stream.Out(out); }
68 public Stream(InputStream in, OutputStream out) { this.in = new Stream.In(in); this.out = new Stream.Out(out); }
69 public Stream(String s) { this(new ByteArrayInputStream(s.getBytes())); }
70 public Stream(File f) {
71 try { this.in = new Stream.In(new FileInputStream(f)); } catch (IOException e) { ioe(e); throw new Error(); }
74 public Stream(Socket s) {
75 try { this.in = new Stream.In(s.getInputStream()); } catch (IOException e) { ioe(e); throw new Error(); }
76 try { this.out = new Stream.Out(s.getOutputStream()); } catch (IOException e) { ioe(e); throw new Error(); }
79 static int ioe(IOException e) {
80 if (e instanceof SocketException && e.toString().indexOf("Connection reset")!=-1)
81 throw new Closed(e.getMessage());
82 throw new StreamException(e);
84 public static class StreamException extends RuntimeException {
85 public StreamException(Exception e) { super(e); }
86 public StreamException(String s) { super(s); }
88 public static class EOF extends StreamException { public EOF() { super("End of stream"); } }
89 public static class Closed extends StreamException { public Closed(String s) { super(s); } }
92 private static Hashtable blocker = new Hashtable();
93 public static void kill(Thread thread) {
94 Stream block = (Stream)blocker.get(thread);
96 Log.warn(Stream.class, "thread " + thread + " is not blocked on a stream");
98 Log.warn(Stream.class, "asynchronously closing " + block);
103 public char peekc() {
104 Stream old = (Stream)blocker.get(Thread.currentThread());
106 blocker.put(Thread.currentThread(), this);
107 flush(); return in.getc(true);
108 } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
111 Stream old = (Stream)blocker.get(Thread.currentThread());
113 blocker.put(Thread.currentThread(), this);
114 flush(); char ret = in.getc(false); log(ret); return ret;
115 } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
117 public String readln() {
118 Stream old = (Stream)blocker.get(Thread.currentThread());
120 blocker.put(Thread.currentThread(), this);
121 flush(); String s = in.readln(); log(s); log('\n'); return s;
122 } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
125 public void print(String s) {
126 Stream old = (Stream)blocker.get(Thread.currentThread());
128 blocker.put(Thread.currentThread(), this);
132 } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
134 public void println(String s) {
135 Stream old = (Stream)blocker.get(Thread.currentThread());
137 blocker.put(Thread.currentThread(), this);
143 } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
145 public void flush() {
146 Stream old = (Stream)blocker.get(Thread.currentThread());
148 blocker.put(Thread.currentThread(), this);
149 if (out != null) try { out.w.flush(); } catch(IOException e) { ioe(e); }
150 } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
152 public int read(byte[] b, int off, int len) {
153 Stream old = (Stream)blocker.get(Thread.currentThread());
155 blocker.put(Thread.currentThread(), this);
157 int ret = in.readBytes(b, off, len);
158 if (log != null) log("\n[read " + ret + " bytes of binary data ]\n");
161 } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
163 public int read(char[] c, int off, int len) {
164 Stream old = (Stream)blocker.get(Thread.currentThread());
166 blocker.put(Thread.currentThread(), this);
168 int ret = in.read(c, off, len);
169 if (log != null && ret != -1) log(new String(c, off, ret));
171 } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
174 public void unread(String s) { in.unread(s); }
176 /** should not throw exceptions */
177 public void close() { try { if (in!=null) in.close(); } finally { if (out!=null) out.close(); } }
178 public void setNewline(String s) { newLine = s; }
181 /** dumps the connection log into a file */
182 public String dumpLog() { if (log==null) return ""; String ret = log.toString(); log = new StringBuffer(16 * 1024); return ret; }
183 private void log(String s) { if(log==null) return; if (!nnl) Log.note("\n[read ] "); Log.note(s + "\n"); nnl=false; if (log != null) log.append(s); }
184 private void logWrite(String s) { if(log==null) return; if (nnl) Log.note("\n"); Log.note("[write] "+s+"\n"); nnl=false; if (log != null) log.append(s); }
185 private void log(char c) { if(log==null) return; if (c == '\r') return; if (!nnl) Log.note("[read ] "); Log.note(c+""); nnl = c != '\n'; if (log != null) log.append(c); }
186 private boolean nnl = false;
188 private static class Out extends BufferedOutputStream {
189 private Writer w = new BufferedWriter(new OutputStreamWriter(this));
190 public Out(OutputStream out) { super(out); }
191 public void close() { try { super.close(); } catch (Exception e) { Log.error(this, e); } }
192 public void write(String s) { try { w.write(s); } catch (IOException e) { ioe(e); } }
195 private class In extends InputStream {
196 public final Reader reader = new InputStreamReader(this);
197 private /*final*/ InputStream orig;
198 public In(InputStream in) { orig = in; }
200 char[] cbuf = new char[8192];
204 byte[] buf = new byte[8192];
208 boolean flushing = false;
210 public int available() { return flushing ? 0 : (end - start); }
211 public void close() { try {
212 if (orig!=null) orig.close();
213 if (in_next != null) in_next.close(); // FIXME: correct?
214 } catch (Exception e) { Log.error(this, e); } }
216 public char getc(boolean peek) { try {
217 if (cstart == cend) {
219 cend = reader.read(cbuf, 0, cbuf.length);
223 if (in_next == null) throw new EOF();
227 return peek ? cbuf[cstart] : cbuf[cstart++];
228 } catch (IOException e) { return (char)ioe(e); } }
230 public String readln() { try {
232 for(int i=cstart; i<cend; i++)
233 if (cbuf[i] == '\n') {
234 // this should (in theory) handle CR, LF,
235 // CRLF, and LFCR properly, assuming that the
236 // file consistently uses the same ending
241 if (cbuf[begin] == '\r') { begin++; len--; }
242 while (len > 0 && cbuf[begin+len-1] == '\r') { len--; }
243 return new String(cbuf, begin, len);
246 int numread = reader.read(cbuf, cend, cbuf.length - cend);
249 if (cstart == cend) return null;
250 String ret = new String(cbuf, cstart, cend-cstart);
256 } catch (IOException e) { ioe(e); return null; } }
258 public int read(char[] c, int pos, int len) { try {
259 if (cstart == cend) {
261 cend = reader.read(cbuf, 0, cbuf.length);
262 if (cend == -1) { reader.close(); cend = cstart; return -1; }
264 if (len > cend - cstart) len = cend - cstart;
265 System.arraycopy(cbuf, cstart, c, pos, len);
268 } catch (IOException e) { ioe(e); return -1; } }
270 public int readBytes(byte[] b, int pos, int len) { flushchars(); return read(b, pos, len); }
271 public int read() { byte[] b = new byte[1]; if (read(b, 0, 1) == -1) return -1; return (int)b[0]; }
272 public int read(byte[] b, int pos, int len) { try {
275 end = orig.read(buf, 0, buf.length);
279 if (in_next==null) return -1;
280 return in_next.read(b, pos, len);
283 if (len > end - start) len = end - start;
284 System.arraycopy(buf, start, b, pos, len);
287 } catch (IOException e) { ioe(e); return -1; } }
289 private void growc(int s){char[] cbuf2=new char[cbuf.length+s*2];System.arraycopy(cbuf,0,cbuf2,0,cbuf.length);cbuf=cbuf2; }
290 private void shiftc() {
291 char[] cbuf2 = new char[cbuf.length];
292 System.arraycopy(cbuf, cstart, cbuf2, 0, cend-cstart);
297 private void ensurec(int space) { if (cend-cstart+space>cbuf.length) growc(space); if (cend+space>cbuf.length) shiftc(); }
299 private void growb(int s) { byte[] buf2 = new byte[buf.length+s*2]; System.arraycopy(buf,0,buf2,0,buf.length); buf=buf2; }
300 private void shiftb() { System.arraycopy(buf, start, buf, 0, end-start); end -= start; start = 0; }
301 private void ensureb(int space) { if (end-start+space>buf.length) growb(space); if (end+space>buf.length) shiftb(); }
302 private void ensureb2(int space) { if (end-start+space>buf.length) growb(space); if (start<space) unshiftb(); }
303 private void unshiftb() {
304 System.arraycopy(buf,start,buf,buf.length-(end-start),end-start);start=buf.length-(end-start);end=buf.length; }
306 public void unread(String s) { ensurec(s.length()); s.getChars(0, s.length(), cbuf, cend); cend += s.length(); }
308 private void flushchars() {
311 for(; reader.ready(); reader.read(cbuf, cend++, 1)) ensurec(10);
313 unreader.write(cbuf, cstart, cend-cstart);
316 } catch (IOException e) { ioe(e);
317 } finally { flushing = false; }
320 Writer unreader = new OutputStreamWriter(new InOutputStream());
321 private class InOutputStream extends OutputStream {
322 public void close() { }
323 public void write(int i) throws IOException { byte[] b = new byte[1]; b[0] = (byte)i; write(b, 0, 1); }
324 public void write(byte[] b) throws IOException { write(b, 0, b.length); }
325 public void write(byte[] b, int p, int l) {
327 System.arraycopy(b, p, buf, start-l, l);
333 public static interface Transformer {
334 public Stream transform(Stream in);