remember to put newlines in the log
[org.ibex.io.git] / src / org / ibex / io / Stream.java
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.
4
5 package org.ibex.io;
6
7 import java.io.*;
8 import java.net.*;
9 import java.util.*;
10 import java.util.zip.*;
11 import org.ibex.util.*;
12
13 /** plays the role of InputStream, OutputStream, Reader and Writer, with logging and unchecked exceptions */
14 public class Stream {
15
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;
21
22     public Stream appendStream(Stream in_next) {
23         if (this.in_next != null) return this.in_next.appendStream(in_next);
24         this.in_next = in_next;
25         return this;
26     }
27
28     public static boolean loggingEnabled = "true".equals(System.getProperty("ibex.io.stream.logEnabled", "false"));
29
30     public void transcribe(Stream out) {
31         try {
32             byte[] buf = new byte[1024];
33             while(true) {
34                 int numread = in.read(buf, 0, buf.length);
35                 if (numread==-1) return;
36                 out.out.write(buf, 0, numread);
37             }
38         } catch (IOException ioe) { throw new StreamException(ioe); }
39     }
40
41     public void transcribe(StringBuffer out) {
42         //try {
43             char[] buf = new char[1024];
44             while(true) {
45                 int numread = in.read(buf, 0, buf.length);
46                 if (numread==-1) return;
47                 out.append(buf, 0, numread);
48             }
49             //} catch (IOException ioe) { throw new StreamException(ioe); }
50     }
51
52     public static int countLines(Stream s) {
53         int ret = 0;
54         while(s.readln() != null) ret++;
55         return ret;
56     }
57
58     public Stream(byte[] b, int off, int len) { this.in = new Stream.In(new ByteArrayInputStream(b, off, len)); this.out=null; }
59     public  Stream(InputStream in)                   { this.in = new Stream.In(in); this.out = null; }
60     public  Stream(                OutputStream out) { this.in = null;              this.out = new Stream.Out(out); }
61     public  Stream(InputStream in, OutputStream out) { this.in = new Stream.In(in); this.out = new Stream.Out(out); }
62     public  Stream(String s)                         { this(new ByteArrayInputStream(s.getBytes())); }
63     public  Stream(File f)                           {
64         try { this.in = new Stream.In(new FileInputStream(f)); } catch (IOException e) { throw new StreamException(e); }
65         this.out = null;
66     }
67     public  Stream(Socket s) {
68         try { this.in = new Stream.In(s.getInputStream());    } catch (IOException e) { throw new StreamException(e); }
69         try { this.out = new Stream.Out(s.getOutputStream()); } catch (IOException e) { throw new StreamException(e); }
70     }
71
72     private static int ioe(Exception e) { throw new StreamException(e); }
73     public static class StreamException extends RuntimeException {
74         public StreamException(Exception e) { super(e); }
75         public StreamException(String s)    { super(s); }
76     }
77     public static class EOF             extends StreamException  { public EOF() { super("End of stream"); } }
78     public static class Closed          extends StreamException  { public Closed(String s) { super(s); } }
79
80
81     private static Hashtable blocker = new Hashtable();
82     public static void kill(Thread thread) {
83         Stream block = (Stream)blocker.get(thread);
84         if (block == null) {
85             Log.warn(Stream.class, "thread " + thread + " is not blocked on a stream");
86         } else {
87             Log.warn(Stream.class, "asynchronously closing " + block);
88             block.close();
89         }
90     }
91
92     public char   peekc()                          {
93         Stream old = (Stream)blocker.get(Thread.currentThread());
94         try {
95             blocker.put(Thread.currentThread(), this);
96             flush(); return in.getc(true);
97         } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
98     }
99     public char   getc()                           {
100         Stream old = (Stream)blocker.get(Thread.currentThread());
101         try {
102             blocker.put(Thread.currentThread(), this);
103             flush(); char ret = in.getc(false); log(ret); return ret;
104         } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
105     }   
106     public String readln()                         {
107         Stream old = (Stream)blocker.get(Thread.currentThread());
108         try {
109             blocker.put(Thread.currentThread(), this);
110             flush(); String s = in.readln(); log(s); log('\n'); return s;
111         } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
112     }
113     
114     public void   print(String s) {
115         Stream old = (Stream)blocker.get(Thread.currentThread());
116         try {
117             blocker.put(Thread.currentThread(), this);
118             logWrite(s);
119             out.write(s);
120             flush();
121         } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
122     }
123     public void   println(String s) {
124         Stream old = (Stream)blocker.get(Thread.currentThread());
125         try {
126             blocker.put(Thread.currentThread(), this);
127             logWrite(s);
128             logWrite(newLine);
129             out.write(s);
130             out.write(newLine);
131             flush();
132         } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
133     }
134     public void   flush()                          {
135         Stream old = (Stream)blocker.get(Thread.currentThread());
136         try {
137             blocker.put(Thread.currentThread(), this);
138             if (out != null) try { out.w.flush(); } catch(IOException e) { ioe(e); }
139         } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
140     }
141     public int    read(byte[] b, int off, int len) {
142         Stream old = (Stream)blocker.get(Thread.currentThread());
143         try {
144             blocker.put(Thread.currentThread(), this);
145             flush();
146             int ret = in.readBytes(b, off, len);
147             if (log != null) log("\n[read " + ret + " bytes of binary data ]\n");
148             nnl = false;
149             return ret;
150         } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
151     }
152     public int    read(char[] c, int off, int len) {
153         Stream old = (Stream)blocker.get(Thread.currentThread());
154         try {
155             blocker.put(Thread.currentThread(), this);
156             flush();
157             int ret = in.read(c, off, len);
158             if (log != null && ret != -1) log(new String(c, off, ret));
159             return ret;
160         } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
161     }
162
163     public void   unread(String s)                 { in.unread(s); }
164
165     public void   close()                          { try { if (in!=null) in.close(); } finally { if (out!=null) out.close(); } }
166     public void   setNewline(String s)             { newLine = s; }
167
168
169     /** dumps the connection log into a file */
170     public  String dumpLog()         { if (log==null) return ""; String ret = log.toString(); log = new StringBuffer(16 * 1024); return ret; }
171     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); }
172     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); }
173     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); }
174     private boolean nnl = false;
175
176     private static class Out extends BufferedOutputStream {
177         private Writer w = new BufferedWriter(new OutputStreamWriter(this));
178         public Out(OutputStream out) { super(out); }
179         public void close() { try { super.close(); } catch (Exception e) { Log.error(this, e); } }
180         public void write(String s) { try { w.write(s); } catch (IOException e) { ioe(e); } }
181     }
182
183     private class In extends InputStream {
184         public final Reader reader = new InputStreamReader(this);
185         private /*final*/ InputStream orig;
186         public In(InputStream in) { orig = in; }
187
188         char[] cbuf = new char[8192];
189         int cstart = 0;
190         int cend = 0;
191
192         byte[] buf = new byte[8192];
193         int start = 0;
194         int end = 0;
195
196         boolean flushing = false;
197
198         public int available() { return flushing ? 0 : (end - start); }
199         public void close() { try { if (orig!=null) orig.close(); } catch (Exception e) { Log.error(this, e); } }
200
201         public char getc(boolean peek) { try {
202             if (cstart == cend) {
203                 cstart = 0;
204                 cend = reader.read(cbuf, 0, cbuf.length);
205                 if (cend == -1) {
206                     cend = cstart;
207                     if (in_next == null) throw new EOF();
208                     // FIXME: sketchy
209                     orig = in_next.in.orig;
210                     in_next = in_next.in_next;
211                     return getc(peek);
212                 }
213             }
214             return peek ? cbuf[cstart] : cbuf[cstart++];
215         } catch (IOException e) { return (char)ioe(e); } }
216
217         public String readln() { try {
218             while(true) {
219                 for(int i=cstart; i<cend; i++)
220                     if (cbuf[i] == '\n') {
221                         // this should (in theory) handle CR, LF,
222                         // CRLF, and LFCR properly, assuming that the
223                         // file consistently uses the same ending
224                         // throughout.
225                         int begin = cstart;
226                         int len = i-cstart;
227                         cstart = i+1;
228                         if (cbuf[begin] == '\r') { begin++; len--; }
229                         while (len > 0 && cbuf[begin+len-1] == '\r') { len--; }
230                         return new String(cbuf, begin, len);
231                     }
232                 ensurec(256);
233                 int numread = reader.read(cbuf, cend, cbuf.length - cend);
234                 if (numread == -1) {
235                     if (cstart == cend) return null;
236                     String ret = new String(cbuf, cstart, cend-cstart);
237                     cstart = cend = 0;
238                     return ret;
239                 }
240                 cend += numread;
241             }
242         } catch (IOException e) { ioe(e); return null; } }
243
244         public int read(char[] c, int pos, int len) { try {
245             if (cstart == cend) {
246                 cstart = 0;
247                 cend = reader.read(cbuf, 0, cbuf.length);
248                 if (cend == -1) { cend = cstart; return -1; }
249             }
250             if (len > cend - cstart) len = cend - cstart;
251             System.arraycopy(cbuf, cstart, c, pos, len);
252             cstart += len;
253             return len;
254         } catch (IOException e) { ioe(e); return -1; } }
255
256         public int readBytes(byte[] b, int pos, int len) { flushchars(); return read(b, pos, len); }
257         public int read() { byte[] b = new byte[1]; if (read(b, 0, 1) == -1) return -1; return (int)b[0]; } 
258         public int read(byte[] b, int pos, int len) { try {
259             if (start == end) {
260                 start = 0;
261                 end = orig.read(buf, 0, buf.length);
262                 if (end == -1) { end = start; return -1; }
263             }
264             if (len > end - start) len = end - start;
265             System.arraycopy(buf, start, b, pos, len);
266             start += len;
267             return len;
268         } catch (IOException e) { ioe(e); return -1; } }
269
270         private void growc(int s){char[] cbuf2=new char[cbuf.length+s*2];System.arraycopy(cbuf,0,cbuf2,0,cbuf.length);cbuf=cbuf2; }
271         private void shiftc() {
272             char[] cbuf2 = new char[cbuf.length];
273             System.arraycopy(cbuf, cstart, cbuf2, 0, cend-cstart);
274             cend -= cstart;
275             cstart = 0;
276             cbuf = cbuf2;
277         }
278         private void ensurec(int space) { if (cend-cstart+space>cbuf.length) growc(space); if (cend+space>cbuf.length) shiftc(); }
279
280         private void growb(int s) { byte[] buf2 = new byte[buf.length+s*2]; System.arraycopy(buf,0,buf2,0,buf.length); buf=buf2; }
281         private void shiftb() { System.arraycopy(buf, start, buf, 0, end-start); end -= start; start = 0; }
282         private void ensureb(int space) { if (end-start+space>buf.length) growb(space); if (end+space>buf.length) shiftb(); }
283         private void ensureb2(int space) { if (end-start+space>buf.length) growb(space); if (start<space) unshiftb(); }
284         private void unshiftb() {
285             System.arraycopy(buf,start,buf,buf.length-(end-start),end-start);start=buf.length-(end-start);end=buf.length; }
286
287         public  void unread(String s) { ensurec(s.length()); s.getChars(0, s.length(), cbuf, cend); cend += s.length(); }
288
289         private void flushchars() {
290             try {
291                 flushing = true;
292                 for(; reader.ready(); reader.read(cbuf, cend++, 1)) ensurec(1);
293                 unreader.write(cbuf, cstart, cend);
294                 cstart = cend = 0;
295                 unreader.flush();
296             } catch (IOException e) { ioe(e);
297             } finally { flushing = false; }
298         }
299
300         Writer unreader = new OutputStreamWriter(new InOutputStream());
301         private class InOutputStream extends OutputStream {
302             public void close() { }
303             public void write(int i) throws IOException { byte[] b = new byte[1]; b[0] = (byte)i; write(b, 0, 1); }
304             public void write(byte[] b) throws IOException { write(b, 0, b.length); }
305             public void write(byte[] b, int p, int l) {
306                 ensureb2(l);
307                 System.arraycopy(b, p, buf, start-l, l);
308                 start -= l;
309             }
310         }
311     }
312
313     public static interface Transformer {
314         public Stream transform(Stream in);
315     }
316
317 }