KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > patterns > backgroundtask > www > BackgroundTaskListener


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: BackgroundTaskListener.java,v 1.9 2007/01/07 06:15:34 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.patterns.backgroundtask.www;
23
24 import java.util.ArrayList JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.Iterator JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.Map JavaDoc;
29 import java.util.Properties JavaDoc;
30 import java.util.Timer JavaDoc;
31 import java.util.logging.Level JavaDoc;
32 import java.util.logging.Logger JavaDoc;
33
34 import javax.servlet.ServletContextEvent JavaDoc;
35 import javax.servlet.ServletContextListener JavaDoc;
36
37 import org.opensubsystems.core.error.OSSException;
38 import org.opensubsystems.core.util.Config;
39 import org.opensubsystems.core.util.DateUtils;
40 import org.opensubsystems.core.util.Log;
41 import org.opensubsystems.patterns.backgroundtask.util.BackgroundTask;
42
43 /**
44  * BackgroundTaskListener is responsible for initialization and starting of tasks
45  * which in background, that is without user interaction, periodically execute
46  * some functionality. This class is useful for starting such tasks in web
47  * environment when the application is running as managed application on the
48  * application server and therefore it's lifecycle is controlled by the
49  * application server.
50  *
51  * @version $Id: BackgroundTaskListener.java,v 1.9 2007/01/07 06:15:34 bastafidli Exp $
52  * @author Miro Halas
53  * @code.reviewer Miro Halas
54  * @code.reviewed 1.6 2006/04/20 13:59:45 bastafidli
55  */

