package org.jboss.test.txtimer.ejb;
import org.apache.log4j.Logger;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import java.security.Principal;
import java.io.Serializable;
public class TimerSessionBean
implements SessionBean, TimedObject
{
private static Logger log = Logger.getLogger(TimerSessionBean.class);
private SessionContext context;
private int callCount;
private static int globalCallCount;
private Principal ejbTimeoutCaller;
public void createTimer(long duration, long periode, Serializable info)
{
TimerService timerService = context.getTimerService();
if (periode > 0)
timerService.createTimer(duration, periode, info);
else
timerService.createTimer(duration, info);
}
public void cancelFirstTimer()
{
TimerService timerService = context.getTimerService();
if (timerService.getTimers().isEmpty())
throw new EJBException("There are no timers");
Timer timer = (Timer)timerService.getTimers().iterator().next();
timer.cancel();
}
public Object createTimerReturnHandle(long duration)
{
TimerService timerService = context.getTimerService();
Timer timer = timerService.createTimer(duration, null);
return timer.getHandle();
}
public String passTimerHandle(Object handle)
{
return handle.toString();
}
public void resetCallCount()
{
callCount = 0;
globalCallCount = 0;
}
public int getCallCount()
{
log.info("getCallCount [count=" + callCount + "]");
return callCount;
}
public int getGlobalCallCount()
{
log.info("getGlobalCallCount [count=" + globalCallCount + "]");
return globalCallCount;
}
public List getTimers()
{
TimerService timerService = context.getTimerService();
ArrayList handles = new ArrayList();
Iterator it = timerService.getTimers().iterator();
while (it.hasNext())
{
Timer timer = (Timer) it.next();
handles.add(timer.getHandle().toString());
}
return handles;
}
public Principal getEjbTimeoutCaller()
{
return ejbTimeoutCaller;
}
public void ejbTimeout(Timer timer)
{
callCount++;
globalCallCount++;
log.info("ejbTimeout [count=" + callCount + "] timer=" + timer);
ejbTimeoutCaller = context.getCallerPrincipal();
log.info("ejbTimeout [callerPrincipal=" + ejbTimeoutCaller + "]");
if (timer.getInfo() != null)
{
Properties props = (Properties)timer.getInfo();
if ("true".equals(props.getProperty("cancel")))
timer.cancel();
}
}
public void setSessionContext(SessionContext ctx) throws EJBException, RemoteException
{
this.context = ctx;
}
public void ejbCreate() throws CreateException
{
}
public void ejbRemove() throws EJBException, RemoteException
{
}
public void ejbActivate() throws EJBException, RemoteException
{
}
public void ejbPassivate() throws EJBException, RemoteException
{
}
}