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