56 public abstract class BackgroundTaskListener implements ServletContextListener JavaDoc
57 {
58    // Attributes ///////////////////////////////////////////////////////////////
59

60    /**
61     * Map with all tasks created by this listener. Key is task name read from
62     * properties, value is BackgroundTask derived object for this name.
63     */

64    protected Map JavaDoc m_tasks;
65    
66    /**
67     * Timer which periodically execute receiver tasks threads. Key is task name,
68     * value is task timer.
69     */

70    protected Map JavaDoc m_tasksTimers;
71
72    // Cached values ////////////////////////////////////////////////////////////
73

74    /**
75     * Logger for this class
76     */

77    private static Logger JavaDoc s_logger = Log.getInstance(BackgroundTaskListener.class);
78
79    // Constructor //////////////////////////////////////////////////////////////
80

81    /**
82     * Creates a new instance of FileProcessorListener
83     */

84    public BackgroundTaskListener()
85    {
86       super();
87    }
88    
89    /**
90     * {@inheritDoc}
91     */

92    public void contextInitialized(
93       ServletContextEvent JavaDoc servletContextEvent
94    )
95    {
96       s_logger.entering(this.getClass().getName(), "contextInitialized");
97       try
98       {
99          BackgroundTask currentTask = null;
100          Timer JavaDoc currentTimer = null;
101          List JavaDoc receiverIDs = new ArrayList JavaDoc();
102          Properties JavaDoc settings;
103          String JavaDoc receiverIdValue;
104          StringBuffer JavaDoc sbTaskIdentifier = new StringBuffer JavaDoc();
105          int iDefaultTaskIdentifierLength;
106            
107          settings = Config.getInstance().getPropertiesSafely();
108       
109          sbTaskIdentifier.append(getBaseProperty());
110          sbTaskIdentifier.append(".");
111          iDefaultTaskIdentifierLength = sbTaskIdentifier.length();
112          for (int id = 0;; id++)
113          {
114             // Remove the previous number
115
sbTaskIdentifier.delete(iDefaultTaskIdentifierLength,
116                                     sbTaskIdentifier.length());
117             sbTaskIdentifier.append(id);
118             // And check if this task exists and if it is enabled or disabled
119
receiverIdValue = settings.getProperty(sbTaskIdentifier.toString(),
120                                                    "id_not_found");
121             // there is not receiver with this id - skip out
122
if (receiverIdValue.equals("id_not_found"))
123             {
124                break;
125             }
126             if (Config.isTrue(receiverIdValue))
127             {
128                // remember this id
129
receiverIDs.add(new Integer JavaDoc(id));
130             }
131          }
132       
133          m_tasks = new HashMap JavaDoc(receiverIDs.size());
134          m_tasksTimers = new HashMap JavaDoc(receiverIDs.size());
135       
136          Iterator JavaDoc tasksIterator = receiverIDs.iterator();
137          Integer JavaDoc taskID;
138          
139          while (tasksIterator.hasNext())
140          {
141             try
142             {
143                taskID = (Integer JavaDoc)tasksIterator.next();
144    
145                currentTask = createTask(taskID.intValue());
146                currentTimer = new Timer JavaDoc(true);
147                m_tasks.put(taskID, currentTask);
148                m_tasksTimers.put(taskID, currentTimer);
149                
150                // this method will start thread every runEveryValue seconds, if
151
// thread is after runEveryValue still running, new thread wil be
152
// not started
153
currentTimer.schedule(
154                      currentTask,
155                      currentTask.getStartDelay() * DateUtils.ONE_SECOND,
156                      (long) (currentTask.getRunEvery() * DateUtils.ONE_SECOND));
157             }
158             catch (Throwable JavaDoc thr)
159             {
160                s_logger.log(Level.SEVERE,
161                                    "Problem while creating background task", thr);
162             }
163          }
164       }
165       // This is here just so we get a log about the exception since the
166
// web server may not print it out
167
catch (Throwable JavaDoc thr)
168       {
169          // No way to throw checked exception so convert it to unchecked
170
s_logger.log(Level.SEVERE, "Unexpected exception.", thr);
171          throw new RuntimeException JavaDoc("Unexpected exception.", thr);
172       }
173       finally
174       {
175          s_logger.exiting(this.getClass().getName(), "contextInitialized");
176       }
177    }
178
179    /**
180     * {@inheritDoc}
181     */

182    public void contextDestroyed(
183        ServletContextEvent JavaDoc servletContextEvent
184    )
185    {
186       s_logger.entering(this.getClass().getName(), "contextDestroyed");
187       try
188       {
189          if (m_tasksTimers != null)
190          {
191             Iterator JavaDoc timersIterator = m_tasksTimers.entrySet().iterator();
192             Timer JavaDoc currentTaskTimer;
193             Integer JavaDoc currentTaskID;
194             BackgroundTask currentTask;
195             Map.Entry JavaDoc currentEntry;
196    
197             while (timersIterator.hasNext())
198             {
199                currentEntry = (Map.Entry JavaDoc)timersIterator.next();
200                currentTaskID = (Integer JavaDoc)currentEntry.getKey();
201                currentTaskTimer = (Timer JavaDoc)currentEntry.getValue();
202                // stop thread
203
currentTaskTimer.cancel();
204                // Cancel task which will logout the user if needed
205
currentTask = (BackgroundTask)m_tasks.get(currentTaskID);
206                currentTask.cancel();
207             }
208          }
209       }
210       finally
211       {
212          s_logger.exiting(this.getClass().getName(), "contextDestroyed");
213       }
214    }
215    
216    /**
217     * Create task with given id. Derived class will implement this by creation
218     * of specific task based on the business logic of the derived class.
219     *
220     * @param iId - id of the task to create
221     * @return BackgroundTask - newly created task
222     * @throws OSSException - error during creation of task
223     */

224    protected abstract BackgroundTask createTask(
225       int iId
226    ) throws OSSException;
227
228    /**
229     * Get base property which will be used to construct identification of the task.
230     * The identification of task will be property.X where X goes sequentially from
231     * 0 to x and can have value 1 for enabled task or 0 for disabled task.
232     *
233     * @return String - name of the base property for task
234     */

235    // TODO: Improve: Implement this method in this class by returnning value
236
// passed into constructor as a new parameter
237
protected abstract String JavaDoc getBaseProperty(
238    );
239 }
240
Popular Tags