KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > glassfish > grizzly > async > javamail > JavaMailAsyncFilter


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package org.glassfish.grizzly.async.javamail;
25
26 import com.sun.enterprise.web.connector.grizzly.AsyncExecutor;
27 import com.sun.enterprise.web.connector.grizzly.AsyncFilter;
28 import com.sun.enterprise.web.connector.grizzly.AsyncHandler;
29 import com.sun.enterprise.web.connector.grizzly.async.AsyncProcessorTask;
30 import com.sun.enterprise.web.connector.grizzly.ProcessorTask;
31
32 import java.util.Properties JavaDoc;
33 import java.util.concurrent.ConcurrentHashMap JavaDoc;
34 import java.util.concurrent.ConcurrentLinkedQueue JavaDoc;
35 import java.util.concurrent.ScheduledThreadPoolExecutor JavaDoc;
36 import java.util.concurrent.TimeUnit JavaDoc;
37 import javax.mail.Folder JavaDoc;
38 import javax.mail.Message JavaDoc;
39 import javax.mail.Session JavaDoc;
40 import javax.mail.Store JavaDoc;
41 import javax.naming.InitialContext JavaDoc;
42
43 import com.sun.enterprise.deployment.MailConfiguration;
44 import com.sun.mail.pop3.POP3SSLStore;
45 import javax.mail.URLName JavaDoc;
46 import org.apache.coyote.Request;
47
48 /**
49  * This <code>AsyncFilter</code> connect to an email account and look for
50  * new messages. If there is no new message, the connection is keep-alived
51  * until a new message arrives. This is just an example on how asynchronous
52  * request processing works in Grizzly.
53  *
54  * @author Jeanfrancois Arcand
55  */

