package test.compliance.timer;
import java.util.ArrayList;
import java.util.Date;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.timer.Timer;
import javax.management.timer.TimerNotification;
import junit.framework.TestCase;
public class TimerNotificationTestCase
extends TestCase
implements NotificationListener
{
String TIMER_TYPE = "TimerType";
String MESSAGE = "Message";
String USER_DATA = "UserData";
MBeanServer server;
ObjectName timerName;
Timer timer;
Integer id;
ArrayList notifications = new ArrayList();
public TimerNotificationTestCase(String s)
{
super(s);
}
public void testReasonableValues()
{
initTest();
try
{
initTimer();
startTimer();
long startTime = timeOffset(0).getTime();
addNotification(TimerSUITE.ZERO_TIME);
sync();
stopTimer();
long endTime = timeOffset(0).getTime();
assertEquals(1, notifications.size());
TimerNotification tn = (TimerNotification) notifications.get(0);
assertEquals(MESSAGE, tn.getMessage());
assertEquals(1, tn.getSequenceNumber());
assertEquals(timerName, tn.getSource());
assertEquals(TIMER_TYPE, tn.getType());
assertEquals(USER_DATA, tn.getUserData());
assertEquals(id, tn.getNotificationID());
if (tn.getTimeStamp() < startTime + TimerSUITE.ZERO_TIME)
fail("Timer notification before start?");
if (tn.getTimeStamp() > endTime)
fail("Timer notification after end?");
}
finally
{
MBeanServerFactory.releaseMBeanServer(server);
}
}
private void initTest()
{
notifications.clear();
server = MBeanServerFactory.createMBeanServer();
}
private void initTimer()
{
try
{
timer = new Timer();
timerName = new ObjectName("test:type=timer");
server.registerMBean(timer, timerName);
server.addNotificationListener(timerName, this, null, null);
}
catch (Exception e)
{
fail(e.toString());
}
}
private void startTimer()
{
timer.start();
}
private void stopTimer()
{
sleep();
timer.stop();
}
private void addNotification(long offset)
{
id = timer.addNotification(TIMER_TYPE, MESSAGE, USER_DATA,
timeOffset(TimerSUITE.ZERO_TIME));
}
public void handleNotification(Notification n, Object ignored)
{
notifications.add(n);
synchronized(notifications)
{
notifications.notifyAll();
}
}
private void sync()
{
synchronized(notifications)
{
try
{
notifications.wait(TimerSUITE.MAX_WAIT);
}
catch (InterruptedException ignored)
{
}
}
}
private Date timeOffset(long offset)
{
return new Date(System.currentTimeMillis() + offset);
}
private void sleep()
{
sleep(TimerSUITE.ZERO_TIME);
}
private void sleep(long time)
{
try
{
Thread.sleep(time);
}
catch (InterruptedException ignored)
{
}
}
}