stream doesnt need ibex.net
[org.ibex.io.git] / src / org / ibex / io / Stream.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [LGPL]
2 package org.ibex.io;
3
4 import java.io.*;
5 import java.net.*;
6 import java.util.zip.*;
7 import org.ibex.util.*;
8
9 /** plays the role of InputStream, OutputStream, Reader and Writer, with logging and unchecked exceptions */
10 public class Stream {
11
12     protected final In in;
13     protected final Out out;
14     private         StringBuffer log = loggingEnabled ? new StringBuffer(16 * 1024) : null;
15     private         String newLine = "\r\n";
16
17     public static boolean loggingEnabled = System.getProperty("ibex.io.stream.logEnabled", "true") != null;
18
19     public  Stream(InputStream in)                   { this.in = new Stream.In(in); this.out = null; }
20     public  Stream(                OutputStream out) { this.in = null;              this.out = new Stream.Out(out); }
21     public  Stream(InputStream in, OutputStream out) { this.in = new Stream.In(in); this.out = new Stream.Out(out); }
22     public  Stream(String s)                         { this(new ByteArrayInputStream(s.getBytes())); }
23     public  Stream(Socket s) {
24         try { this.in = new Stream.In(s.getInputStream());    } catch (IOException e) { throw new StreamException(e); }
25         try { this.out = new Stream.Out(s.getOutputStream()); } catch (IOException e) { throw new StreamException(e); }
26     }
27
28     private static int ioe(Exception e) { throw new StreamException(e); }
29     public static class StreamException extends RuntimeException {
30         public StreamException(Exception e) { super(e); }
31         public StreamException(String s)    { super(s); }
32     }
33     public static class EOF             extends StreamException  { public EOF() { super("End of stream"); } }
34     public static class Closed          extends StreamException  { public Closed(String s) { super(s); } }
35
36
37     public char   peekc()                          { flush(); return in.getc(true); }
38     public char   getc()                           { flush(); char ret = in.getc(false); log(ret); return ret; }
39     public String readln()                         { flush(); String s = in.readln(); log(s); log('\n'); return s; }
40     public int    read(byte[] b, int off, int len) {
41         flush();
42         int ret = in.readBytes(b, off, len);
43         if (log != null) log("\n[read " + ret + " bytes of binary data ]\n");
44         nnl = false;
45         return ret;
46     }
47     public int    read(char[] c, int off, int len) {
48         flush();
49         int ret = in.read(c, off, len);
50         if (log != null && ret != -1) log(new String(c, off, ret));
51         return ret;
52     }
53
54     public void   unread(String s)                 { in.unread(s); }
55
56     public void   println()                        { println(""); }
57     public void   println(String s)                { logWrite(s); out.write(s); out.write(newLine); }
58
59     public void   flush()                          { if (out != null) try { out.w.flush(); } catch(IOException e) { ioe(e); } }
60     public void   close()                          { in.close(); out.close(); }
61     public void   setNewline(String s)             { newLine = s; }
62
63
64     /** dumps the connection log into a file */
65     public  String dumpLog()         { String ret = log.toString(); log = new StringBuffer(16 * 1024); return ret; }
66     private void  log(String s)      { if(log==null) return; if (!nnl) Log.note("\n[read ] "); Log.note(s + "\n"); nnl=false; }
67     private void  logWrite(String s) { if(log==null) return; if (nnl) Log.note("\n"); Log.note("[write] "+s+"\n"); nnl=false; }
68     private void  log(char c)        { if(log==null) return; if (c == '\r') return; if (!nnl) Log.note("[read ] "); Log.note(c+""); nnl = c != '\n'; }
69     private boolean nnl = false;
70
71     private static class Out extends BufferedOutputStream {
72         private Writer w = new BufferedWriter(new OutputStreamWriter(this));
73         public Out(OutputStream out) { super(out); }
74         public void close() { try { super.close(); } catch (Exception e) { Log.error(this, e); } }
75         public void write(String s) { try { w.write(s); } catch (IOException e) { ioe(e); } }
76     }
77
78     private static class In extends InputStream {
79         public Reader reader = new InputStreamReader(this);
80         private final InputStream orig;
81         public In(InputStream in) { orig = in; }
82
83         char[] cbuf = new char[8192];
84         int cstart = 0;
85         int cend = 0;
86
87         byte[] buf = new byte[8192];
88         int start = 0;
89         int end = 0;
90
91         boolean flushing = false;
92
93         public int available() { return flushing ? 0 : (end - start); }
94         public void close() { try { orig.close(); } catch (Exception e) { Log.error(this, e); } }
95
96         public char getc(boolean peek) { try {
97             if (cstart == cend) {
98                 cstart = 0;
99                 cend = reader.read(cbuf, 0, cbuf.length);
100                 if (cend == -1) { cend = cstart; throw new EOF(); }
101             }
102             return peek ? cbuf[cstart] : cbuf[cstart++];
103         } catch (IOException e) { return (char)ioe(e); } }
104
105         public String readln() { try {
106             while(true) {
107                 for(int i=cstart; i<cend; i++)
108                     if (cbuf[i] == '\n') {
109                         // this should (in theory) handle CR, LF,
110                         // CRLF, and LFCR properly, assuming that the
111                         // file consistently uses the same ending
112                         // throughout.
113                         int begin = cstart;
114                         int len = i-cstart;
115                         cstart = i+1;
116                         if (cbuf[begin] == '\r') { begin++; len--; }
117                         if (len > 0 && cbuf[begin+len-1] == '\r') { len--; }
118                         return new String(cbuf, begin, len);
119                     }
120                 ensurec(256);
121                 int numread = reader.read(cbuf, cend, cbuf.length - cend);
122                 if (numread == -1) {
123                     if (cstart == cend) return null;
124                     String ret = new String(cbuf, cstart, cend-cstart);
125                     cstart = cend = 0;
126                     return ret;
127                 }
128                 cend += numread;
129             }
130         } catch (IOException e) { ioe(e); return null; } }
131
132         public int read(char[] c, int pos, int len) { try {
133             if (cstart == cend) {
134                 cstart = 0;
135                 cend = reader.read(cbuf, 0, cbuf.length);
136                 if (cend == -1) { cend = cstart; return -1; }
137             }
138             if (len > cend - cstart) len = cend - cstart;
139             System.arraycopy(cbuf, cstart, c, pos, len);
140             cstart += len;
141             return len;
142         } catch (IOException e) { ioe(e); return -1; } }
143
144         public int readBytes(byte[] b, int pos, int len) { flushchars(); return read(b, pos, len); }
145         public int read() { byte[] b = new byte[1]; if (read(b, 0, 1) == -1) return -1; return (int)b[0]; } 
146         public int read(byte[] b, int pos, int len) { try {
147             if (start == end) {
148                 start = 0;
149                 end = orig.read(buf, 0, buf.length);
150                 if (end == -1) { end = start; return -1; }
151             }
152             if (len > end - start) len = end - start;
153             System.arraycopy(buf, start, b, pos, len);
154             start += len;
155             return len;
156         } catch (IOException e) { ioe(e); return -1; } }
157
158         private void growc(int s){char[] cbuf2=new char[cbuf.length+s*2];System.arraycopy(cbuf,0,cbuf2,0,cbuf.length);cbuf=cbuf2; }
159         private void shiftc() {
160             char[] cbuf2 = new char[cbuf.length];
161             System.arraycopy(cbuf, cstart, cbuf2, 0, cend-cstart);
162             cend -= cstart;
163             cstart = 0;
164             cbuf = cbuf2;
165         }
166         private void ensurec(int space) { if (cend-cstart+space>cbuf.length) growc(space); if (cend+space>cbuf.length) shiftc(); }
167
168         private void growb(int s) { byte[] buf2 = new byte[buf.length+s*2]; System.arraycopy(buf,0,buf2,0,buf.length); buf=buf2; }
169         private void shiftb() { System.arraycopy(buf, start, buf, 0, end-start); end -= start; start = 0; }
170         private void ensureb(int space) { if (end-start+space>buf.length) growb(space); if (end+space>buf.length) shiftb(); }
171         private void ensureb2(int space) { if (end-start+space>buf.length) growb(space); if (start<space) unshiftb(); }
172         private void unshiftb() {
173             System.arraycopy(buf,start,buf,buf.length-(end-start),end-start);start=buf.length-(end-start);end=buf.length; }
174
175         public  void unread(String s) { ensurec(s.length()); s.getChars(0, s.length(), cbuf, cend); cend += s.length(); }
176
177         private void flushchars() {
178             try {
179                 flushing = true;
180                 for(; reader.ready(); reader.read(cbuf, cend++, 1)) ensurec(1);
181                 unreader.write(cbuf, cstart, cend);
182                 cstart = cend = 0;
183                 unreader.flush();
184             } catch (IOException e) { ioe(e);
185             } finally { flushing = false; }
186         }
187
188         Writer unreader = new OutputStreamWriter(new OutputStream() {
189                 public void close() { }
190                 public void write(int i) throws IOException { byte[] b = new byte[1]; b[0] = (byte)i; write(b, 0, 1); }
191                 public void write(byte[] b) throws IOException { write(b, 0, b.length); }
192                 public void write(byte[] b, int p, int l) {
193                     ensureb2(l);
194                     System.arraycopy(b, p, buf, start-l, l);
195                     start -= l;
196                 }
197             });
198     }
199 }