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