KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > timer > ejb > TimerSLSBean


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.test.timer.ejb;
23
24 import java.util.Date JavaDoc;
25 import java.util.HashMap JavaDoc;
26 import java.util.Map JavaDoc;
27 import java.util.List JavaDoc;
28 import java.io.*;
29
30 import javax.ejb.SessionBean JavaDoc;
31 import javax.ejb.SessionContext JavaDoc;
32 import javax.ejb.TimedObject JavaDoc;
33 import javax.ejb.Timer JavaDoc;
34 import javax.ejb.TimerHandle JavaDoc;
35 import javax.ejb.TimerService JavaDoc;
36 import javax.ejb.EJBException JavaDoc;
37 import javax.ejb.NoSuchObjectLocalException JavaDoc;
38 import javax.management.MBeanServerFactory JavaDoc;
39 import javax.management.MBeanServer JavaDoc;
40
41 import org.jboss.logging.Logger;
42 import org.jboss.test.timer.interfaces.TimerSLSB;
43 import org.jboss.ejb.txtimer.FixedDelayRetryPolicyMBean;
44
45 /**
46  * Stateless Session Bean Timer Test
47  *
48  * @ejb:bean name="test/timer/TimerSLSB"
49  * display-name="Timer in Stateless Session Bean"
50  * type="Stateless"
51  * transaction-type="Container"
52  * view-type="remote"
53  * jndi-name="ejb/test/timer/TimerSLSB"
54  *
55  * @ejb:transaction type="Required"
56  * @author Thomas Diesler
57  * @author Scott.Stark@jboss.org
58  * @version $Revision: 58115 $
59  **/

