KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > mail > MailAction


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.mail;
17
18 import java.text.SimpleDateFormat JavaDoc;
19 import java.util.HashMap JavaDoc;
20 import java.util.Iterator JavaDoc;
21 import java.util.List JavaDoc;
22 import java.util.Map JavaDoc;
23 import java.util.Properties JavaDoc;
24
25 import javax.mail.Folder JavaDoc;
26 import javax.mail.Message JavaDoc;
27 import javax.mail.Provider JavaDoc;
28 import javax.mail.Store JavaDoc;
29 import javax.mail.URLName JavaDoc;
30
31 import org.apache.avalon.framework.context.ContextException;
32 import org.apache.avalon.framework.logger.Logger;
33 import org.apache.avalon.framework.parameters.Parameters;
34 import org.apache.avalon.framework.thread.ThreadSafe;
35 import org.apache.cocoon.ProcessingException;
36 import org.apache.cocoon.acting.ServiceableAction;
37 import org.apache.cocoon.environment.ObjectModelHelper;
38 import org.apache.cocoon.environment.Redirector;
39 import org.apache.cocoon.environment.Request;
40 import org.apache.cocoon.environment.Session;
41 import org.apache.cocoon.environment.SourceResolver;
42 import org.apache.cocoon.mail.command.AbstractMailCommand;
43
44 /**
45  * This action creates javamail objects, and puts XMLizable object wrappers
46  * of these objects into the request attribute map.
47  * <p>
48  * This action enables javamail access as action. It creates an http sesion,
49  * and puts the MailContext object into the session attributes.
50  * </p>
51  *
52  * @see MailContext
53  *
54  * @author Bernhard Huber
55  * @version CVS $Id: MailAction.java 30932 2004-07-29 17:35:38Z vgritsenko $
56  * @since Cocoon 2.1, 16 December 2002
57  */

