KickJava   Java API By Example, From Geeks To Geeks.

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


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: TimerServiceImpl.java 37858 2005-11-05 17:06:17Z dimitris $
25

26 import java.io.Serializable JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Collection JavaDoc;
29 import java.util.Date JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.Map JavaDoc;
33
34 import javax.ejb.EJBException JavaDoc;
35 import javax.ejb.Timer JavaDoc;
36 import javax.ejb.TimerHandle JavaDoc;
37 import javax.ejb.TimerService JavaDoc;
38 import javax.transaction.SystemException JavaDoc;
39 import javax.transaction.Transaction JavaDoc;
40 import javax.transaction.TransactionManager JavaDoc;
41
42 import org.jboss.logging.Logger;
43
44 /**
45  * The TimerService provides enterprise bean components with access to the
46  * container-provided Timer Service. The EJB Timer Service allows entity beans, stateless
47  * session beans, and message-driven beans to be registered for timer callback events at
48  * a specified time, after a specified elapsed time, or after a specified interval.
49  *
50  * @author Thomas.Diesler@jboss.org
51  * @author Dimitris.Andreadis@jboss.org
52  * @version $Revision: 37858 $
53  * @since 07-Apr-2004
54  */

55 public class TimerServiceImpl implements TimerService JavaDoc
56 {
57    // logging support
58
private static Logger log = Logger.getLogger(TimerServiceImpl.class);
59
60    // The tx manager
61
private TransactionManager JavaDoc transactionManager;
62    // The persistence policy plug-in
63
private PersistencePolicy persistencePolicy;
64    // The timerId generator
65
private TimerIdGenerator timerIdGenerator;
66    // The retry policy
67
private RetryPolicy retryPolicy;
68    
69    // The timed object id
70
private TimedObjectId timedObjectId;
71    // The invoker for the timed object
72
private TimedObjectInvoker timedObjectInvoker;
73
74    // Map<TimerHandleImpl,TimerImpl>
75
private Map JavaDoc timers = new HashMap JavaDoc();
76
77    // Constructors --------------------------------------------------
78

79    /**
80     * CTOR
81     *
82     * All the dependencies are supplied by the caller
83     */

84    public TimerServiceImpl(
85          TimedObjectId timedObjectId, TimedObjectInvoker timedObjectInvoker,
86          TransactionManager JavaDoc transactionManager, PersistencePolicy persistencePolicy,
87          RetryPolicy retryPolicy, TimerIdGenerator timerIdGenerator)
88    {
89       this.timedObjectId = timedObjectId;
90       this.timedObjectInvoker = timedObjectInvoker;
91       this.transactionManager = transactionManager;
92       this.persistencePolicy = persistencePolicy;
93       this.timerIdGenerator = timerIdGenerator;
94       this.retryPolicy = retryPolicy;
95    }
96
97    // Public --------------------------------------------------------
98

99    /**
100     * Get the list of all registerd timers, both active and inactive
101     */

102    public Collection JavaDoc getAllTimers()
103    {
104       synchronized (timers)
105       {
106          return new ArrayList JavaDoc(timers.values());
107       }
108    }
109
110    /**
111     * Get the Timer for the given timedObjectId
112     */

113    public Timer JavaDoc getTimer(TimerHandle JavaDoc handle)
114    {
115       TimerImpl timer = (TimerImpl)timers.get(handle);
116       if (timer != null && timer.isActive())
117          return timer;
118       else
119          return null;
120    }
121    
122    /**
123     * Kill all timers
124     *
125     * @param keepState Whether to maintain or remove timer persistent state
126     */

127    public void shutdown(boolean keepState)
128    {
129       synchronized (timers)
130       {
131          Iterator JavaDoc it = timers.values().iterator();
132          while (it.hasNext())
133          {
134             TimerImpl timer = (TimerImpl)it.next();
135             timer.stopTimer();
136             
137             if (keepState == false)
138                persistencePolicy.deleteTimer(timer.getTimerId(), timer.getTimedObjectId());
139          }
140          timers.clear();
141       }
142    }
143
144    /**
145     * Get the TimedObjectInvoker associated with this TimerService
146     */

147    public TimedObjectInvoker getTimedObjectInvoker()
148    {
149       return timedObjectInvoker;
150    }
151
152    // javax.ejb.TimerService ----------------------------------------
153

154    /**
155     * Create a single-action txtimer that expires after a specified duration.
156     *
157     * @param duration The number of milliseconds that must elapse before the txtimer expires.
158     * @param info Application information to be delivered along with the txtimer expiration
159     * notification. This can be null.
160     * @return The newly created Timer.
161     * @throws IllegalArgumentException If duration is negative
162     * @throws IllegalStateException If this method is invoked while the instance is in
163     * a state that does not allow access to this method.
164     * @throws javax.ejb.EJBException If this method could not complete due to a system-level failure.
165     */

166    public Timer JavaDoc createTimer(long duration, Serializable JavaDoc info) throws IllegalArgumentException JavaDoc, IllegalStateException JavaDoc, EJBException JavaDoc
167    {
168       if (duration < 0)
169          throw new IllegalArgumentException JavaDoc("duration is negative");
170
171       return createTimer(new Date JavaDoc(System.currentTimeMillis() + duration), 0, info);
172    }
173
174    /**
175     * Create an interval txtimer whose first expiration occurs after a specified duration,
176     * and whose subsequent expirations occur after a specified interval.
177     *
178     * @param initialDuration The number of milliseconds that must elapse before the first
179     * txtimer expiration notification.
180     * @param intervalDuration The number of milliseconds that must elapse between txtimer
181     * expiration notifications. Expiration notifications are
182     * scheduled relative to the time of the first expiration. If
183     * expiration is delayed(e.g. due to the interleaving of other
184     * method calls on the bean) two or more expiration notifications
185     * may occur in close succession to "catch up".
186     * @param info Application information to be delivered along with the txtimer expiration
187     * notification. This can be null.
188     * @return The newly created Timer.
189     * @throws IllegalArgumentException If initialDuration is negative, or intervalDuration
190     * is negative.
191     * @throws IllegalStateException If this method is invoked while the instance is in
192     * a state that does not allow access to this method.
193     * @throws javax.ejb.EJBException If this method could not complete due to a system-level failure.
194     */

195    public Timer JavaDoc createTimer(long initialDuration, long intervalDuration, Serializable JavaDoc info) throws IllegalArgumentException JavaDoc, IllegalStateException JavaDoc, EJBException JavaDoc
196    {
197       if (initialDuration < 0)
198          throw new IllegalArgumentException JavaDoc("initial duration is negative");
199       if (intervalDuration < 0)
200          throw new IllegalArgumentException JavaDoc("interval duration is negative");
201
202       return createTimer(new Date JavaDoc(System.currentTimeMillis() + initialDuration), intervalDuration, info);
203    }
204
205    /**
206     * Create a single-action txtimer that expires at a given point in time.
207     *
208     * @param expiration The point in time at which the txtimer must expire.
209     * @param info Application information to be delivered along with the txtimer expiration
210     * notification. This can be null.
211     * @return The newly created Timer.
212     * @throws IllegalArgumentException If expiration is null, or expiration.getTime() is negative.
213     * @throws IllegalStateException If this method is invoked while the instance is in
214     * a state that does not allow access to this method.
215     * @throws javax.ejb.EJBException If this method could not complete due to a system-level failure.
216     */

217    public Timer JavaDoc createTimer(Date JavaDoc expiration, Serializable JavaDoc info) throws IllegalArgumentException JavaDoc, IllegalStateException JavaDoc, EJBException JavaDoc
218    {
219       if (expiration == null)
220          throw new IllegalArgumentException JavaDoc("expiration is null");
221
222       return createTimer(expiration, 0, info);
223    }
224
225    /**
226     * Create an interval txtimer whose first expiration occurs at a given point in time and
227     * whose subsequent expirations occur after a specified interval.
228     *
229     * @param initialExpiration The point in time at which the first txtimer expiration must occur.
230     * @param intervalDuration The number of milliseconds that must elapse between txtimer
231     * expiration notifications. Expiration notifications are
232     * scheduled relative to the time of the first expiration. If
233     * expiration is delayed(e.g. due to the interleaving of other
234     * method calls on the bean) two or more expiration notifications
235     * may occur in close succession to "catch up".
236     * @param info Application information to be delivered along with the txtimer expiration
237     * notification. This can be null.
238     * @return The newly created Timer.
239     * @throws IllegalArgumentException If initialExpiration is null, or initialExpiration.getTime()
240     * is negative, or intervalDuration is negative.
241     * @throws IllegalStateException If this method is invoked while the instance is in
242     * a state that does not allow access to this method.
243     * @throws javax.ejb.EJBException If this method could not complete due to a system-level failure.
244     */

245    public Timer JavaDoc createTimer(Date JavaDoc initialExpiration, long intervalDuration, Serializable JavaDoc info) throws IllegalArgumentException JavaDoc, IllegalStateException JavaDoc, EJBException JavaDoc
246    {
247       if (initialExpiration == null)
248          throw new IllegalArgumentException JavaDoc("initial expiration is null");
249       if (intervalDuration < 0)
250          throw new IllegalArgumentException JavaDoc("interval duration is negative");
251
252       try
253       {
254          String JavaDoc timerId = timerIdGenerator.nextTimerId();
255          TimerImpl timer = new TimerImpl(this, timerId, timedObjectId, timedObjectInvoker, info);
256          persistencePolicy.insertTimer(timerId, timedObjectId, initialExpiration, intervalDuration, info);
257          timer.startTimer(initialExpiration, intervalDuration);
258          return timer;
259       }
260       catch (Exception JavaDoc e)
261       {
262          log.error("Cannot create txtimer", e);
263          return null;
264       }
265    }
266    
267    /**
268     * Get all the active timers associated with this bean.
269     *
270     * @return A collection of javax.ejb.Timer objects.
271     * @throws IllegalStateException If this method is invoked while the instance is in
272     * a state that does not allow access to this method.
273     * @throws javax.ejb.EJBException If this method could not complete due to a system-level failure.
274     */

275    public Collection JavaDoc getTimers() throws IllegalStateException JavaDoc, EJBException JavaDoc
276    {
277       ArrayList JavaDoc activeTimers = new ArrayList JavaDoc();
278       synchronized (timers)
279       {
280          Iterator JavaDoc it = timers.values().iterator();
281          while (it.hasNext())
282          {
283             TimerImpl timer = (TimerImpl)it.next();
284             if (timer.isActive())
285                activeTimers.add(timer);
286          }
287       }
288       return activeTimers;
289    }
290    
291    // Package protected ---------------------------------------------
292

293    /**
294     * Get the current transaction
295     */

296    Transaction JavaDoc getTransaction()
297    {
298       try
299       {
300          return transactionManager.getTransaction();
301       }
302       catch (SystemException JavaDoc e)
303       {
304          return null;
305       }
306    }
307
308    /**
309     * Add a txtimer to the list of active timers
310     */

311    void addTimer(TimerImpl txtimer)
312    {
313       synchronized (timers)
314       {
315          TimerHandle JavaDoc handle = new TimerHandleImpl(txtimer);
316          timers.put(handle, txtimer);
317       }
318    }
319
320    /**
321     * Remove a txtimer from the list of active timers
322     */

323    void removeTimer(TimerImpl txtimer)
324    {
325       synchronized (timers)
326       {
327          persistencePolicy.deleteTimer(txtimer.getTimerId(), txtimer.getTimedObjectId());
328          timers.remove(new TimerHandleImpl(txtimer));
329       }
330    }
331    
332    void retryTimeout(TimerImpl txtimer)
333    {
334       try
335       {
336          retryPolicy.retryTimeout(timedObjectInvoker, txtimer);
337       }
338       catch (Exception JavaDoc e)
339       {
340          log.error("Retry timeout failed for timer: " + txtimer, e);
341       }
342    }
343 }
344
Popular Tags