01: package org.claros.commons.mail.protocols;
02:
03: import javax.mail.Folder;
04: import javax.mail.FolderClosedException;
05: import javax.mail.Message;
06: import javax.mail.MessagingException;
07: import javax.mail.event.MessageChangedEvent;
08: import javax.mail.event.MessageChangedListener;
09:
10: import com.sun.mail.imap.IMAPFolder;
11:
12: public class ImapIdleModifiedMsgThread extends Thread {
13: private IMAPFolder fold;
14:
15: public ImapIdleModifiedMsgThread(Folder folder) {
16: if (folder instanceof IMAPFolder) {
17: fold = (IMAPFolder) folder;
18: }
19: }
20:
21: public void run() {
22: try {
23: monitorModifiedMail();
24: } catch (Exception e) {
25: e.printStackTrace();
26: }
27: }
28:
29: /**
30: * Uses the IMAP IDLE Extension and monitors for modified mail.
31: * @throws Exception
32: */
33: public void monitorModifiedMail() throws Exception {
34: // Add messageCountListener to listen for new messages
35: fold.addMessageChangedListener(new MessageChangedListener() {
36: public void messageChanged(MessageChangedEvent ev) {
37: try {
38: Message msg = ev.getMessage();
39: System.out
40: .println("In folder "
41: + fold.getFullName()
42: + " A message has been changed. Info:..... Subject: "
43: + msg.getSubject() + " From: "
44: + msg.getFrom().toString());
45: } catch (MessagingException e) {
46: e.printStackTrace();
47: }
48: }
49: });
50:
51: // Check mail once in "freq" MILLIseconds
52: try {
53: int freq = 5000;
54: boolean supportsIdle = false;
55: try {
56: if (fold instanceof IMAPFolder) {
57: IMAPFolder f = (IMAPFolder) fold;
58: f.idle();
59: supportsIdle = true;
60: }
61: } catch (FolderClosedException fex) {
62: throw fex;
63: } catch (MessagingException mex) {
64: supportsIdle = false;
65: }
66: for (;;) {
67: if (supportsIdle && fold instanceof IMAPFolder) {
68: IMAPFolder f = (IMAPFolder) fold;
69: f.idle();
70: System.out.println("IDLE done");
71: } else {
72: Thread.sleep(freq); // sleep for freq milliseconds
73: // This is to force the IMAP server to send us
74: // EXISTS notifications.
75: fold.getMessageCount();
76: }
77: }
78: } catch (FolderClosedException e) {
79: e.printStackTrace();
80: } catch (MessagingException e) {
81: e.printStackTrace();
82: } catch (InterruptedException e) {
83: e.printStackTrace();
84: }
85: }
86: }
|