ea43ba7471266b51280cf010389b3c32026c9b00
[org.ibex.io.git] / src / org / ibex / io / Stream.java
1 // Copyright 2000-2007 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 // Features:
14 //   - automatically flush writer before reading on linked read/write pairs
15 //   - no checked exceptions thrown
16 //   - unified write(char), print(char), and write(byte)
17 //   - unreading/peeking
18 //   - transcribe
19 //   - append (daisy-chaining)
20 //   - automatically closes input streams when end reached
21
22 /** plays the role of InputStream, OutputStream, Reader and Writer, with logging and unchecked exceptions */
23 public class Stream {
24
25     protected final In in;
26     protected final Out out;
27     private         String newLine = "\r\n";
28     private         Stream in_next = null;
29
30     public  Stream(byte[] b, int off, int len) { this.in = new Stream.In(new ByteArrayInputStream(b, off, len)); this.out=null; }
31     public  Stream(InputStream in)                   { this.in = new Stream.In(in); this.out = null; }
32     public  Stream(                OutputStream out) { this.in = null;              this.out = new Stream.Out(out); }
33     public  Stream(InputStream in, OutputStream out) { this.in = new Stream.In(in); this.out = new Stream.Out(out); }
34     public  Stream(String s)                         { this(new ByteArrayInputStream(s.getBytes())); }
35     public  Stream(File f)                           {
36         try { this.in = new Stream.In(new FileInputStream(f)); } catch (IOException e) { ioe(e); throw new Error(); }
37         this.out = null;
38     }
39     public  Stream(Socket s) {
40         try { this.in = new Stream.In(s.getInputStream());    } catch (IOException e) { ioe(e); throw new Error(); }
41         try { this.out = new Stream.Out(s.getOutputStream()); } catch (IOException e) { ioe(e); throw new Error(); }
42     }
43
44     // Main API //////////////////////////////////////////////////////////////////////////////
45
46     public char   peekc()                          { flush(); return in.getc(true); }
47     public char   getc()                           { flush(); return in.getc(false); }
48     public String readln()                         { flush(); return in.readln(); }
49     public void   print(String s)                  { out.write(s); flush(); }
50     public void   println(String s)                { print(s); print(newLine); }
51     public void   flush()                          { if (out != null) out.flushWriter(); }
52     public int    read(byte[] b, int off, int len) { flush(); return in.readBytes(b, off, len); }
53     public int    read(char[] c, int off, int len) { flush(); return in.readChars(c, off, len); }
54     public void   close()                          { try { if (in!=null) in.close(); } finally { if (out!=null) out.close(); } }
55     public void   setNewline(String s)             { newLine = s; }
56
57     private static class Out extends BufferedOutputStream {
58         private Writer writer = new OutputStreamWriter(this);
59         public Out(OutputStream out) { super(out); }
60         public  void close() { try { super.close(); } catch (Exception e) { Log.error(this, e); } }
61         public  void write(String s) { try { writer.write(s); } catch (IOException e) { ioe(e); } }
62         private void flushWriter() { try { writer.flush(); } catch (IOException e) { ioe(e); } }
63         private boolean flushing = false;
64         public  void flush() {
65             if (flushing) return;
66             try {
67                 flushing = true;
68                 try {
69                     writer.flush();
70                 } finally { flushing = false; }
71                 super.flush();
72             } catch (IOException e) { ioe(e); }
73         }
74     }
75
76     private class In extends InputStream {
77         private ByteBufInputStream bbis;
78         private CharBufReader cbr;
79         public  Reader reader;
80         private Writer unreader;
81
82         public char getc(boolean peek) { return cbr.getc(peek); }
83         public String readln() { return cbr.readln(); }
84         public int read() { return bbis.read(); }
85         public int read(byte[] b) { try { return bbis.read(b); } catch (IOException e) { ioe(e); return 0; } }
86         public int read(byte[] b, int off, int len) { return bbis.read(b, off, len); }
87         public void close() { try { cbr.close(); } catch (Exception e) { Log.error(this, e); } }
88         public int readBytes(byte[] b, int off, int len) { return bbis.read(b, off, len); }
89         public int readChars(char[] c, int off, int len) { return cbr.read(c, off, len); }
90
91         public In(InputStream in) {
92             bbis = new ByteBufInputStream(in) {
93                     public void preread() {
94                         try {
95                             if (!cbr.ready()) return;
96                         } catch (IOException e) { ioe(e); }
97                         char[] c = new char[20];
98                         while(true) {
99                             try {
100                                 if (!cbr.ready()) break;
101                                 int numread = cbr.read(c, 0, c.length);
102                                 if (numread == -1) break;
103                                 unreader.write(c, 0, numread);
104                             } catch (IOException e) { ioe(e); }
105                         }
106                     }
107                 };
108             unreader = new OutputStreamWriter(new UnReaderStream(bbis));
109             cbr = new CharBufReader(new InputStreamReader(bbis));
110         }
111
112     }
113
114     // Utilities: append() and transcribe() //////////////////////////////////////////////////////////////////////////////
115
116     public Stream append(String in_next) { return appendStream(new Stream(in_next)); }
117     public Stream appendStream(Stream in_next) {
118         if (this.in_next != null)
119             this.in_next.appendStream(in_next);
120         else
121             this.in_next = in_next;
122         return this;
123     }
124
125     public void transcribe(Stream out) { transcribe(out, false); }
126     public void transcribe(Stream out, boolean close) {
127         try {
128             byte[] buf = new byte[1024];
129             while(true) {
130                 int numread = in.read(buf, 0, buf.length);
131                 if (numread==-1) { in.close(); break; }
132                 out.out.write(buf, 0, numread);
133             }
134             if (close) out.close();
135         } catch (IOException ioe) { ioe(ioe); }
136     }
137
138     public void transcribe(StringBuffer out) {
139         char[] buf = new char[1024];
140         while(true) {
141             int numread = in.readChars(buf, 0, buf.length);
142             if (numread==-1) { in.close(); return; }
143             out.append(buf, 0, numread);
144         }
145     }
146
147     public static int countLines(Stream s) {
148         System.out.println("counting lines...");
149         int ret = 0;
150         while(s.readln() != null) ret++;
151         s.close();
152         return ret;
153     }
154
155     // Exceptions //////////////////////////////////////////////////////////////////////////////
156
157     static int ioe(IOException e) {
158         if (e instanceof SocketException && e.toString().indexOf("Connection reset")!=-1)
159             throw new Closed(e.getMessage());
160         throw new StreamException(e);
161     }
162     public static class StreamException extends RuntimeException {
163         public StreamException(Exception e) { super(e); }
164         public StreamException(String s)    { super(s); }
165     }
166     public static class EOF             extends StreamException  { public EOF() { super("End of stream"); } }
167     public static class Closed          extends StreamException  { public Closed(String s) { super(s); } }
168 }