1 21 package org.apache.derby.impl.drda; 22 23 import java.io.InputStream ; 24 import java.io.Reader ; 25 import java.io.OutputStreamWriter ; 26 import java.io.ByteArrayOutputStream ; 27 import java.io.ByteArrayInputStream ; 28 29 import java.io.IOException ; 30 import java.io.UnsupportedEncodingException ; 31 32 import org.apache.derby.iapi.services.sanity.SanityManager; 33 34 46 public class ReEncodedInputStream extends InputStream { 47 48 private static final int BUFFERED_CHAR_LEN = 1024; 49 50 private Reader reader_; 51 private char[] decodedBuffer_; 52 53 private OutputStreamWriter encodedStreamWriter_; 54 private PublicBufferOutputStream encodedOutputStream_; 55 56 private ByteArrayInputStream encodedInputStream_; 57 58 public ReEncodedInputStream(Reader reader) 59 throws IOException { 60 61 reader_ = reader; 62 decodedBuffer_ = new char[BUFFERED_CHAR_LEN]; 63 64 encodedOutputStream_ = new PublicBufferOutputStream( BUFFERED_CHAR_LEN * 3 ); 65 encodedStreamWriter_ = new OutputStreamWriter (encodedOutputStream_,"UTF8"); 66 67 encodedInputStream_ = reEncode(reader_); 68 69 } 70 71 72 private ByteArrayInputStream reEncode(Reader reader) 73 throws IOException 74 { 75 76 int count; 77 do{ 78 count = reader.read(decodedBuffer_, 0, BUFFERED_CHAR_LEN); 79 80 }while(count == 0); 81 82 if(count < 0) 83 return null; 84 85 encodedOutputStream_.reset(); 86 encodedStreamWriter_.write(decodedBuffer_,0,count); 87 encodedStreamWriter_.flush(); 88 89 int encodedLength = encodedOutputStream_.size(); 90 91 return new ByteArrayInputStream (encodedOutputStream_.getBuffer(), 92 0, 93 encodedLength); 94 } 95 96 97 public int available() 98 throws IOException { 99 100 if(encodedInputStream_ == null){ 101 return 0; 102 } 103 104 return encodedInputStream_.available(); 105 106 } 107 108 109 public void close() 110 throws IOException { 111 112 if(encodedInputStream_ != null ){ 113 encodedInputStream_.close(); 114 encodedInputStream_ = null; 115 } 116 117 if(reader_ != null ){ 118 reader_.close(); 119 reader_ = null; 120 } 121 122 if(encodedStreamWriter_ != null){ 123 encodedStreamWriter_.close(); 124 encodedStreamWriter_ = null; 125 } 126 127 } 128 129 130 public int read() 131 throws IOException { 132 133 if(encodedInputStream_ == null){ 134 return -1; 135 } 136 137 int c = encodedInputStream_.read(); 138 139 if(c > -1){ 140 return c; 141 142 }else{ 143 encodedInputStream_ = reEncode(reader_); 144 145 if(encodedInputStream_ == null){ 146 return -1; 147 } 148 149 return encodedInputStream_.read(); 150 151 } 152 153 } 154 155 156 protected void finalize() throws IOException { 157 close(); 158 } 159 160 161 static class PublicBufferOutputStream extends ByteArrayOutputStream { 162 163 PublicBufferOutputStream(int size){ 164 super(size); 165 } 166 167 public byte[] getBuffer(){ 168 return buf; 169 } 170 171 } 172 173 } 174 175 176 | Popular Tags |