1 17 18 package org.apache.james.util; 19 20 import java.io.InputStream ; 21 import java.io.BufferedReader ; 22 import java.io.UnsupportedEncodingException ; 23 import java.io.IOException ; 24 import java.io.InputStreamReader ; 25 26 32 public class CRLFTerminatedReader extends BufferedReader { 33 34 public class TerminationException extends IOException { 35 private int where; 36 public TerminationException(int where) { 37 super(); 38 this.where = where; 39 } 40 41 public TerminationException(String s, int where) { 42 super(s); 43 this.where = where; 44 } 45 46 public int position() { 47 return where; 48 } 49 } 50 51 59 public CRLFTerminatedReader(InputStream in, String charsetName) 60 throws UnsupportedEncodingException { 61 super(new InputStreamReader (in, charsetName)); 62 } 63 64 private StringBuffer lineBuffer = new StringBuffer (); 65 private final int 66 EOF = -1, 67 CR = 13, 68 LF = 10; 69 70 private int tainted = -1; 71 72 86 public String readLine() throws IOException { 87 88 lineBuffer.delete(0, lineBuffer.length()); 90 91 95 boolean cr_just_received = false; 96 97 while (true){ 98 int inChar = read(); 99 100 if (!cr_just_received){ 101 switch (inChar){ 103 case CR : cr_just_received = true; 104 break; 105 case EOF : return null; case LF : if (tainted == -1) tainted = lineBuffer.length(); 108 default : lineBuffer.append((char)inChar); 110 } 111 }else{ 112 switch (inChar){ 114 case LF : if (tainted != -1) { 116 int pos = tainted; 117 tainted = -1; 118 throw new TerminationException("\"bare\" CR or LF in data stream", pos); 119 } 120 return lineBuffer.toString(); 121 case EOF : return null; case CR : if (tainted == -1) tainted = lineBuffer.length(); 124 lineBuffer.append((char)CR); 125 break; 126 default : if (tainted == -1) tainted = lineBuffer.length(); 128 lineBuffer.append((char)CR); 129 lineBuffer.append((char)inChar); 130 cr_just_received = false; 131 } 132 } 133 } }} 136 | Popular Tags |