1 21 package org.jsmtpd.core.common.io.dataStream; 22 23 import java.io.ByteArrayOutputStream ; 24 import java.io.IOException ; 25 import java.io.InputStream ; 26 27 import org.jsmtpd.core.common.io.BareLFException; 28 import org.jsmtpd.core.common.io.InvalidStreamParserInitialisation; 29 import org.jsmtpd.core.common.io.InputSizeToBig; 30 31 34 public class DataStreamParser { 35 36 private ByteArrayOutputStream bos = null; 37 private byte[] buffer = null; 38 private long maxMessageSize; 39 private int readSize = 0; 40 private byte[] cleanData = null; 41 private long currentSize = 0; 42 43 49 public DataStreamParser(int bufferSize, long maxMessageSize) throws InvalidStreamParserInitialisation { 50 if (bufferSize < 10) 51 throw new InvalidStreamParserInitialisation(); 52 53 if (maxMessageSize < 10) 54 throw new InvalidStreamParserInitialisation(); 55 56 bos = new ByteArrayOutputStream (bufferSize); 57 this.maxMessageSize = maxMessageSize; 58 buffer = new byte[bufferSize]; 59 } 60 61 65 public void appendString(String toAppend) { 66 String tmp = toAppend + "\r\n"; 67 try { 68 bos.write(tmp.getBytes()); 69 } catch (IOException e) {} 70 } 71 72 79 public void parseInputStream(InputStream in) throws IOException , InputSizeToBig, BareLFException { 80 while (true) { 81 readSize = in.read(buffer); 83 if (readSize<0) 84 throw new IOException ("Negative byte count read"); 85 currentSize += readSize; 86 bos.write(buffer, 0, readSize); 87 if (currentSize > maxMessageSize) 88 throw new InputSizeToBig(); 89 90 if (checkEOS()) 91 break; 92 93 } 94 } 95 96 101 private boolean checkEOS() throws BareLFException { 102 103 if (buffer[readSize - 1] == 10) { 106 int sz = bos.size(); 107 byte[] pt = bos.toByteArray(); 108 if ((pt[sz - 2] == 13) && (pt[sz - 3] == 46) && (pt[sz - 4] == 10) && (pt[sz - 5] == 13)) { cleanData = new byte[bos.size() - 5]; 110 System.arraycopy(bos.toByteArray(), 0, cleanData, 0, bos.size() - 5); 111 return true; 112 } 113 } 114 115 return false; 116 } 117 118 public byte[] getData() { 119 if (cleanData != null) 120 return cleanData; 121 return bos.toByteArray(); 122 } 123 124 public void checkData() { 125 } 126 } | Popular Tags |