KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > email > Pop3MessageDispatcher


1 /*
2  * $Id: Pop3MessageDispatcher.java 3982 2006-11-22 14:28:01Z lajos $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.providers.email;
12
13 import javax.mail.Flags JavaDoc;
14 import javax.mail.Folder JavaDoc;
15 import javax.mail.Message JavaDoc;
16 import javax.mail.MessagingException JavaDoc;
17 import javax.mail.Session JavaDoc;
18 import javax.mail.Store JavaDoc;
19 import javax.mail.URLName JavaDoc;
20
21 import org.mule.impl.MuleMessage;
22 import org.mule.providers.AbstractMessageDispatcher;
23 import org.mule.umo.UMOEvent;
24 import org.mule.umo.UMOException;
25 import org.mule.umo.UMOMessage;
26 import org.mule.umo.endpoint.UMOEndpointURI;
27 import org.mule.umo.endpoint.UMOImmutableEndpoint;
28 import org.mule.umo.provider.UMOConnector;
29
30 /**
31  * <code>Pop3MessageDispatcher</code> For Pop3 connections the dispatcher can only
32  * be used to receive message (as opposed to listening for them). Trying to send or
33  * dispatch will throw an UnsupportedOperationException.
34  */

35
36 public class Pop3MessageDispatcher extends AbstractMessageDispatcher
37 {
38     private Pop3Connector connector;
39
40     private Folder JavaDoc folder;
41
42     private Session JavaDoc session = null;
43
44     public Pop3MessageDispatcher(UMOImmutableEndpoint endpoint)
45     {
46         super(endpoint);
47         this.connector = (Pop3Connector)endpoint.getConnector();
48     }
49
50     protected void doConnect(UMOImmutableEndpoint endpoint) throws Exception JavaDoc
51     {
52
53         if (folder == null || !folder.isOpen())
54         {
55             String JavaDoc inbox = (String JavaDoc)endpoint.getProperty("folder");
56
57             if (inbox == null || endpoint.getProtocol().toLowerCase().startsWith("pop3"))
58             {
59                 inbox = Pop3Connector.MAILBOX;
60             }
61
62             UMOEndpointURI uri = endpoint.getEndpointURI();
63             URLName JavaDoc url = new URLName JavaDoc(uri.getScheme(), uri.getHost(), uri.getPort(), inbox,
64                 uri.getUsername(), uri.getPassword());
65
66             session = MailUtils.createMailSession(url, connector);
67             session.setDebug(logger.isDebugEnabled());
68
69             Store JavaDoc store = session.getStore(url);
70             store.connect(uri.getHost(), uri.getPort(), uri.getUsername(), uri.getPassword());
71
72             folder = store.getFolder(inbox);
73             if (!folder.isOpen())
74             {
75                 try
76                 {
77                     // Depending on Server implementation it's not always
78
// necessary to open the folder to check it
79
// Opening folders can be exprensive!
80
// folder.open(Folder.READ_ONLY);
81
folder.open(Folder.READ_WRITE);
82                 }
83                 catch (MessagingException JavaDoc e)
84                 {
85                     logger.warn("Failed to open folder: " + folder.getFullName(), e);
86                 }
87             }
88         }
89     }
90
91     protected void doDisconnect() throws Exception JavaDoc
92     {
93         // close and expunge deleted messages
94
try
95         {
96             if (folder != null)
97             {
98                 try
99                 {
100                     folder.expunge();
101                 }
102                 catch (MessagingException JavaDoc e)
103                 {
104                     // maybe next time.
105
}
106                 if (folder.isOpen())
107                 {
108                     folder.close(true);
109                 }
110             }
111             session = null;
112         }
113         catch (Exception JavaDoc e)
114         {
115             logger.error("Failed to close inbox: " + e.getMessage(), e);
116         }
117     }
118
119     /**
120      * @param event
121      * @throws UnsupportedOperationException
122      */

123     protected void doDispatch(UMOEvent event) throws Exception JavaDoc
124     {
125         throw new UnsupportedOperationException JavaDoc("Cannot dispatch from a Pop3 connection");
126     }
127
128     /**
129      * @param event
130      * @return
131      * @throws UnsupportedOperationException
132      */

133     protected UMOMessage doSend(UMOEvent event) throws Exception JavaDoc
134     {
135         throw new UnsupportedOperationException JavaDoc("Cannot send from a Pop3 connection");
136     }
137
138     /**
139      * Make a specific request to the underlying transport Endpoint can be in the
140      * form of pop3://username:password@pop3.lotsofmail.org
141      *
142      * @param endpoint the endpoint to use when connecting to the resource
143      * @param timeout the maximum time the operation should block before returning.
144      * The call should return immediately if there is data available. If
145      * no data becomes available before the timeout elapses, null will be
146      * returned
147      * @return the result of the request wrapped in a UMOMessage object. Null will be
148      * returned if no data was avaialable
149      * @throws Exception if the call to the underlying protocal cuases an exception
150      */

151     protected synchronized UMOMessage doReceive(UMOImmutableEndpoint endpoint, long timeout) throws Exception JavaDoc
152     {
153         long t0 = System.currentTimeMillis();
154         if (timeout < 0)
155         {
156             timeout = Long.MAX_VALUE;
157         }
158
159         do
160         {
161             if (hasMessages(folder))
162             {
163                 int count = getMessageCount(folder);
164                 if (count > 0)
165                 {
166                     Message JavaDoc message = getNextMessage(folder);
167                     // so we don't get the same message again
168
flagMessage(folder, message);
169
170                     return new MuleMessage(connector.getMessageAdapter(message));
171                 }
172                 else if (count == -1)
173                 {
174                     throw new MessagingException JavaDoc("Cannot monitor folder: " + folder.getFullName()
175                                     + " as folder is closed");
176                 }
177             }
178
179             long sleep = Math.min(this.connector.getCheckFrequency(), timeout
180                             - (System.currentTimeMillis() - t0));
181
182             if (sleep > 0)
183             {
184                 if (logger.isDebugEnabled())
185                 {
186                     logger.debug("No results, sleeping for " + sleep);
187                 }
188                 Thread.sleep(sleep);
189             }
190             else
191             {
192                 logger.debug("Timeout");
193                 return null;
194             }
195
196         }
197         while (true);
198     }
199
200     /**
201      * There seems to be som variation on pop3 implementation so it may be
202      * preferrable to mark messages as seen here and alos overload the getMessages
203      * method to grab only new messages
204      *
205      * @param message
206      * @throws MessagingException
207      */

208     protected void flagMessage(Folder JavaDoc folder, Message JavaDoc message) throws MessagingException JavaDoc
209     {
210         message.setFlag(Flags.Flag.DELETED, true);
211     }
212
213     protected Message JavaDoc getNextMessage(Folder JavaDoc folder) throws MessagingException JavaDoc
214     {
215         return folder.getMessage(1);
216     }
217
218     protected int getMessageCount(Folder JavaDoc folder) throws MessagingException JavaDoc
219     {
220         return folder.getMessageCount();
221     }
222
223     /**
224      * Optimised check to se whether to return the message count and retrieve the
225      * messages. Some pop3 implementations differ so an optimised check such as
226      * folder.hasNewMessages() cannot be used
227      *
228      * @param folder
229      * @return
230      * @throws MessagingException
231      */

232     protected boolean hasMessages(Folder JavaDoc folder) throws MessagingException JavaDoc
233     {
234         return getMessageCount(folder) > 0;
235     }
236
237     public Object JavaDoc getDelegateSession() throws UMOException
238     {
239         return session;
240     }
241
242     public UMOConnector getConnector()
243     {
244         return connector;
245     }
246
247     protected void doDispose()
248     {
249         // template method
250
}
251 }
252
Popular Tags