KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > ejb > txtimer > DatabasePersistencePolicy


1 /*
2  * JBoss, Home of Professional Open Source
3  * Copyright 2005, JBoss Inc., and individual contributors as indicated
4  * by the @authors tag. See the copyright.txt in the distribution for a
5  * full listing of individual contributors.
6  *
7  * This is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as
9  * published by the Free Software Foundation; either version 2.1 of
10  * the License, or (at your option) any later version.
11  *
12  * This software 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 GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this software; if not, write to the Free
19  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21  */

22 package org.jboss.ejb.txtimer;
23
24 // $Id: DatabasePersistencePolicy.java 45421 2006-06-01 10:19:34Z adrian $
25

26 import java.io.Serializable JavaDoc;
27 import java.sql.SQLException JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Date JavaDoc;
30 import java.util.List JavaDoc;
31
32 import javax.ejb.TimerService JavaDoc;
33 import javax.management.ObjectName JavaDoc;
34 import javax.transaction.SystemException JavaDoc;
35 import javax.transaction.Transaction JavaDoc;
36 import javax.transaction.TransactionManager JavaDoc;
37
38 import org.jboss.ejb.ContainerMBean;
39 import org.jboss.logging.Logger;
40 import org.jboss.mx.util.MBeanProxyExt;
41 import org.jboss.system.ServiceMBeanSupport;
42 import org.jboss.tm.TransactionManagerLocator;
43
44 /**
45  * This service implements a PersistencePolicy that persistes the timer to a
46  * database.
47  *
48  * @author Thomas.Diesler@jboss.org
49  * @author Scott.Stark@jboss.org
50  * @author Dimitris.Andreadis@jboss.org
51  * @version $Revision: 45421 $
52  * @since 09-Sep-2004
53  */