60 public class TimerSLSBean
61    implements SessionBean JavaDoc, TimedObject JavaDoc
62 {
63    // -------------------------------------------------------------------------
64
// Static
65
// -------------------------------------------------------------------------
66
private static HashMap JavaDoc timeoutCounts = new HashMap JavaDoc();
67    private static Logger log = Logger.getLogger(TimerSLSBean.class);
68
69    // -------------------------------------------------------------------------
70
// Members
71
// -------------------------------------------------------------------------
72
private SessionContext JavaDoc context;
73
74    // -------------------------------------------------------------------------
75
// Methods
76
// -------------------------------------------------------------------------
77

78   /**
79     * Start a single timer (if not already set) with the start date plus the period
80     * Uses the string "TimerSLSBean.startSingleTimer" as the timer info data.
81     *
82     * @param pPeriod Time that will elapse between now and the timed event in milliseconds
83     *
84     * @ejb:interface-method view-type="remote"
85     **/

86    public byte[] startSingleTimer(long pPeriod)
87    {
88       return startSingleTimer(pPeriod,"TimerSLSBean.startSingleTimer");
89    }
90
91     /**
92     * Start a single timer (if not already set) with the start date plus the period and specified info.
93     *
94     * @param pPeriod Time that will elapse between now and the timed event in milliseconds
95     * @param info an object to be used as the info for the timer.
96     *
97     * @ejb:interface-method view-type="remote"
98     **/

99    public byte[] startSingleTimer(long pPeriod, Serializable info)
100    {
101       log.info("TimerSLSBean.startSingleTimer(), try to get a Timer Service from the Session Context");
102       TimerService JavaDoc ts = context.getTimerService();
103       long exp = System.currentTimeMillis() + pPeriod;
104       Timer JavaDoc timer = ts.createTimer(new Date JavaDoc(exp), info);
105       log.info("TimerSLSBean.startSingleTimer(), create a timer: "+timer);
106       byte[] handle = getHandle(timer);
107       return handle;
108    }
109
110    /**
111     * Start a timer (if not already set) with the start date plus the period
112     * and an interval of the given period
113     * Uses the string "TimerSLSBean.startTimer" as the timer info data.
114     *
115     * @param pPeriod Time that will elapse between two events in milliseconds
116     *
117     * @ejb:interface-method view-type="remote"
118     **/

119    public byte[] startTimer(long pPeriod)
120    {
121       return startTimer(pPeriod, "TimerSLSBean.startTimer");
122    }
123
124      /**
125     * Start a timer (if not already set) with the start date plus the period
126     * and an interval of the given period
127     *
128     * @param pPeriod Time that will elapse between two events in milliseconds
129     * @param info an object to be used as the info for the timer.
130     *
131     * @ejb:interface-method view-type="remote"
132     **/

133    public byte[] startTimer(long pPeriod, Serializable info)
134    {
135       log.info("TimerSLSBean.startTimer(), try to get a Timer Service from the Session Context");
136       TimerService JavaDoc ts = context.getTimerService();
137       long exp = System.currentTimeMillis() + pPeriod;
138       Timer JavaDoc timer = ts.createTimer(new Date JavaDoc(exp), pPeriod, info);
139       log.info("TimerSLSBean.startTimer(), create a timer: "+timer);
140       byte[] handle = getHandle(timer);
141       return handle;
142    }
143
144    /**
145     * @ejb:interface-method view-type="remote"
146     **/

147    public void stopTimer(byte[] handle)
148    {
149       Timer JavaDoc timer = getTimer(handle);
150       timer.cancel();
151       log.info("TimerSLSBean.stopTimer(), create a timer: "+timer);
152       synchronized( TimerSLSBean.class )
153       {
154          Long JavaDoc key = getKey(handle);
155          timeoutCounts.remove(key);
156       }
157    }
158
159    /**
160     * @ejb:interface-method view-type="remote"
161     **/

162    public int getTimeoutCount(byte[] handle)
163    {
164       Integer JavaDoc count = null;
165       try
166       {
167          Long JavaDoc key = getKey(handle);
168          count = (Integer JavaDoc) timeoutCounts.get(key);
169       }
170       catch(NoSuchObjectLocalException JavaDoc e)
171       {
172          // Expected if the timer has been stopped
173
}
174       log.info("TimerSLSBean.getTimeoutCount(): " + count);
175       return count != null ? count.intValue() : 0;
176    }
177
178    /**
179     * @return Date of the next timed event
180     *
181     * @ejb:interface-method view-type="remote"
182     **/

183    public Date JavaDoc getNextTimeout(byte[] handle)
184    {
185       Timer JavaDoc timer = getTimer(handle);
186       return timer.getNextTimeout();
187    }
188
189    /**
190     * @return Time remaining until next timed event in milliseconds
191     *
192     * @ejb:interface-method view-type="remote"
193     **/

194    public long getTimeRemaining(byte[] handle)
195    {
196       Timer JavaDoc timer = getTimer(handle);
197       return timer.getTimeRemaining();
198    }
199
200    /**
201     * @return User object of the timer
202     *
203     * @ejb:interface-method view-type="remote"
204     **/

205    public Object JavaDoc getInfo(byte[] handle)
206    {
207       Timer JavaDoc timer = getTimer(handle);
208       return timer.getInfo();
209    }
210
211    /**
212     * Create the Session Bean
213     *
214     * @ejb:create-method view-type="both"
215     **/

216    public void ejbCreate()
217    {
218       log.info("TimerSLSBean.ejbCreate()");
219    }
220
221    public void ejbTimeout(Timer JavaDoc timer)
222    {
223       Integer JavaDoc count = null;
224       Long JavaDoc key = null;
225       synchronized( TimerSLSBean.class )
226       {
227          log.debug("ejbTimeout(): Timer State:" + timer);
228          byte[] handle = getHandle(timer);
229          key = getKey(handle);
230          count = (Integer JavaDoc) timeoutCounts.get(key);
231          if( count == null )
232             count = new Integer JavaDoc(1);
233          else
234             count = new Integer JavaDoc(1 + count.intValue());
235          timeoutCounts.put(key, count);
236          log.info("ejbTimeout(): count for timer handle " + key + " is " + count);
237       }
238
239       log.info("ejbTimeout(), timer: " + timer+", key: "+key+", count: "+count);
240
241       Object JavaDoc info = timer.getInfo();
242       if(info instanceof Map JavaDoc) {
243          Map JavaDoc mInfo = ((Map JavaDoc)info);
244          Integer JavaDoc failCount = (Integer JavaDoc) mInfo.get(TimerSLSB.INFO_EXEC_FAIL_COUNT);
245          Integer JavaDoc taskTime = (Integer JavaDoc) mInfo.get(TimerSLSB.INFO_TASK_RUNTIME);
246
247          // If the timer is supposed to fail (testing the retry mechanism)
248
// then we simply rollback the trans. Note this will still increase
249
// the timeoutCounts which is what we want.
250
if(failCount != null && count.compareTo(failCount) <= 0) {
251             log.info("ejbTimeout(): Failing timeout because '" + TimerSLSB.INFO_EXEC_FAIL_COUNT
252                   + "' is set to " + failCount + " and count is " + count);
253             context.setRollbackOnly();
254             return;
255          }
256
257          // Make method simulate a long running task
258
// This is used to test the case in JBAS-1926
259
if(taskTime != null) {
260             try
261             {
262                log.info("ejbTimeout(): Simulating long task ("+ taskTime +"ms)");
263                Thread.sleep(taskTime.intValue());
264             }
265             catch (InterruptedException JavaDoc e) {}
266          }
267       }
268    }
269
270    /**
271     * Describes the instance and its content for debugging purpose
272     *
273     * @return Debugging information about the instance and its content
274     **/

275    public String JavaDoc toString()
276    {
277       return "TimerSLSBean [ " + " ]";
278    }
279
280    // -------------------------------------------------------------------------
281
// Framework Callbacks
282
// -------------------------------------------------------------------------
283

284    public void setSessionContext(SessionContext JavaDoc aContext)
285    {
286       context = aContext;
287    }
288
289    public void ejbActivate()
290    {
291    }
292
293    public void ejbPassivate()
294    {
295    }
296
297    public void ejbRemove()
298    {
299    }
300
301    private Long JavaDoc getKey(byte[] handle)
302    {
303       long key = 0;
304       for(int n = 0; n < handle.length; n ++)
305          key += handle[n];
306       log.info("HandleKey: "+key);
307       return new Long JavaDoc(key);
308    }
309    private byte[] getHandle(Timer JavaDoc timer)
310       throws EJBException JavaDoc
311    {
312       try
313       {
314          ByteArrayOutputStream baos = new ByteArrayOutputStream();
315          ObjectOutputStream oos = new ObjectOutputStream(baos);
316          oos.writeObject(timer.getHandle());
317          oos.close();
318          byte[] handle = baos.toByteArray();
319          return handle;
320       }
321       catch (Exception JavaDoc e)
322       {
323          throw new EJBException JavaDoc("Failed to get timer from handle", e);
324       }
325    }
326    private Timer JavaDoc getTimer(byte[] handle)
327       throws NoSuchObjectLocalException JavaDoc, EJBException JavaDoc
328    {
329       try
330       {
331          ByteArrayInputStream bais = new ByteArrayInputStream(handle);
332          ObjectInputStream ois = new ObjectInputStream(bais);
333          TimerHandle JavaDoc th = null;
334          th = (TimerHandle JavaDoc) ois.readObject();
335          ois.close();
336          Timer JavaDoc timer = th.getTimer();
337          return timer;
338       }
339       catch(NoSuchObjectLocalException JavaDoc e)
340       {
341          throw e;
342       }
343       catch (Exception JavaDoc e)
344       {
345          throw new EJBException JavaDoc("Failed to get timer from handle", e);
346       }
347    }
348
349    /**
350     * Returns the value from the RetryPolicyMBean. This is used by unit tests to help determine timing
351     * for some of the tests, specifically, those that test the fix for JBAS-1926.
352     */

353    public long getRetryTimeoutPeriod() {
354       List JavaDoc lServers = MBeanServerFactory.findMBeanServer( null );
355       MBeanServer JavaDoc lServer = (MBeanServer JavaDoc) lServers.get( 0 );
356       try
357       {
358          Long JavaDoc val = (Long JavaDoc) lServer.getAttribute(FixedDelayRetryPolicyMBean.OBJECT_NAME, "Delay");
359          return val.longValue();
360       }
361       catch (Exception JavaDoc e)
362       {
363          log.error(e);
364          e.printStackTrace();
365
366          return -1;
367       }
368    }
369 }
370
Popular Tags