01: package org.claros.commons.mail.protocols;
02:
03: import java.io.IOException;
04:
05: import javax.mail.Folder;
06: import javax.mail.FolderClosedException;
07: import javax.mail.Message;
08: import javax.mail.MessagingException;
09: import javax.mail.event.MessageCountAdapter;
10: import javax.mail.event.MessageCountEvent;
11:
12: import com.sun.mail.imap.IMAPFolder;
13:
14: /**
15: * @author umut
16: *
17: */
18: public class ImapIdleNewMsgThread extends Thread {
19: private IMAPFolder fold;
20:
21: public ImapIdleNewMsgThread(Folder folder) {
22: if (folder instanceof IMAPFolder) {
23: fold = (IMAPFolder) folder;
24: }
25: }
26:
27: public void run() {
28: try {
29: monitorNewMail();
30: } catch (Exception e) {
31: e.printStackTrace();
32: }
33: }
34:
35: /**
36: * Uses the IMAP IDLE Extension and monitors for new mail.
37: * @throws Exception
38: */
39: public void monitorNewMail() throws Exception {
40: // Add messageCountListener to listen for new messages
41: fold.addMessageCountListener(new MessageCountAdapter() {
42: public void messagesAdded(MessageCountEvent ev) {
43: Message[] msgs = ev.getMessages();
44: System.out.println("Got " + msgs.length
45: + " new messages in folder"
46: + fold.getFullName());
47:
48: // Just dump out the new messages
49: for (int i = 0; i < msgs.length; i++) {
50: try {
51: System.out.println("-----");
52: System.out.println("Message "
53: + msgs[i].getMessageNumber() + ":");
54: msgs[i].writeTo(System.out);
55: } catch (IOException ioex) {
56: ioex.printStackTrace();
57: } catch (MessagingException mex) {
58: mex.printStackTrace();
59: }
60: }
61: }
62: });
63:
64: // Check mail once in "freq" MILLIseconds
65: try {
66: int freq = 5000;
67: boolean supportsIdle = false;
68: try {
69: if (fold instanceof IMAPFolder) {
70: IMAPFolder f = (IMAPFolder) fold;
71: f.idle();
72: supportsIdle = true;
73: }
74: } catch (FolderClosedException fex) {
75: throw fex;
76: } catch (MessagingException mex) {
77: supportsIdle = false;
78: }
79: for (;;) {
80: if (supportsIdle && fold instanceof IMAPFolder) {
81: IMAPFolder f = (IMAPFolder) fold;
82: f.idle();
83: System.out.println("IDLE done");
84: } else {
85: Thread.sleep(freq); // sleep for freq milliseconds
86: // This is to force the IMAP server to send us
87: // EXISTS notifications.
88: fold.getMessageCount();
89: }
90: }
91: } catch (FolderClosedException e) {
92: e.printStackTrace();
93: } catch (MessagingException e) {
94: e.printStackTrace();
95: } catch (InterruptedException e) {
96: e.printStackTrace();
97: }
98: }
99: }
|