58 public class MailAction extends ServiceableAction implements ThreadSafe {
59
60     /**
61      * Request attribute name of a XMLizable folder
62      */

63     public final static String JavaDoc REQUEST_ATTRIBUTE_FOLDER = "folder";
64     /**
65      * Request attribute name of a XMLizable folders object
66      */

67     public final static String JavaDoc REQUEST_ATTRIBUTE_FOLDERS = "folders";
68     /**
69      * Request attribute name of a XMLizable message object
70      */

71     public final static String JavaDoc REQUEST_ATTRIBUTE_MESSAGE = "message";
72     /**
73      * Request attribute name of a XMLizable messages object
74      */

75     public final static String JavaDoc REQUEST_ATTRIBUTE_MESSAGES = "messages";
76
77
78     /**
79      * Execute mail commands.
80      *
81      *@param redirector Cocoon's redirector
82      *@param resolver Cocoon's source resolver, used for testing if a source is resolvable
83      *@param source the source, e.g.: index.html
84      *@param objectModel Description of the Parameter
85      *@param par Description of the Parameter
86      *@exception Exception Description of the Exception
87      */

88     public Map JavaDoc act(Redirector redirector, SourceResolver resolver, Map JavaDoc objectModel, String JavaDoc source, Parameters par) throws Exception JavaDoc {
89         Map JavaDoc actionMap = new HashMap JavaDoc();
90
91         Request request = ObjectModelHelper.getRequest(objectModel);
92
93         String JavaDoc command = request.getParameter("cmd");
94         String JavaDoc folderName = request.getParameter("folder");
95         String JavaDoc userid = request.getParameter("mail-userid");
96         String JavaDoc password = request.getParameter("mail-password");
97
98         // assert mailContext is available
99
Session session = request.getSession(true);
100         MailContext mailContext = (MailContext) session.getAttribute(MailContext.SESSION_MAIL_CONTEXT);
101         if (mailContext == null) {
102             // no mailContext is yet available
103
// create it and put it into http-session
104
mailContext = new MailContextHttpSession(null);
105             mailContext.enableLogging(getLogger());
106             session.setAttribute(MailContext.SESSION_MAIL_CONTEXT, mailContext);
107         }
108
109         // assert mailSession is available
110
javax.mail.Session JavaDoc mailSession = null;
111         Store JavaDoc mailStore = null;
112         try {
113             try {
114                 mailSession = (javax.mail.Session JavaDoc) mailContext.get(MailContext.MAIL_SESSION_ENTRY);
115             } catch (ContextException ce) {
116                 // build session properties
117
Properties JavaDoc sessionProperties = new Properties JavaDoc();
118                 String JavaDoc[] allParameterNames = par.getNames();
119                 for (int i = 0; i < allParameterNames.length; i++) {
120                     String JavaDoc parameterName = allParameterNames[i];
121                     final String JavaDoc PARAMETER_NAME_PREFIX = "javax.mail.Session.props:";
122                     if (parameterName.startsWith(PARAMETER_NAME_PREFIX)) {
123                         String JavaDoc sessionPropName = parameterName.substring(PARAMETER_NAME_PREFIX.length());
124                         String JavaDoc sessionPropValue = par.getParameter(parameterName, null);
125                         if (sessionPropValue != null) {
126                             getLogger().debug("Add session property " +
127                                     String.valueOf(sessionPropName) + ": " +
128                                     String.valueOf(sessionPropValue));
129                             sessionProperties.put(sessionPropName, sessionPropValue);
130                         }
131                     }
132                 }
133                 mailSession = javax.mail.Session.getDefaultInstance(sessionProperties, null);
134                 checkProviders(mailSession);
135                 mailContext.put(MailContext.MAIL_SESSION_ENTRY, mailSession);
136             }
137         } catch (Exception JavaDoc e) {
138             String JavaDoc message = "Cannot create mail session";
139             getLogger().error(message, e);
140             throw new ProcessingException(message, e);
141         }
142
143         // assert mailStore is available
144
String JavaDoc storeURLNameExpanded = null;
145         String JavaDoc storeURLNameTemplate = par.getParameter("store-urlname", null);
146         try {
147             try {
148                 mailStore = (Store JavaDoc) mailContext.get(MailContext.MAIL_STORE_ENTRY);
149             } catch (ContextException ce) {
150
151                 // imap://{userid}:{password}@host:port/
152
storeURLNameExpanded = getURLNameExpanded(storeURLNameTemplate, userid, password);
153
154                 URLName JavaDoc urlNameExpanded = new URLName JavaDoc(storeURLNameExpanded);
155                 getLogger().info("get store using URLName " + String.valueOf(urlNameExpanded));
156                 mailStore = mailSession.getStore(urlNameExpanded);
157                 mailStore.connect();
158                 mailContext.put(MailContext.MAIL_STORE_ENTRY, mailStore);
159             }
160         } catch (Exception JavaDoc e) {
161             String JavaDoc message = "Cannot get store, and connect " + String.valueOf(storeURLNameExpanded);
162             getLogger().error(message, e);
163             throw new ProcessingException(message, e);
164         }
165
166         if (folderName != null) {
167             // make folderName the current working folder (a la cwd)
168
// check foldername a bit
169
mailContext.put(MailContext.MAIL_CURRENT_WORKING_FOLDER_ENTRY, folderName);
170         } else {
171             // no folderName in request parameter, retrieve current working folder
172
folderName = (String JavaDoc) mailContext.get(MailContext.MAIL_CURRENT_WORKING_FOLDER_ENTRY);
173         }
174         actionMap.put(MailContext.MAIL_CURRENT_WORKING_FOLDER_ENTRY, folderName);
175
176         if (command != null) {
177             mailContext.put(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY, command);
178         } else {
179             command = (String JavaDoc) mailContext.get(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY);
180         }
181         actionMap.put(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY, command);
182
183         // mailSession and mailStore are available
184

185         // excecute mail command, and populate request attribute
186
mailContext.setRequest(request);
187         populateRequestAttribute(request, mailContext);
188         // it's better to release ref to request, as it is not needed, and helps
189
// recycling of the request
190
mailContext.setRequest(null);
191
192         return actionMap;
193     }
194
195
196     /**
197      * Gets the uRLNameExpanded attribute of the MailGenerator object
198      *
199      *@param storeURLNameTemplate Description of the Parameter
200      *@param userid Description of the Parameter
201      *@param password Description of the Parameter
202      *@return The uRLNameExpanded value
203      */

204     protected String JavaDoc getURLNameExpanded(String JavaDoc storeURLNameTemplate, String JavaDoc userid, String JavaDoc password) {
205         String JavaDoc tokenStart = "''";
206         String JavaDoc tokenEnd = "''";
207         Properties JavaDoc filters = new Properties JavaDoc();
208         filters.put("mail-userid", userid);
209         filters.put("mail-passwd", password);
210
211         String JavaDoc filteredURLName = filter(tokenStart, tokenEnd, storeURLNameTemplate, filters);
212         return filteredURLName;
213     }
214
215
216     /**
217      * replace occurences of <code>TOKEN_STARTxxxTOKEN_END</code> by value of entry xxx in tokens table.
218      *
219      *@param tokenStart token start marker
220      *@param tokenEnd token end marker
221      *@param s the string examined
222      *@param tokens Description of the Parameter
223      *@return String replaced all tokenized entries of original String s.
224      */

225     protected String JavaDoc filter(final String JavaDoc tokenStart, final String JavaDoc tokenEnd, String JavaDoc s, Properties JavaDoc tokens) {
226         int index = s.indexOf(tokenStart);
227
228         if (index > -1) {
229             try {
230                 StringBuffer JavaDoc b = new StringBuffer JavaDoc();
231                 int i = 0;
232                 String JavaDoc token = null;
233                 String JavaDoc value = null;
234
235                 do {
236                     int endIndex = s.indexOf(tokenEnd, index + tokenStart.length() + 1);
237                     if (endIndex == -1) {
238                         break;
239                     }
240                     token = s.substring(index + tokenStart.length(), endIndex);
241                     b.append(s.substring(i, index));
242                     if (tokens.containsKey(token)) {
243                         value = (String JavaDoc) tokens.get(token);
244                         b.append(value);
245                         i = index + tokenStart.length() + token.length() + tokenEnd.length();
246                     } else {
247                         // just append TOKEN_START and search further
248
b.append(tokenStart);
249                         i = index + tokenStart.length();
250                     }
251                 } while ((index = s.indexOf(tokenStart, i)) > -1);
252
253                 b.append(s.substring(i));
254                 return b.toString();
255             } catch (StringIndexOutOfBoundsException JavaDoc e) {
256                 return s;
257             }
258         } else {
259             return s;
260         }
261     }
262
263
264     /**
265      * Check that the provider need is available
266      *
267      *@param session The javamail Session used for checking its providers.
268      */

269     protected void checkProviders(javax.mail.Session JavaDoc session) {
270         Provider JavaDoc[] providers = session.getProviders();
271         // just log the available providers
272
for (int i = 0; i < providers.length; i++) {
273             getLogger().info("mail provider " + providers[i]);
274         }
275     }
276
277
278     /**
279      * Populate request attribute map.
280      * <p>
281      * Execute mail command, and populate request attribute map with
282      * XMLizable javamail objects, created by the mail command
283      * </p>
284      *
285      *@param request triggering the creation of javamail objects
286      *@param mailContext javamail context, store, session, folders
287      *@exception Exception Description of the Exception
288      */

289     protected void populateRequestAttribute(Request request, MailContext mailContext) throws Exception JavaDoc {
290         String JavaDoc folderName = (String JavaDoc) mailContext.get(MailContext.MAIL_CURRENT_WORKING_FOLDER_ENTRY);
291         request.setAttribute(MailContext.MAIL_CURRENT_WORKING_FOLDER_ENTRY, folderName);
292         String JavaDoc command = (String JavaDoc) mailContext.get(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY);
293         request.setAttribute(MailContext.MAIL_CURRENT_WORKING_COMMAND_ENTRY, command);
294
295         // build javamail objects
296
List JavaDoc javaMailResult = retrieveJavaMailObjects(mailContext);
297         Iterator JavaDoc javaMailResultIterator;
298
299         // put javamail objects into request attribute map
300
javaMailResultIterator = javaMailResult.iterator();
301         //Request request = ObjectModelHelper.getRequest(objectModel);
302
putXMLizerToRequestAttribute(request, javaMailResultIterator);
303     }
304
305
306     /**
307      * Put XMLizable javamail objects into request attribute map
308      *
309      *@param request holding the destination attribute map
310      *@param resultIterator Iterator of
311      */

312     protected void putXMLizerToRequestAttribute(Request request, Iterator JavaDoc resultIterator) {
313         if (resultIterator != null) {
314             // marshal java mail objects
315
Logger logger = getLogger();
316
317             // make it an optional parameter?
318
String JavaDoc datePattern = "dd.MM.yyyy HH:mm";
319             SimpleDateFormat JavaDoc sdf = new SimpleDateFormat JavaDoc(datePattern);
320
321             while (resultIterator.hasNext()) {
322                 Object JavaDoc objRef = resultIterator.next();
323
324                 getLogger().debug("Creating XMLizer for " + String.valueOf(objRef));
325
326                 if (objRef instanceof Folder JavaDoc) {
327                     MailContentHandlerDelegate.FolderXMLizer fx = new MailContentHandlerDelegate.FolderXMLizer((Folder JavaDoc) objRef);
328                     fx.enableLogging(logger);
329                     request.setAttribute(REQUEST_ATTRIBUTE_FOLDER, fx);
330                 } else if (objRef instanceof Folder JavaDoc[]) {
331                     Folder JavaDoc[] folders = (Folder JavaDoc[]) objRef;
332                     MailContentHandlerDelegate.FolderXMLizer[] fxs = new MailContentHandlerDelegate.FolderXMLizer[folders.length];
333                     for (int i = 0; i < folders.length; i++) {
334                         fxs[i] = new MailContentHandlerDelegate.FolderXMLizer(folders[i]);
335                         fxs[i].enableLogging(logger);
336                     }
337                     // trust that array of XMLizable is handled
338
request.setAttribute(REQUEST_ATTRIBUTE_FOLDERS, fxs);
339                 } else if (objRef instanceof Message JavaDoc) {
340                     MailContentHandlerDelegate.MessageXMLizer mx = new MailContentHandlerDelegate.MessageXMLizer((Message JavaDoc) objRef);
341                     mx.enableLogging(logger);
342                     mx.setSimpleDateFormat(sdf);
343                     request.setAttribute(REQUEST_ATTRIBUTE_MESSAGE, mx);
344                 } else if (objRef instanceof Message JavaDoc[]) {
345                     MailContentHandlerDelegate.MessageEnvelopeXMLizer mex = new MailContentHandlerDelegate.MessageEnvelopeXMLizer((Message JavaDoc[]) objRef);
346                     mex.enableLogging(logger);
347                     mex.setSimpleDateFormat(sdf);
348                     request.setAttribute(REQUEST_ATTRIBUTE_MESSAGES, mex);
349                 }
350             }
351         }
352     }
353
354
355     /**
356      * Retrieve javamail objects
357      *
358      *@param mailContext Description of the Parameter
359      *@return List of retrieved javamail objects
360      *@exception ProcessingException thrown iff retrieval fails
361      */

362     protected List JavaDoc retrieveJavaMailObjects(MailContext mailContext) throws ProcessingException {
363
364         List JavaDoc result = null;
365         try {
366             // do we have a MailCommandManager ?
367
MailCommandManager mam = new MailCommandManager();
368             mam.enableLogging(getLogger());
369
370             // build the MailCommand(s)
371
MailCommandBuilder mab = new MailCommandBuilder();
372             mab.enableLogging(getLogger());
373             AbstractMailCommand ama = mab.buildAbstractMailCommand(mailContext);
374
375             getLogger().debug("Executing " + String.valueOf(ama));
376
377             // execute the command(s)
378
result = mam.execute(ama);
379
380             // return the javamail objects
381
return result;
382         } catch (Exception JavaDoc e) {
383             String JavaDoc message = "Cannot retrieve javamail objects";
384             getLogger().error(message, e);
385             throw new ProcessingException(message, e);
386         }
387     }
388 }
389
390
Popular Tags