added transcribe(StringBuffer)
[org.ibex.io.git] / src / org / ibex / io / Stream.java
index 0732016..019a2f4 100644 (file)
@@ -1,8 +1,12 @@
-// Copyright 2004 Adam Megacz, see the COPYING file for licensing [LGPL]
+// Copyright 2000-2005 the Contributors, as shown in the revision logs.
+// Licensed under the Apache Public Source License 2.0 ("the License").
+// You may not use this file except in compliance with the License.
+
 package org.ibex.io;
 
 import java.io.*;
 import java.net.*;
+import java.util.*;
 import java.util.zip.*;
 import org.ibex.util.*;
 
@@ -13,13 +17,53 @@ public class Stream {
     protected final Out out;
     private         StringBuffer log = loggingEnabled ? new StringBuffer(16 * 1024) : null;
     private         String newLine = "\r\n";
+    private   Stream in_next = null;
+
+    public Stream appendStream(Stream in_next) {
+        if (this.in_next != null) return this.in_next.appendStream(in_next);
+        this.in_next = in_next;
+        return this;
+    }
+
+    public static boolean loggingEnabled = "true".equals(System.getProperty("ibex.io.stream.logEnabled", "false"));
+
+    public void transcribe(Stream out) {
+        try {
+            byte[] buf = new byte[1024];
+            while(true) {
+                int numread = in.read(buf, 0, buf.length);
+                if (numread==-1) return;
+                out.out.write(buf, 0, numread);
+            }
+        } catch (IOException ioe) { throw new StreamException(ioe); }
+    }
 
-    public static boolean loggingEnabled = System.getProperty("ibex.io.stream.logEnabled", "true") != null;
+    public void transcribe(StringBuffer out) {
+        //try {
+            char[] buf = new char[1024];
+            while(true) {
+                int numread = in.read(buf, 0, buf.length);
+                if (numread==-1) return;
+                out.append(buf, 0, numread);
+            }
+            //} catch (IOException ioe) { throw new StreamException(ioe); }
+    }
+
+    public static int countLines(Stream s) {
+        int ret = 0;
+        while(s.readln() != null) ret++;
+        return ret;
+    }
 
+    public Stream(byte[] b, int off, int len) { this.in = new Stream.In(new ByteArrayInputStream(b, off, len)); this.out=null; }
     public  Stream(InputStream in)                   { this.in = new Stream.In(in); this.out = null; }
     public  Stream(                OutputStream out) { this.in = null;              this.out = new Stream.Out(out); }
     public  Stream(InputStream in, OutputStream out) { this.in = new Stream.In(in); this.out = new Stream.Out(out); }
     public  Stream(String s)                         { this(new ByteArrayInputStream(s.getBytes())); }
+    public  Stream(File f)                           {
+        try { this.in = new Stream.In(new FileInputStream(f)); } catch (IOException e) { throw new StreamException(e); }
+        this.out = null;
+    }
     public  Stream(Socket s) {
         try { this.in = new Stream.In(s.getInputStream());    } catch (IOException e) { throw new StreamException(e); }
         try { this.out = new Stream.Out(s.getOutputStream()); } catch (IOException e) { throw new StreamException(e); }
@@ -34,38 +78,98 @@ public class Stream {
     public static class Closed          extends StreamException  { public Closed(String s) { super(s); } }
 
 
-    public char   peekc()                          { flush(); return in.getc(true); }
-    public char   getc()                           { flush(); char ret = in.getc(false); log(ret); return ret; }
-    public String readln()                         { flush(); String s = in.readln(); log(s); log('\n'); return s; }
+    private static Hashtable blocker = new Hashtable();
+    public static void kill(Thread thread) {
+        Stream block = (Stream)blocker.get(thread);
+        if (block == null) {
+            Log.warn(Stream.class, "thread " + thread + " is not blocked on a stream");
+        } else {
+            Log.warn(Stream.class, "asynchronously closing " + block);
+            block.close();
+        }
+    }
+
+    public char   peekc()                          {
+        Stream old = (Stream)blocker.get(Thread.currentThread());
+        try {
+            blocker.put(Thread.currentThread(), this);
+            flush(); return in.getc(true);
+        } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
+    }
+    public char   getc()                           {
+        Stream old = (Stream)blocker.get(Thread.currentThread());
+        try {
+            blocker.put(Thread.currentThread(), this);
+            flush(); char ret = in.getc(false); log(ret); return ret;
+        } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
+    }   
+    public String readln()                         {
+        Stream old = (Stream)blocker.get(Thread.currentThread());
+        try {
+            blocker.put(Thread.currentThread(), this);
+            flush(); String s = in.readln(); log(s); log('\n'); return s;
+        } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
+    }
+    
+    public void   print(String s) {
+        Stream old = (Stream)blocker.get(Thread.currentThread());
+        try {
+            blocker.put(Thread.currentThread(), this);
+            logWrite(s);
+            out.write(s);
+            flush();
+        } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
+    }
+    public void   println(String s) {
+        Stream old = (Stream)blocker.get(Thread.currentThread());
+        try {
+            blocker.put(Thread.currentThread(), this);
+            logWrite(s);
+            out.write(s);
+            out.write(newLine);
+            flush();
+        } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
+    }
+    public void   flush()                          {
+        Stream old = (Stream)blocker.get(Thread.currentThread());
+        try {
+            blocker.put(Thread.currentThread(), this);
+            if (out != null) try { out.w.flush(); } catch(IOException e) { ioe(e); }
+        } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
+    }
     public int    read(byte[] b, int off, int len) {
-        flush();
-        int ret = in.readBytes(b, off, len);
-        if (log != null) log("\n[read " + ret + " bytes of binary data ]\n");
-        nnl = false;
-        return ret;
+        Stream old = (Stream)blocker.get(Thread.currentThread());
+        try {
+            blocker.put(Thread.currentThread(), this);
+            flush();
+            int ret = in.readBytes(b, off, len);
+            if (log != null) log("\n[read " + ret + " bytes of binary data ]\n");
+            nnl = false;
+            return ret;
+        } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
     }
     public int    read(char[] c, int off, int len) {
-        flush();
-        int ret = in.read(c, off, len);
-        if (log != null && ret != -1) log(new String(c, off, ret));
-        return ret;
+        Stream old = (Stream)blocker.get(Thread.currentThread());
+        try {
+            blocker.put(Thread.currentThread(), this);
+            flush();
+            int ret = in.read(c, off, len);
+            if (log != null && ret != -1) log(new String(c, off, ret));
+            return ret;
+        } finally { if (old == null) blocker.remove(Thread.currentThread()); else blocker.put(Thread.currentThread(), old); }
     }
 
     public void   unread(String s)                 { in.unread(s); }
 
-    public void   println()                        { println(""); }
-    public void   println(String s)                { logWrite(s); out.write(s); out.write(newLine); }
-
-    public void   flush()                          { if (out != null) try { out.w.flush(); } catch(IOException e) { ioe(e); } }
-    public void   close()                          { in.close(); out.close(); }
+    public void   close()                          { try { if (in!=null) in.close(); } finally { if (out!=null) out.close(); } }
     public void   setNewline(String s)             { newLine = s; }
 
 
     /** dumps the connection log into a file */
-    public  String dumpLog()         { String ret = log.toString(); log = new StringBuffer(16 * 1024); return ret; }
-    private void  log(String s)      { if(log==null) return; if (!nnl) Log.note("\n[read ] "); Log.note(s + "\n"); nnl=false; }
-    private void  logWrite(String s) { if(log==null) return; if (nnl) Log.note("\n"); Log.note("[write] "+s+"\n"); nnl=false; }
-    private void  log(char c)        { if(log==null) return; if (c == '\r') return; if (!nnl) Log.note("[read ] "); Log.note(c+""); nnl = c != '\n'; }
+    public  String dumpLog()         { if (log==null) return ""; String ret = log.toString(); log = new StringBuffer(16 * 1024); return ret; }
+    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); }
+    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); }
+    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); }
     private boolean nnl = false;
 
     private static class Out extends BufferedOutputStream {
@@ -75,9 +179,9 @@ public class Stream {
         public void write(String s) { try { w.write(s); } catch (IOException e) { ioe(e); } }
     }
 
-    private static class In extends InputStream {
-        public Reader reader = new InputStreamReader(this);
-        private final InputStream orig;
+    private class In extends InputStream {
+        public final Reader reader = new InputStreamReader(this);
+        private /*final*/ InputStream orig;
         public In(InputStream in) { orig = in; }
 
         char[] cbuf = new char[8192];
@@ -91,13 +195,20 @@ public class Stream {
         boolean flushing = false;
 
         public int available() { return flushing ? 0 : (end - start); }
-        public void close() { try { orig.close(); } catch (Exception e) { Log.error(this, e); } }
+        public void close() { try { if (orig!=null) orig.close(); } catch (Exception e) { Log.error(this, e); } }
 
         public char getc(boolean peek) { try {
             if (cstart == cend) {
                 cstart = 0;
                 cend = reader.read(cbuf, 0, cbuf.length);
-                if (cend == -1) { cend = cstart; throw new EOF(); }
+                if (cend == -1) {
+                    cend = cstart;
+                    if (in_next == null) throw new EOF();
+                    // FIXME: sketchy
+                    orig = in_next.in.orig;
+                    in_next = in_next.in_next;
+                    return getc(peek);
+                }
             }
             return peek ? cbuf[cstart] : cbuf[cstart++];
         } catch (IOException e) { return (char)ioe(e); } }
@@ -114,7 +225,7 @@ public class Stream {
                         int len = i-cstart;
                         cstart = i+1;
                         if (cbuf[begin] == '\r') { begin++; len--; }
-                        if (len > 0 && cbuf[begin+len-1] == '\r') { len--; }
+                        while (len > 0 && cbuf[begin+len-1] == '\r') { len--; }
                         return new String(cbuf, begin, len);
                     }
                 ensurec(256);
@@ -185,15 +296,21 @@ public class Stream {
             } finally { flushing = false; }
         }
 
-        Writer unreader = new OutputStreamWriter(new OutputStream() {
-                public void close() { }
-                public void write(int i) throws IOException { byte[] b = new byte[1]; b[0] = (byte)i; write(b, 0, 1); }
-                public void write(byte[] b) throws IOException { write(b, 0, b.length); }
-                public void write(byte[] b, int p, int l) {
-                    ensureb2(l);
-                    System.arraycopy(b, p, buf, start-l, l);
-                    start -= l;
-                }
-            });
+        Writer unreader = new OutputStreamWriter(new InOutputStream());
+       private class InOutputStream extends OutputStream {
+           public void close() { }
+           public void write(int i) throws IOException { byte[] b = new byte[1]; b[0] = (byte)i; write(b, 0, 1); }
+           public void write(byte[] b) throws IOException { write(b, 0, b.length); }
+           public void write(byte[] b, int p, int l) {
+               ensureb2(l);
+               System.arraycopy(b, p, buf, start-l, l);
+               start -= l;
+           }
+       }
     }
+
+    public static interface Transformer {
+        public Stream transform(Stream in);
+    }
+
 }