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