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