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