KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jcorporate > expresso > core > misc > EventHandler


1 /* ====================================================================
2  * The Jcorporate Apache Style Software License, Version 1.2 05-07-2002
3  *
4  * Copyright (c) 1995-2002 Jcorporate Ltd. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by Jcorporate Ltd.
21  * (http://www.jcorporate.com/)."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. "Jcorporate" and product names such as "Expresso" must
26  * not be used to endorse or promote products derived from this
27  * software without prior written permission. For written permission,
28  * please contact info@jcorporate.com.
29  *
30  * 5. Products derived from this software may not be called "Expresso",
31  * or other Jcorporate product names; nor may "Expresso" or other
32  * Jcorporate product names appear in their name, without prior
33  * written permission of Jcorporate Ltd.
34  *
35  * 6. No product derived from this software may compete in the same
36  * market space, i.e. framework, without prior written permission
37  * of Jcorporate Ltd. For written permission, please contact
38  * partners@jcorporate.com.
39  *
40  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
41  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
42  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
43  * DISCLAIMED. IN NO EVENT SHALL JCORPORATE LTD OR ITS CONTRIBUTORS
44  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
45  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
47  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
49  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
50  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This software consists of voluntary contributions made by many
55  * individuals on behalf of the Jcorporate Ltd. Contributions back
56  * to the project(s) are encouraged when you make modifications.
57  * Please send them to support@jcorporate.com. For more information
58  * on Jcorporate Ltd. and its products, please see
59  * <http://www.jcorporate.com/>.
60  *
61  * Portions of this software are based upon other open source
62  * products and are subject to their respective licenses.
63  */

64
65 /*
66  * EventHandler.java
67  *
68  * Copyright 1999, 2000, 2001 Jcorporate Ltd.
69  */

70 package com.jcorporate.expresso.core.misc;
71
72 import com.jcorporate.expresso.core.db.DBException;
73 import com.jcorporate.expresso.core.registry.ExpressoThread;
74 import com.jcorporate.expresso.core.security.User;
75 import com.jcorporate.expresso.services.dbobj.Event;
76 import org.apache.log4j.Logger;
77
78 import java.util.Vector JavaDoc;
79
80
81 /**
82  * The EventHandler is an asynchronous handler for email Event notifications - it accepts
83  * requests to trigger an event, then sends them "eventually" in a seperate thread
84  *
85  * @author Michael Nash
86  */

