KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > glassfish > grizzly > async > servlet > EmailNotifierServlet


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
5  * in compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * glassfish/bootstrap/legal/CDDLv1.0.txt or
9  * https://glassfish.dev.java.net/public/CDDLv1.0.html.
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 in each file and include the License file at
15  * glassfish/bootstrap/legal/CDDLv1.0.txt. If applicable,
16  * add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your
18  * own identifying information: Portions Copyright [yyyy]
19  * [name of copyright owner]
20  */

21 package org.glassfish.grizzly.async.servlet;
22
23 import java.io.IOException JavaDoc;
24 import java.io.PrintWriter JavaDoc;
25 import javax.mail.Address JavaDoc;
26 import javax.mail.Message JavaDoc;
27 import javax.mail.MessagingException JavaDoc;
28 import javax.mail.internet.InternetAddress JavaDoc;
29 import javax.servlet.ServletConfig JavaDoc;
30 import javax.servlet.ServletException JavaDoc;
31 import javax.servlet.ServletOutputStream JavaDoc;
32 import javax.servlet.http.HttpServlet JavaDoc;
33 import javax.servlet.http.HttpServletRequest JavaDoc;
34 import javax.servlet.http.HttpServletResponse JavaDoc;
35
36 import org.glassfish.grizzly.async.javamail.JavaMailAsyncFilterHandler;
37 import org.glassfish.grizzly.async.javamail.JavaMailAsyncFilterEvent;
38 import org.glassfish.grizzly.async.javamail.JavaMailAsyncFilter;
39
40 /**
41  * Simple servlet that use Grizzly Asynchronous Request Processing to fecth
42  * mail from an email account (Gmail, Yahoo, etc.). The Servlet will be interupted
43  * until new mails are available in the Gmail account.
44  *
45  * @author Jeanfrancois Arcand
46  */

47 public class EmailNotifierServlet extends HttpServlet JavaDoc
48                                     implements JavaMailAsyncFilterHandler{
49      
50     /**
51      * The username for the account
52      */

53     private String JavaDoc username;
54     
55     
56     /**
57      * The password for the account
58      */

59     private String JavaDoc password;
60     
61     
62     /**
63      * The mail server
64      */

65     private String JavaDoc mailServer;
66     
67     
68     /**
69      * The port the mail server is listeningt
70      */

71     private String JavaDoc mailServerPort;
72     
73     
74     /**
75      * The current Gmail message list.
76      */

77     private Message JavaDoc[] messages;
78     
79     
80     public EmailNotifierServlet() {
81     }
82     
83     
84     /**
85      * Init this Servlet by registering it with the
86      * <code>JavaMailAsyncFilter</code>.
87      */

88     public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
89         username = config.getInitParameter("username");
90         password = config.getInitParameter("password");
91         mailServer = config.getInitParameter("mailServer");
92         mailServerPort = config.getInitParameter("mailServerPort");
93         
94         JavaMailAsyncFilter.register(
95                 config.getInitParameter("contextPath"), this);
96     }
97    
98     
99     /**
100      * The <code>doGet</code> will execute only when the Grizzly
101      * <code>JavaMailAsyncFilter</code> determines this servlet can execute.
102      * The <code>JavaMailAsyncFilter</code> will allow the execution of this
103      * Servlet only if a new email message arrive in the remote email account.
104      */

105     public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
106                                         throws ServletException JavaDoc, IOException JavaDoc {
107         
108         PrintWriter JavaDoc out = response.getWriter();
109         try{
110             
111             if ( messages != null) {
112                 out.println("<html>");
113                     out.println("<HEAD><TITLE>Async JavaMail Servlet</TITLE></HEAD>");
114                 out.println("<BODY bgcolor=\"#ccccff\">");
115                 out.print("<center><font face=\"Arial,Helvetica\" ");
116                 out.println("font size=\"+3\"><b>");
117                 out.println("You have " + messages.length + " messages in folder "
118                         + "inbox</b></font></center><p>");
119
120                 for (int i=0; i < messages.length; i++){
121                     try {
122                         Message JavaDoc msg = messages[i];
123                         displayMessageHeaders(msg, out);
124
125                         try{
126                             Object JavaDoc o = msg.getContent();
127
128                             out.println("<pre>");
129                             out.println((String JavaDoc)o);
130                             out.println("</pre>");
131                         } catch (NullPointerException JavaDoc ex){
132                             ; //If the message isn't having body
133
}
134                      } catch (MessagingException JavaDoc mex) {
135                         out.println(mex.toString());
136                     }
137                 }
138             }
139   
140             out.println("</BODY></html>");
141             out.close();
142         } catch (Throwable JavaDoc t){
143            t.printStackTrace();
144         }
145     }
146
147     // --------------------------------------------------------- Async Hook ---/
148

