1package CyrusSasl; 2 3import java.io.*; 4 5public class SaslOutputStream extends OutputStream 6{ 7 static final boolean DoEncrypt = true; 8 static final boolean DoDebug = false; 9 10 private static int MAXBUFFERSIZE=1000; 11 private GenericCommon conn; 12 OutputStream out; 13 14 private byte[] buffer=new byte[MAXBUFFERSIZE]; 15 private int buffersize=0; 16 17 public SaslOutputStream(OutputStream out, GenericCommon conn) 18 { 19 if (DoDebug) { 20 System.err.println("DEBUG constructing SaslOutputStream"); 21 } 22 this.conn=conn; 23 this.out=out; 24 } 25 26 private void write_if_size() throws IOException 27 { 28 if (DoDebug) { 29 System.err.println("DEBUG write_if_size(): buffersize " + 30 buffersize); 31 } 32 if ( buffersize >=MAXBUFFERSIZE) 33 flush(); 34 } 35 36 public synchronized void write(int b) throws IOException 37 { 38 buffer[buffersize]=(byte) b; 39 buffersize++; 40 write_if_size(); 41 } 42 43 public synchronized void write(byte b[]) throws IOException 44 { 45 write(b,0,b.length); 46 } 47 48 public synchronized void write(byte b[], 49 int off, 50 int len) throws IOException 51 { 52 if (DoDebug) { 53 System.err.println("DEBUG writing() len " + len); 54 } 55 if (len+buffersize < MAXBUFFERSIZE) { 56 for (int lup=0;lup<len;lup++) { 57 buffer[buffersize+lup]=b[lup+off]; 58 } 59 buffersize+=len; 60 61 write_if_size(); 62 63 } else { 64 flush(); 65 66 if (DoEncrypt && conn != null) { 67 // ok, this is a messy way of doing byte[] sub-arraying 68 String str=new String(b,off,len); 69 out.write( conn.encode(str.getBytes()) ); 70 } else { 71 out.write(b); 72 } 73 out.flush(); 74 } 75 76 if (DoDebug) { 77 System.err.println("DEBUG writing(): done"); 78 } 79 } 80 81 public synchronized void flush() throws IOException 82 { 83 if (DoDebug) { 84 System.err.println("DEBUG flushing(): buffersize " + buffersize); 85 } 86 if (buffersize==0) return; 87 88 if (DoEncrypt && conn != null) { 89 // ok, this is a messy way of doing byte[] sub-arraying 90 String str = new String(buffer, 0, buffersize); 91 out.write( conn.encode(str.getBytes()) ); 92 } else { 93 out.write(buffer, 0, buffersize); 94 } 95 out.flush(); 96 buffersize=0; 97 if (DoDebug) { 98 System.err.println("DEBUG flushing(): done"); 99 } 100 } 101 102 public synchronized void close() throws IOException 103 { 104 flush(); 105 out.close(); 106 } 107 108 109} 110