54 public class DatabasePersistencePolicy extends ServiceMBeanSupport
55    implements DatabasePersistencePolicyMBean
56 {
57    // logging support
58
private static Logger log = Logger.getLogger(DatabasePersistencePolicy.class);
59
60    // The persistence plugin
61
private DatabasePersistencePlugin dbpPlugin;
62
63    // The service attributes
64
private ObjectName JavaDoc dataSource;
65    private String JavaDoc dbpPluginClassName;
66
67    // The transaction manager, to suspend the current Tx during delete
68
private TransactionManager JavaDoc tm;
69    
70    // The persisted timers seen on startup
71
private List JavaDoc timersToRestore;
72
73    /**
74     * Initializes this service.
75     */

76    public void startService() throws Exception JavaDoc
77    {
78       tm = TransactionManagerLocator.getInstance().locate();
79
80       // Get the persistence plugin
81
if (dbpPluginClassName != null)
82       {
83          Class JavaDoc dbpPolicyClass = Thread.currentThread().getContextClassLoader().loadClass(dbpPluginClassName);
84          dbpPlugin = (DatabasePersistencePlugin)dbpPolicyClass.newInstance();
85       }
86       else
87       {
88          dbpPlugin = new GeneralPurposeDatabasePersistencePlugin();
89       }
90
91       // init the plugin
92
dbpPlugin.init(server, dataSource);
93
94       // create the table if needed
95
dbpPlugin.createTableIfNotExists();
96    }
97
98    /**
99     * Creates the timer in persistent storage.
100     *
101     * @param timerId The timer id
102     * @param timedObjectId The timed object id
103     * @param firstEvent The point in time at which the first txtimer expiration must occur.
104     * @param intervalDuration The number of milliseconds that must elapse between txtimer expiration notifications.
105     * @param info A serializable handback object.
106     */

107    public void insertTimer(String JavaDoc timerId, TimedObjectId timedObjectId, Date JavaDoc firstEvent, long intervalDuration, Serializable JavaDoc info)
108    {
109       try
110       {
111          dbpPlugin.insertTimer(timerId, timedObjectId, firstEvent, intervalDuration, info);
112       }
113       catch (SQLException JavaDoc e)
114       {
115          RuntimeException JavaDoc ex = new IllegalStateException JavaDoc("Unable to persist timer");
116          ex.initCause(e);
117          throw ex;
118       }
119    }
120
121    /**
122     * Removes the timer from persistent storage.
123     *
124     * @param timerId The timer id
125     */

126    public void deleteTimer(String JavaDoc timerId, TimedObjectId timedObjectId)
127    {
128       // suspend the Tx before we get the con, because you cannot get a connection on an already commited Tx
129
Transaction JavaDoc threadTx = suspendTransaction();
130
131       try
132       {
133          dbpPlugin.deleteTimer(timerId, timedObjectId);
134       }
135       catch (SQLException JavaDoc e)
136       {
137          log.warn("Unable to delete timer", e);
138       }
139       finally
140       {
141          // resume the Tx
142
resumeTransaction(threadTx);
143       }
144    }
145
146    /**
147     * List the persisted timer handles for a particular container
148     *
149     * @param containerId The Container ObjectName
150     * @param loader The ClassLoader to use for loading the handles
151     * @return a list of TimerHandleImpl objects
152     */

153    public List JavaDoc listTimerHandles(ObjectName JavaDoc containerId, ClassLoader JavaDoc loader)
154    {
155       List JavaDoc list = new ArrayList JavaDoc();
156
157       ClassLoader JavaDoc oldCl = Thread.currentThread().getContextClassLoader();
158       try
159       {
160          if (loader != null)
161          {
162             Thread.currentThread().setContextClassLoader(loader);
163          }
164          list.addAll(dbpPlugin.selectTimers(containerId));
165       }
166       catch (SQLException JavaDoc e)
167       {
168          log.warn("Unable to get timer handles for containerId: " + containerId, e);
169       }
170       finally
171       {
172          // restore class loader
173
Thread.currentThread().setContextClassLoader(oldCl);
174       }
175       return list;
176    }
177    
178    /**
179     * Return a List of TimerHandle objects.
180     */

181    public List JavaDoc listTimerHandles()
182    {
183       List JavaDoc list = new ArrayList JavaDoc();
184       try
185       {
186          list.addAll(dbpPlugin.selectTimers(null));
187       }
188       catch (SQLException JavaDoc e)
189       {
190          log.warn("Unable to get timer handles", e);
191       }
192       return list;
193    }
194    
195    /**
196     * Restore the persistent timers seen during service startup
197     */

198    public void restoreTimers()
199    {
200       if (timersToRestore != null && timersToRestore.size() > 0)
201       {
202          log.debug("Restoring " + timersToRestore.size() + " timer(s)");
203
204          // recreate the timers
205
for (int i = 0; i < timersToRestore.size(); i++)
206          {
207             TimerHandleImpl handle = (TimerHandleImpl)timersToRestore.get(i);
208
209             try
210             {
211                TimedObjectId targetId = handle.getTimedObjectId();
212                ObjectName JavaDoc containerName = targetId.getContainerId();
213                ContainerMBean container = (ContainerMBean)MBeanProxyExt.create(ContainerMBean.class, containerName, server);
214                TimerService JavaDoc timerService = container.getTimerService(targetId.getInstancePk());
215                timerService.createTimer(handle.getFirstTime(), handle.getPeriode(), handle.getInfo());
216             }
217             catch (Exception JavaDoc e)
218             {
219                log.warn("Unable to restore timer record: " + handle);
220             }
221          }
222          timersToRestore.clear();
223       }
224    }
225
226    /**
227     * Delete all persisted timers
228     */

229    public void clearTimers()
230    {
231       try
232       {
233          dbpPlugin.clearTimers();
234       }
235       catch (SQLException JavaDoc e)
236       {
237          log.warn("Unable to clear timers", e);
238       }
239    }
240
241    /** Re-read the current persistent timers list, clear the db of timers,
242     * and restore the timers.
243     *
244     * @jmx.managed-operation
245     */

246    public void resetAndRestoreTimers() throws SQLException JavaDoc
247    {
248       timersToRestore = dbpPlugin.selectTimers(null);
249       log.debug("Found " + timersToRestore.size() + " timer(s)");
250       if (timersToRestore.size() > 0)
251       {
252          // delete all timers
253
clearTimers();
254       }
255       restoreTimers();
256    }
257
258    // MBean attributes *************************************************************************************************\
259

260    /**
261     * @jmx.managed-attribute
262     */

263    public ObjectName JavaDoc getDataSource()
264    {
265       return dataSource;
266    }
267
268    /**
269     * @jmx.managed-attribute
270     */

271    public void setDataSource(ObjectName JavaDoc dataSource)
272    {
273       this.dataSource = dataSource;
274    }
275
276    /**
277     * @jmx.managed-attribute
278     */

279    public String JavaDoc getDatabasePersistencePlugin()
280    {
281       return dbpPluginClassName;
282    }
283
284    /**
285     * @jmx.managed-attribute
286     */

287    public void setDatabasePersistencePlugin(String JavaDoc dbpPluginClass)
288    {
289       this.dbpPluginClassName = dbpPluginClass;
290    }
291    // private **********************************************************************************************************
292

293    private Transaction JavaDoc suspendTransaction()
294    {
295       Transaction JavaDoc threadTx = null;
296       try
297       {
298          threadTx = tm.suspend();
299       }
300       catch (SystemException JavaDoc e)
301       {
302          log.warn("Cannot suspend Tx: " + e.toString());
303       }
304       return threadTx;
305    }
306
307    private void resumeTransaction(Transaction JavaDoc threadTx)
308    {
309       try
310       {
311          if (threadTx != null)
312             tm.resume(threadTx);
313       }
314       catch (Exception JavaDoc e)
315       {
316          log.warn("Cannot resume Tx: " + e.toString());
317       }
318    }
319 }
320
321
Popular Tags