56 public class JavaMailAsyncFilter implements AsyncFilter {
57     
58     /**
59      * Collection used to store <code>JavaMailAsyncHandler</code> registration.
60      */

61     private static ConcurrentHashMap JavaDoc<String JavaDoc,JavaMailAsyncFilterHandler> handlers
62        = new ConcurrentHashMap JavaDoc<String JavaDoc,JavaMailAsyncFilterHandler>();
63     
64     
65     /**
66      * Cache instance of <code>MailFetcher</code>
67      */

68     private static ConcurrentLinkedQueue JavaDoc<MailFetcher> mailFetcherCache =
69             new ConcurrentLinkedQueue JavaDoc<MailFetcher>();
70             
71     
72     /**
73      * Scheduler used to wait between execution of
74      * <code>JavaMailAsyncHandler</code>
75      */

76     private final static ScheduledThreadPoolExecutor JavaDoc scheduler
77             = new ScheduledThreadPoolExecutor JavaDoc(1);
78     
79     
80     /**
81      * The current JavaMal Session.
82      */

83     private Session JavaDoc mailSession;
84     
85     
86     /**
87      * Properties used to store JavaMal configuration.
88      */

89     private Properties JavaDoc props;
90
91     
92     // ---------------------------------------------------------------------//
93

94     
95     /**
96      * <code>AsyncFilter</code> which implement a JavaMail client.
97      */

98     public JavaMailAsyncFilter() {
99         try {
100             InitialContext JavaDoc ic = new InitialContext JavaDoc();
101             String JavaDoc snName = "mail/MailSession";
102             MailConfiguration mailConfig =
103                      (MailConfiguration)ic.lookup(snName);
104             
105             props = mailConfig.getMailProperties();
106             props.setProperty("mail.pop3.ssl", "true");
107             String JavaDoc SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
108             props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
109             props.setProperty("mail.pop3.socketFactory.fallback", "false");
110  
111         } catch (Throwable JavaDoc ex) {
112             ex.printStackTrace();
113         }
114     }
115
116
117     /**
118      * Register a <code>JavaMailAsyncFilterHandler</code>
119      */

120     public static void register(String JavaDoc contextPath,
121                                 JavaMailAsyncFilterHandler handler){
122         handlers.put(contextPath,handler);
123     }
124        
125     
126     /**
127      * Execute the the filter by looking at the request context path. If
128      * the context path is a registered <code>JavaMailAsyncFilterHandler</code>,
129      * the request will be executed asynchronously. If not, the request will
130      * be executed synchronously.
131      *
132      **/

133     public boolean doFilter(AsyncExecutor asyncExecutor) {
134         AsyncProcessorTask asyncProcessorTask
135                 = asyncExecutor.getAsyncProcessorTask();
136         ProcessorTask processorTask = asyncProcessorTask.getProcessorTask();
137         AsyncHandler asyncHandler = processorTask.getAsyncHandler();
138         
139         Request request = processorTask.getRequest();
140         String JavaDoc contextPath = request.requestURI().toString();
141         contextPath = contextPath.substring(contextPath.lastIndexOf("/"));
142         
143         JavaMailAsyncFilterHandler handler = handlers.get(contextPath);
144         if ( handler == null){
145             processorTask.invokeAdapter();
146             return true;
147         }
148         MailFetcher mf = mailFetcherCache.poll();
149         if ( mf == null ){
150             mf = new MailFetcher();
151         }
152         mf.handler = handler;
153         mf.processorTask = processorTask;
154         mf.asyncProcessorTask = asyncProcessorTask;
155         mf.asyncHandler = asyncHandler;
156         
157         scheduler.schedule(mf,1L,TimeUnit.SECONDS);
158         return false;
159     }
160     
161     
162     /**
163      * Simple class that look for remote email and execute a
164      * <code>ProcessorTask</code>.
165      */

166     private class MailFetcher implements Runnable JavaDoc{
167     
168         /**
169          * The handler associated with this class (Servlet).
170          */

171         JavaMailAsyncFilterHandler handler;
172
173         
174         /**
175          * The event object shared with <code>JavaMailAsyncFilterHandler</code>
176          * implementation.
177          */

178         JavaMailAsyncFilterEvent event = new JavaMailAsyncFilterEvent();
179         
180     
181         /**
182          * The <code>ProcessorTask</code>, which is used to execture the HTTP
183          * request.
184          */

185         private ProcessorTask processorTask;
186
187
188         /**
189          * The async wrapper around the code>ProcessorTask</code>
190          */

191         private AsyncProcessorTask asyncProcessorTask;
192
193
194         /**
195          * The Default <code>AsyncHandler</code> implementation used to execute
196          * aynchronous request. This object own the main <code>Pipeline</code>
197          * used to execute an asynchronous operation.
198          */

199         private AsyncHandler asyncHandler;
200         
201     
202         /**
203          * If the <code>JavaMailAsyncFilterHandler</code> is ready to execute,
204          * the execute it. If not, return this object to the scheduler for another
205          * 10 seconds.
206          */

207         public void run(){
208             Message JavaDoc[] messages = checkMail();
209
210             event.setMessages(messages);
211             boolean continueCheckMail = handler.handleEvent(event);
212             if ( !continueCheckMail ) {
213                 processorTask.invokeAdapter();
214                 asyncHandler.handle(asyncProcessorTask);
215                 mailFetcherCache.offer(this);
216             } else {
217                 scheduler.schedule(this,10L,TimeUnit.SECONDS);
218             }
219         }
220
221
222         /**
223          * Connect to email account and look for new emails.
224          */

225         private Message JavaDoc[] checkMail(){
226             try{
227                 props.setProperty("mail.pop3.user", handler.getUserName());
228                 props.setProperty("mail.pop3.passwd", handler.getPassword());
229                 props.setProperty("mail.pop3.host", handler.getMailServer());
230                 props.setProperty("mail.pop3.port", handler.getMailServerPort());
231                 props.setProperty("mail.pop3.socketFactory.port",
232                         handler.getMailServerPort());
233
234                 URLName JavaDoc url = new URLName JavaDoc("pop3://"
235                         + handler.getUserName()
236                         +":"+ handler.getPassword()
237                         +"@"+ handler.getMailServer()
238                         +":"+ handler.getMailServerPort());
239
240                 mailSession = Session.getInstance(props, null);
241                 Store JavaDoc store = new POP3SSLStore(mailSession, url);
242                 store.connect(handler.getMailServer(),
243                               handler.getUserName(), handler.getPassword());
244
245                 Folder JavaDoc folder = store.getDefaultFolder();
246                 folder = folder.getFolder("INBOX");
247
248                 folder.open(Folder.READ_ONLY);
249
250                 return folder.getMessages();
251             } catch (Throwable JavaDoc ex) {
252                 ex.printStackTrace();
253                 return null;
254             }
255         }
256     }
257 }
258
Popular Tags