1 21 22 27 28 package com.sun.mail.imap; 29 30 import java.io.*; 31 import javax.mail.*; 32 import com.sun.mail.imap.protocol.*; 33 import com.sun.mail.iap.*; 34 35 40 41 public class IMAPInputStream extends InputStream { 42 private IMAPMessage msg; private String section; private int pos; private int blksize; private int max; private byte[] buf; private int bufcount; private int bufpos; private boolean peek; 54 55 58 public IMAPInputStream(IMAPMessage msg, String section, int max, 59 boolean peek) { 60 this.msg = msg; 61 this.section = section; 62 this.max = max; 63 this.peek = peek; 64 pos = 0; 65 blksize = msg.getFetchBlockSize(); 66 } 67 68 72 private void fill() throws IOException { 73 77 if (max != -1 && pos >= max) { 78 if (pos == 0) 79 checkSeen(); 80 return; } 82 83 BODY b = null; 84 85 synchronized (msg.getMessageCacheLock()) { 87 88 if (msg.isExpunged()) 90 throw new IOException("No content for expunged message"); 91 92 int seqnum = msg.getSequenceNumber(); 93 int cnt = blksize; 94 if (max != -1 && pos + blksize > max) 95 cnt = max - pos; 96 try { 97 IMAPProtocol p = msg.getProtocol(); 98 if (peek) 99 b = p.peekBody(seqnum, section, pos, cnt); 100 else 101 b = p.fetchBody(seqnum, section, pos, cnt); 102 } catch (ProtocolException pex) { 103 throw new IOException(pex.getMessage()); 104 } catch (FolderClosedException fex) { 105 throw new IOException(fex.getMessage()); 106 } 107 } 108 109 ByteArray ba; 110 if (b == null || ((ba = b.getByteArray()) == null)) 111 throw new IOException("No content"); 112 113 if (pos == 0) 115 checkSeen(); 116 117 buf = ba.getBytes(); 119 bufpos = ba.getStart(); 120 int n = ba.getCount(); bufcount = bufpos + n; 123 pos += n; 124 } 125 126 130 public synchronized int read() throws IOException { 131 if (bufpos >= bufcount) { 132 fill(); 133 if (bufpos >= bufcount) 134 return -1; } 136 return buf[bufpos++] & 0xff; 137 } 138 139 153 public synchronized int read(byte b[], int off, int len) 154 throws IOException { 155 156 int avail = bufcount - bufpos; 157 if (avail <= 0) { 158 fill(); 159 avail = bufcount - bufpos; 160 if (avail <= 0) 161 return -1; } 163 int cnt = (avail < len) ? avail : len; 164 System.arraycopy(buf, bufpos, b, off, cnt); 165 bufpos += cnt; 166 return cnt; 167 } 168 169 183 public int read(byte b[]) throws IOException { 184 return read(b, 0, b.length); 185 } 186 187 191 public synchronized int available() throws IOException { 192 return (bufcount - bufpos); 193 } 194 195 202 private void checkSeen() { 203 if (peek) return; 205 try { 206 Folder f = msg.getFolder(); 207 if (f != null && f.getMode() != Folder.READ_ONLY && 208 !msg.isSet(Flags.Flag.SEEN)) 209 msg.setFlag(Flags.Flag.SEEN, true); 210 } catch (MessagingException ex) { 211 } 213 } 214 } 215 | Popular Tags |