87 public class EventHandler extends ExpressoThread {
88     private static Vector JavaDoc queue = new Vector JavaDoc(3);
89     private static EventHandler myInstance = null;
90
91     /**
92      * Event Handler shuts down it's background thread when it's been
93      * idle for a while
94      */

95     private static int idleTimes = 0;
96     private static int maxIdleTimes = 10;
97
98     /**
99      * Don't process more than a certain number of Event entries, it slows
100      * the system down too much
101      */

102     private static int maxWrites = 5;
103
104     /**
105      * How long to sleep between checking the queue
106      */

107     private static int sleepTime = 30;
108     private static Logger log = Logger.getLogger(EventHandler.class);
109     private static final String JavaDoc thisClass = EventHandler.class.getName() + ".";
110
111     /**
112      * Constructor
113      */

114     public EventHandler() {
115
116     } /* EventHandler() */
117
118     /**
119      * Actually check the event queue and trigger the events or send
120      * notices (electronic mail pertaining to registering Expresso
121      * Framework users)
122      *
123      * @throws DBException upon error.
124      */

125     private synchronized void checkQueue()
126             throws DBException {
127         String JavaDoc myName = (thisClass + "checkQueue()");
128
129         if (queue.size() == 0) {
130             idleTimes++;
131
132             if (log.isDebugEnabled()) {
133                 log.debug("Event queue empty - idle " + idleTimes + " times");
134             }
135
136             return;
137         }
138         if (log.isDebugEnabled()) {
139             log.debug("Checking event queue. " + queue.size() + " entries");
140         }
141
142         EventQueueEntry oneEventQueueEntry = null;
143
144         try {
145             int writeCount = 0;
146
147             // Process all pending entries in the queue. Iterate
148
// through the queue until all elements are processed.
149
while (queue.size() > 0) {
150                 oneEventQueueEntry = (EventQueueEntry) queue.firstElement();
151                 queue.removeElementAt(0);
152
153                 // Is this a queue entry an event or a notice?
154
if (oneEventQueueEntry.isNotice()) {
155                     // It is a notice, send electronic mail
156
User myUser = new User();
157                     myUser.setDataContext(oneEventQueueEntry.getDataContext());
158                     myUser.setUid(oneEventQueueEntry.getUid());
159
160                     if (myUser.find()) {
161                         myUser.notify(oneEventQueueEntry.getSubject(),
162                                 oneEventQueueEntry.getTheMessage(),
163                                 false /*htmlMail*/,
164                                 oneEventQueueEntry.getAttachments());
165                     } else {
166                         log.error("Unable to send notice to user " +
167                                 oneEventQueueEntry.getUid() + ": No such user");
168                     }
169                 } else {
170                     // It is a event, process accordingly
171
new Event(oneEventQueueEntry.getDataContext(),
172                             oneEventQueueEntry.getTheEvent(),
173                             oneEventQueueEntry.getTheMessage(),
174                             oneEventQueueEntry.isSuccess());
175                 }
176
177                 writeCount++;
178
179                 if (writeCount > maxWrites) {
180                     break;
181                 }
182             } /* for each queue entry */
183
184         } catch (Exception JavaDoc de) {
185             log.error("Error sending event from queue", de);
186             throw new DBException(myName + ":Error sending event from queue", de);
187         }
188     } /* checkQueue() */
189
190
191     /**
192      * Queue the requested event for later processing
193      *
194      * @param dbName the database context
195      * @param theEvent the subject line of the event
196      * @param theMessage the message text
197      * @param success the boolean status flag
198      */

199     public static void Event(String JavaDoc dbName, String JavaDoc theEvent, String JavaDoc theMessage, boolean success) {
200
201         if (log.isDebugEnabled()) {
202             log.debug("New event queued:" + theEvent + ":" + theMessage);
203         }
204
205         EventQueueEntry newEntry = new EventQueueEntry(theEvent, theMessage, success);
206         newEntry.setDataContext(dbName);
207         queue.addElement(newEntry);
208         startUp();
209     } /* Event(String, String, String, boolean) */
210
211
212     /**
213      * @throws DBException
214      */

215     public static void flush()
216             throws DBException {
217         startUp();
218         myInstance.checkQueue();
219     } /* flush() */
220
221     /**
222      * Send a user a notification via e-mail with virtual data source attachments.
223      *
224      * @param dbName data context name
225      * @param uid the user id
226      * @param subject Subject of the e-mail
227      * @param message Message to send in body of e-mail
228      */

229     public static void notify(String JavaDoc dbName, int uid, String JavaDoc subject, String JavaDoc message) {
230         notify(dbName, uid, subject, message, null);
231     }
232
233     /**
234      * Send a user a notification via e-mail with virtual data source attachments.
235      *
236      * @param dbName data context name
237      * @param uid the user id
238      * @param subject Subject of the e-mail
239      * @param message Message to send in body of e-mail
240      * @param attachments the array list of virtual byte array data sources
241      */

242     public static void notify(String JavaDoc dbName, int uid, String JavaDoc subject, String JavaDoc message,
243                               ByteArrayDataSource attachments[]) {
244         if (log.isDebugEnabled()) {
245             String JavaDoc msg = "";
246             if (attachments != null) {
247                 msg = " with " + attachments.length + " virtual data source attachments.";
248             }
249
250             log.debug("Queueing notice to user " + uid + " of '" + subject + "'" + msg);
251         }
252
253         EventQueueEntry newEntry = new EventQueueEntry("", message, true);
254         newEntry.setSubject(subject);
255         newEntry.setUid(uid);
256         newEntry.setNotice(true); /*!*/
257         newEntry.setDataContext(dbName);
258         newEntry.setAttachments(attachments);
259         queue.addElement(newEntry);
260         startUp();
261     } /* notify(String, String, String, String, ByteArrayDataSource[]) */
262
263     /**
264      * Main thread process of the EventHandler process
265      */

266     public void run() {
267         super.run();
268         log.info("Event Handler starts");
269         try {
270             while (true) {
271                 if (idleTimes >= maxIdleTimes) {
272                     log.info("Event handler idle more than " + maxIdleTimes +
273                             " times - shutting down");
274                     return;
275                 }
276                 try {
277                     checkQueue();
278                 } catch (DBException ae) {
279                     log.error("Unable to check event queue", ae);
280                 }
281
282                 yield();
283                 sleep(sleepTime * 1000);
284             } /* forever */
285
286         } catch (InterruptedException JavaDoc ie) {
287             log.error("EventHandler was interrupted", ie);
288         }
289     } /* run() */
290
291     /**
292      * Code to start up the event handler, which is normally run on
293      * framework thread.
294      */

295     public synchronized static void startUp() {
296         idleTimes = 0;
297
298         boolean restart = false;
299
300         if (myInstance == null) {
301             restart = true;
302         } else {
303             if (!myInstance.isAlive()) {
304                 restart = true;
305             }
306         }
307         if (restart) {
308             myInstance = new EventHandler();
309             myInstance.start();
310         }
311     } /* startUp() */
312
313 } /* EventHandler */
314
Popular Tags