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