149     /**
150      * The <code>JavaMailAsyncFilter</code> will invoke that method after
151      * fetching the email from the remote account. This method will return
152      * <code>true</code> if the messages retrived aren't new or no new message
153      * has been found. Returning <code>true</code> means the Servlet shouldn't
154      * yet be executed. Returning <code>false</code> will fire the execution
155      * of this Servlet.
156      * @paramc event The JavaMailAsyncFilterEvent notification from
157      * JavaMailAsyncFilter
158      */

159     public boolean handleEvent(JavaMailAsyncFilterEvent event) {
160         messages = event.getMessages();
161
162         if ( messages == null || messages.length == 0){
163             return true;
164         } else {
165             return false;
166         }
167     }
168
169     
170     public String JavaDoc getUserName() {
171        return username;
172     }
173
174     
175     public String JavaDoc getPassword() {
176         return password;
177     }
178
179     
180     public String JavaDoc getMailServer() {
181         return mailServer;
182     }
183
184     
185     public String JavaDoc getMailServerPort() {
186         return mailServerPort;
187     }
188     
189     // -------------------------------------------------------- JavaMail ----/
190

191     private String JavaDoc getDisplayAddress(Address JavaDoc a) {
192         String JavaDoc pers = null;
193         String JavaDoc addr = null;
194         if (a instanceof InternetAddress JavaDoc &&
195             ((pers = ((InternetAddress JavaDoc)a).getPersonal()) != null)) {
196
197             addr = pers + " "+"&lt;"+((InternetAddress JavaDoc)a).getAddress()+"&gt;";
198         } else
199             addr = a.toString();
200
201         return addr;
202     }
203
204     
205     private void displayMessageHeaders(Message JavaDoc msg, PrintWriter JavaDoc out)
206         throws IOException JavaDoc {
207
208         try {
209             out.println("<b>Date:</b> " + msg.getSentDate() + "<br>");
210
211             Address JavaDoc[] fr = msg.getFrom();
212             if (fr != null) {
213                 boolean tf = true;
214                 out.print("<b>From:</b> ");
215                 for (int i = 0; i < fr.length; i++) {
216                     out.print(((tf) ? " " : ", ") + getDisplayAddress(fr[i]));
217                     tf = false;
218                 }
219                 out.println("<br>");
220             }
221
222             Address JavaDoc[] to = msg.getRecipients(Message.RecipientType.TO);
223             if (to != null) {
224                 boolean tf = true;
225                 out.print("<b>To:</b> ");
226                 for (int i = 0; i < to.length; i++) {
227                     out.print(((tf) ? " " : ", ") + getDisplayAddress(to[i]));
228                     tf = false;
229                 }
230                 out.println("<br>");
231             }
232
233             Address JavaDoc[] cc = msg.getRecipients(Message.RecipientType.CC);
234             if (cc != null) {
235                 boolean cf = true;
236                 out.print("<b>CC:</b> ");
237                 for (int i = 0; i < cc.length; i++) {
238                     out.print(((cf) ? " " : ", ") + getDisplayAddress(cc[i]));
239             cf = false;
240             }
241                     out.println("<br>");
242                 }
243
244             out.print("<b>Subject:</b> " +
245                   ((msg.getSubject() !=null) ? msg.getSubject() : "") +
246                   "<br>");
247
248         } catch (MessagingException JavaDoc mex) {
249             out.println(msg.toString());
250         }
251     }
252
253 }
254
Popular Tags