1 36 package org.columba.ristretto.pop3; 37 38 import java.io.FilterInputStream ; 39 import java.io.IOException ; 40 import java.io.InputStream ; 41 import java.util.regex.Matcher ; 42 import java.util.regex.Pattern ; 43 44 import org.columba.ristretto.concurrency.Mutex; 45 import org.columba.ristretto.io.ConnectionDroppedException; 46 import org.columba.ristretto.io.TempSourceFactory; 47 import org.columba.ristretto.parser.ParserException; 48 import org.columba.ristretto.pop3.parser.POP3ResponseParser; 49 50 57 public class POP3InputStream extends FilterInputStream { 58 59 private static final int RETR_BUFFER_SIZE = 1024; 60 private StringBuffer lineBuffer; 61 private static final Pattern sizePattern = Pattern.compile("(\\d+) octets"); 62 63 68 public POP3InputStream(InputStream in) { 69 super(in); 70 71 lineBuffer = new StringBuffer (); 72 } 73 74 81 public POP3Response readSingleLineResponse() 82 throws IOException , POP3Exception { 83 readLineInBuffer(); 84 85 try { 86 POP3Response response = POP3ResponseParser.parse(lineBuffer); 87 88 return response; 89 } catch (ParserException e) { 90 throw new POP3Exception(e.getMessage()); 91 } 92 } 93 94 102 public InputStream asyncDownload(int size, Mutex mutex) throws IOException { 103 return POP3DownloadThread.asyncDownload( new POP3MultiLineStream(this, size), size, mutex); 104 } 105 106 113 public InputStream syncDownload(int size) throws IOException { 114 return new POP3MultiLineStream(this, size); 115 116 } 117 118 119 126 public POP3Response readMultiLineResponse() 127 throws IOException , POP3Exception { 128 POP3Response response = readSingleLineResponse(); 129 130 if (response.isOK()) { 132 int size = -1; 133 Matcher matcher = sizePattern.matcher(response.getMessage()); 135 if( matcher.find() ) { 136 size = Integer.parseInt(matcher.group(1)); 137 } 138 139 POP3MultiLineStream multiLineStream = new POP3MultiLineStream(this, size); 140 response.setData(TempSourceFactory.createTempSource(multiLineStream, -1)); 141 } 142 143 return response; 144 } 145 146 private void readLineInBuffer() throws IOException { 147 lineBuffer.delete(0, lineBuffer.length()); 149 150 int read = in.read(); 151 while (read != '\r' && read != -1) { 153 lineBuffer.append((char) read); 154 read = in.read(); 155 } 156 lineBuffer.append((char)read); 157 158 read = in.read(); 160 if( read != '\n') throw new ConnectionDroppedException(); 161 lineBuffer.append((char) read); 162 } 163 164 } 165 | Popular Tags |