/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package test.implementation.notification.support;

import java.util.ArrayList;
import java.util.HashMap;

import javax.management.Notification;
import javax.management.NotificationListener;

/**
 * A listener
 *
 * @author  <a href="mailto:Adrian.Brock@HappeningTimes.com">Adrian Brock</a>.
 */
public class Listener
   implements NotificationListener
{
   // Attributes ----------------------------------------------------------------

   /**
    * The notifications received by handback object
    */
   public HashMap notifications = new HashMap();

   public boolean waiting = false;

   // Constructor ---------------------------------------------------------------

   /**
    * Constructor
    */
   public Listener()
   {
   }

   // Notification Listener Implementation --------------------------------------

   /**
    * Handle the notification
    */
   public void handleNotification(Notification notification, Object handback)
   {
      doWait(true);

      synchronized(notifications)
      {
         ArrayList received = (ArrayList) notifications.get(handback);
         if (received == null)
         {
            received = new ArrayList();
            notifications.put(handback, received);
         }
         received.add(notification);
      }

      doNotify(false);
   }

   public synchronized void doWait(boolean value)
   {
      try
      {
         waiting = value;
         this.wait();
      }
      catch (InterruptedException e)
      {
         throw new RuntimeException(e.toString());
      }
   }

   public synchronized void doNotify(boolean expected)
   {
      try
      {
         while (waiting != expected)
            this.wait(10);
         this.notifyAll();
      }
      catch (InterruptedException e)
      {
         throw new RuntimeException(e.toString());
      }
   }
}
