1 36 package org.columba.ristretto.coder; 37 38 import java.io.FilterInputStream ; 39 import java.io.IOException ; 40 import java.io.InputStream ; 41 import java.nio.IntBuffer ; 42 43 44 54 public class QuotedPrintableEncoderInputStream extends FilterInputStream { 55 56 private static final char[] hexTable = 57 { 58 '0', 59 '1', 60 '2', 61 '3', 62 '4', 63 '5', 64 '6', 65 '7', 66 '8', 67 '9', 68 'A', 69 'B', 70 'C', 71 'D', 72 'E', 73 'F' }; 74 75 private IntBuffer outBytes; 76 77 private int pos; 78 private int available; 79 private int lineLength; 80 81 86 public QuotedPrintableEncoderInputStream(InputStream arg0) { 87 super(arg0); 88 89 outBytes = IntBuffer.allocate(10); 90 91 } 92 93 94 103 private int processNextInput() throws IOException { 104 outBytes.clear(); 105 int read = in.read(); 106 107 if (read == -1) 108 return -1; 109 110 if (read == '\t' || read == ' ') { 116 if (lineLength >= 74) { 118 outBytes.put('='); 119 outBytes.put(toHexString(read)); 120 lineLength += 3; 121 } else { 122 int next = in.read(); 124 if (next != -1) { 125 if (next == '\r' || next == '\n') { 127 outBytes.put('='); 128 outBytes.put(toHexString(read)); 129 lineLength += 3; 130 } else { 131 outBytes.put( read ); 133 lineLength++; 134 } 135 136 read = next; 140 } 141 } 142 } 143 144 if (read >= 33 && read != 61 && read <= 126) { 146 outBytes.put(read); 147 lineLength++; 148 } else if( read == '\r' ){ 149 outBytes.put('\r'); 150 outBytes.put('\n'); 151 in.read(); 153 lineLength = 0; 154 } else if( read == '\n' ){ 155 outBytes.put('\r'); 157 outBytes.put('\n'); 158 lineLength = 0; 159 } else { 160 outBytes.put('='); 161 outBytes.put(toHexString(read)); 162 lineLength += 3; 163 } 164 165 if( lineLength >= 74) { 167 outBytes.put('='); 168 outBytes.put('\r'); 169 outBytes.put('\n'); 170 lineLength = 0; 171 } 172 173 return outBytes.position(); 174 } 175 176 179 public int read() throws IOException { 180 if( pos == available ) { 181 available = processNextInput(); 182 pos = 0; 183 } 184 185 if( available == -1) return -1; 186 187 return outBytes.get(pos++); 188 } 189 190 193 public int read(byte[] arg0, int arg1, int arg2) throws IOException { 194 int next; 195 for( int i=0; i<arg2; i++) { 196 next = read(); 197 if( next == -1 ) { 198 if( i == 0 ) { 199 return -1; 200 } else { 201 return i; 202 } 203 } 204 arg0[arg1+i] = (byte) next; 205 } 206 return arg2; 207 } 208 209 210 216 private int[] toHexString(int in) { 217 int[] result = new int[2]; 218 int value; 219 if (in < 0) { 220 value = 0x080 | (0x07f & in); 221 } else { 222 value = in; 223 } 224 225 int hi = value / 16; 226 int lo = value % 16; 227 result[0] = hexTable[hi]; 228 result[1] = hexTable[lo]; 229 return result; 230 } 231 232 } 233 | Popular Tags |