KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > applications > email > EmailBuilder


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.applications.email;
11
12 import java.util.ArrayList JavaDoc;
13 import java.util.List JavaDoc;
14 import java.util.Locale JavaDoc;
15 import java.util.MissingResourceException JavaDoc;
16 import java.util.ResourceBundle JavaDoc;
17
18 import org.mmbase.module.Module;
19 import org.mmbase.module.core.*;
20
21 import org.mmbase.storage.search.*;
22 import org.mmbase.storage.search.implementation.*;
23
24 import org.mmbase.util.functions.Functions;
25 import org.mmbase.util.functions.Parameter;
26 import org.mmbase.util.functions.Parameters;
27 import org.mmbase.util.logging.Logger;
28 import org.mmbase.util.logging.Logging;
29
30 /**
31  * Email builder.
32  * Rewrite of the email system, that became too complex to handle.
33  * The focus on the new one is different.
34  * The code is now split per mail type to allow for easer debug and better control over the 'simple'
35  * mail action. The delayed and repeat mail will be handled with
36  * the upcomming crontab builder
37  *
38  * @javadoc is a bit lame
39  *
40  * @author Daniel Ockeloen
41  * @author Michiel Meeuwissen
42  */

43 public class EmailBuilder extends MMObjectBuilder {
44
45     private static final Logger log = Logging.getLoggerInstance(EmailBuilder.class);
46
47     public final static Parameter[] MAIL_PARAMETERS = {
48         new Parameter("type", String JavaDoc.class)
49     };
50
51
52     public final static Parameter[] STARTMAIL_PARAMETERS = MAIL_PARAMETERS;
53     public final static Parameter[] SETTYPE_PARAMETERS = MAIL_PARAMETERS;
54
55     // defined values for state ( node field "mailstatus" )
56
public final static int STATE_UNKNOWN = -1; // unknown
57
public final static int STATE_WAITING = 0; // waiting
58
public final static int STATE_DELIVERED = 1; // delivered
59
public final static int STATE_FAILED = 2; // failed
60
public final static int STATE_SPAMGARDE = 3; // spam filter hit, not mailed
61
public final static int STATE_QUEUED = 4; // queued
62

63
64     // defined values for state ( node field "mailtype" )
65
public final static int TYPE_ONESHOT = 1; // Email will be sent and removed after sending.
66
// public final static int TYPE_REPEATMAIL = 2; // Email will be sent and scheduled after sending for a next time (does not work?)
67
public final static int TYPE_ONESHOTKEEP = 3; // Email will be sent and will not be removed.
68

69     public final static String JavaDoc EMAILTYPE_RESOURCE = "org.mmbase.applications.email.resources.mailtype";
70     public final static String JavaDoc EMAILSTATUS_RESOURCE = "org.mmbase.applications.email.resources.mailstatus";
71
72     static String JavaDoc usersBuilder;
73     static String JavaDoc usersEmailField;
74     static String JavaDoc groupsBuilder;
75
76     // reference to the sendmail module
77
private static SendMailInterface sendmail;
78
79     // reference to the expire handler
80
private static EmailExpireHandler expirehandler;
81
82     protected int expireTime = 60;
83     protected int sleepTime = 60*30;
84
85     /**
86      * init
87      */

88     public boolean init() {
89         super.init ();
90
91         // get the sendmail module
92
sendmail = (SendMailInterface) Module.getModule("sendmail");
93
94         String JavaDoc property = getInitParameter("expireTime");
95         if (property != null) {
96             try {
97                 expireTime = Integer.parseInt(property);
98             } catch(NumberFormatException JavaDoc nfe) {
99                 log.warn("property: expireTime contained an invalid integer value:'" + property +"'(" + nfe + ")");
100             }
101         }
102
103         property = getInitParameter("sleepTime");
104         if (property != null) {
105             try {
106                 sleepTime = Integer.parseInt(property);
107             } catch(NumberFormatException JavaDoc nfe) {
108                 log.warn("property: sleepTime contained an invalid integer value:'" + property +"'(" + nfe + ")");
109             }
110         }
111
112         if (sleepTime > 0 && expireTime >0) {
113             // start the email nodes expire handler, deletes
114
// oneshot email nodes after the defined expiretime
115
// check every defined sleeptime
116
log.service("Expirehandler started with sleep time " + sleepTime + "sec, expire time " + expireTime + "sec.");
117             expirehandler = new EmailExpireHandler(this, sleepTime, expireTime);
118         } else {
119             log.service("Expirehandler not started");
120         }
121
122         usersBuilder = getInitParameter("users-builder");
123         if (usersBuilder == null) usersBuilder = "users";
124
125         usersEmailField = getInitParameter("users-email-field");
126         if (usersEmailField == null) usersEmailField = "email";
127
128         groupsBuilder = getInitParameter("groups-builder");
129         if (groupsBuilder == null) groupsBuilder = "groups";
130
131         return true;
132     }
133
134     /**
135      * Get the display string for a given field of this node.
136      * @param locale de locale voor de gui value
137      * @param field name of the field to describe.
138      * @param node Node containing the field data.
139      * @return A <code>String</code> describing the requested field's content
140      */

141     public String JavaDoc getLocaleGUIIndicator(Locale JavaDoc locale, String JavaDoc field, MMObjectNode node) {
142         if (field.equals("mailstatus")) {
143             String JavaDoc val = node.getStringValue("mailstatus");
144             log.debug("val: " + val); // 0, 1, 2, 3
145
ResourceBundle JavaDoc bundle;
146             bundle = ResourceBundle.getBundle(EMAILTYPE_RESOURCE, locale, getClass().getClassLoader() );
147             try {
148                 return bundle.getString(val);
149             } catch (MissingResourceException JavaDoc e) {
150                 return val;
151             }
152         } else if (field.equals("mailtype")){ // mailtype
153
String JavaDoc val = node.getStringValue("mailtype");
154             return getMailtypeResource(val,locale);
155         } else {
156             return super.getLocaleGUIIndicator(locale,field,node);
157         }
158     }
159
160     /**
161      * {@inheritDoc}
162      *
163      * Override the function call to receive the functions called from
164      * the outside world (mostly from the taglibs)
165      */

166     protected Object JavaDoc executeFunction(MMObjectNode node, String JavaDoc function, List JavaDoc args) {
167         if (log.isDebugEnabled()) {
168             log.debug("function: " + function);
169         }
170         if (function.equals("info")) {
171             List JavaDoc empty = new ArrayList JavaDoc();
172             java.util.Map JavaDoc info = (java.util.Map JavaDoc) super.executeFunction(node, function, empty);
173             info.put("gui", "(mailtype or mailstatus) Gui representation of this object.");
174             if (args == null || args.size() == 0) {
175                 return info;
176             } else {
177                 return info.get(args.get(0));
178             }
179         } else if (function.equals("setType") || function.equals("settype") ) {
180             setType(node, args);
181             return null;
182         } else if (function.equals("mail")) { // function mail(type) called
183
log.debug("We're in mail - args: " + args);
184             setType(node, args);
185
186             // get the mailtype so we can call the correct handler/method
187
int mailType = node.getIntValue("mailtype");
188             switch(mailType) {
189             case TYPE_ONESHOT :
190                 // deleting the node happens in EmailExpireHandler
191
case TYPE_ONESHOTKEEP :
192                 EmailHandler.sendMailNode(node);
193                 break;
194             // case TYPE_REPEATMAIL :
195
default:
196                 log.warn("Trying to mail a node with unsupported type " + mailType);
197             }
198
199             String JavaDoc val = node.getStringValue("mailtype");
200             return null;
201         } else if (function.equals("startmail")) { // function startmail(type) called (starts a background thread)
202
log.debug("We are in startmail - args: " + args);
203             // check if we have arguments ifso call setType()
204
setType(node, args);
205
206             // get the mailtype so we can call the correct handler/method
207
int mailType = node.getIntValue("mailtype");
208             log.debug("mailtype: " + mailType);
209             switch(mailType) {
210             case TYPE_ONESHOT :
211                 // deleting the node happens in EmailExpireHandler
212
case TYPE_ONESHOTKEEP :
213                 new EmailBackgroundHandler(node);
214                 break;
215             // case TYPE_REPEATMAIL :
216
default:
217                 log.warn("Trying to start a mail of a node with unsupported type " + mailType);
218             }
219             String JavaDoc val = node.getStringValue("mailtype");
220             return null;
221         }
222         if (log.isDebugEnabled()) {
223             log.debug("Function '" + function + "' is not found in email app.");
224         }
225         return super.executeFunction(node, function, args);
226     }
227
228     /**
229      * Return the sendmail module
230      */

231     static SendMailInterface getSendMail() {
232         return sendmail;
233     }
234
235     /**
236      * Set the mailtype based on the first argument in the list.
237      *
238      * @param node Email node on which to set the type
239      * @param args List with arguments
240      */

241     private static void setType(MMObjectNode node, List JavaDoc args) {
242         String JavaDoc type = (String JavaDoc) args.get(0);
243         if ("oneshot".equals(type)) {
244             node.setValue("mailtype", TYPE_ONESHOT);
245             log.debug("Setting mailtype to: " + TYPE_ONESHOT);
246         } else if ("oneshotkeep".equals(type)) {
247             node.setValue("mailtype", TYPE_ONESHOTKEEP);
248             log.debug("Setting mailtype to " + TYPE_ONESHOTKEEP);
249         } else {
250             node.setValue("mailtype", TYPE_ONESHOT);
251             log.debug("Setting mailtype to: " + TYPE_ONESHOT);
252         }
253     }
254
255     /**
256      * Mailtype maps to an int in a resource, this method finds it,
257      * if possible and available the localized version of it.
258      *
259      * @param val The int value that maps to a mailtype (1 = oneshot etc.)
260      * @param locale de locale voor de gui value
261      * @return A String from the resource file being a mailtype
262      */

263     private String JavaDoc getMailtypeResource(String JavaDoc val, Locale JavaDoc locale) {
264         ResourceBundle JavaDoc bundle = ResourceBundle.getBundle(EMAILTYPE_RESOURCE, locale, getClass().getClassLoader());
265         try {
266             return bundle.getString(val);
267         } catch (MissingResourceException JavaDoc e) {
268             return val;
269         }
270     }
271
272
273     /**
274      * Returns all the one-shot delivered mail nodes older than a specified time.
275      * This is used by {@link EmailExpireHandler} to remove expired emails.
276      * @param expireAge The minimum age of the desired nodes in seconds
277      * @return a unmodifiable List of MMObjectNodes
278      */

279     List JavaDoc getDeliveredMailOlderThan(long expireAge) {
280         // calc search time based on expire time
281
long age = (System.currentTimeMillis() / 1000) - expireAge;
282         // query database for the nodes
283

284         NodeSearchQuery query = new NodeSearchQuery(this);
285         BasicCompositeConstraint cons = new BasicCompositeConstraint(CompositeConstraint.LOGICAL_AND);
286
287         cons.addChild(new BasicFieldValueConstraint(query.getField(getField("mailstatus")), new Integer JavaDoc(STATE_DELIVERED)));
288         cons.addChild(new BasicFieldValueConstraint(query.getField(getField("mailtype")), new Integer JavaDoc(TYPE_ONESHOT)));
289         cons.addChild(new BasicFieldValueConstraint(query.getField(getField("mailedtime")), new Long JavaDoc(age)).setOperator(FieldCompareConstraint.LESS));
290         query.setConstraint(cons);
291         try {
292             return getNodes(query);
293         } catch (SearchQueryException sqe) {
294             log.error(sqe.getMessage());
295             return new ArrayList JavaDoc();
296         }
297
298     }
299 }
300
Popular Tags