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