/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.test.cluster.drm;

import java.io.Serializable;
import java.util.List;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.naming.InitialContext;

import org.jboss.ha.framework.interfaces.DistributedReplicantManager;
import org.jboss.ha.framework.interfaces.DistributedReplicantManager.ReplicantListener;
import org.jboss.ha.framework.interfaces.HAPartition;
import org.jboss.logging.Logger;

/** Tests of the DistributedReplicantManager aspect of the HAPartition service.

   @author Scott.Stark@jboss.org
   @version $Revision: 1.1 $
*/
public class DRMUser extends NotificationBroadcasterSupport
   implements IReplicants, ReplicantListener
{
   protected static Logger log = Logger.getLogger(DRMUser.class);

   protected DistributedReplicantManager drm;
   protected String category = "DRMUser";
   protected String partitionName = "DefaultPartition";
   protected long sequence;

   public String getPartitionName()
   {
      return partitionName;
   }
   public void setPartitionName(String partitionName)
   {
      this.partitionName = partitionName;
   }

   public String getCategory()
   {
      return category;
   }
   public void setCategory(String category)
   {
      this.category = category;
   }

   public void start() throws Exception
   {
      // Lookup the parition
      InitialContext ctx = new InitialContext();
      String jndiName = "/HAPartition/" + partitionName;
      HAPartition partition = (HAPartition) ctx.lookup(jndiName);
      drm = partition.getDistributedReplicantManager();
      log.debug("Obtained DistributedReplicantManager from partition="+partitionName);
      drm.registerListener(category, this);
      // Bind the jboss.bind.address value into the DRM
      String address = System.getProperty("jboss.bind.address");
      drm.add(category, address);
   }
   public void stop() throws Exception
   {
      drm.remove(category);
      drm.unregisterListener(category, this);
   }

   public Serializable lookupLocalReplicant()
   {
      return drm.lookupLocalReplicant(category);
   }
   public List lookupLocalReplicants()
   {
      return drm.lookupReplicants(category);
   }
   private synchronized long nextSequence()
   {
      return sequence ++;
   }

   public void replicantsChanged(String key, List newReplicants, int newReplicantsViewId)
   {
      NotifyData data = new NotifyData();
      data.key = key;
      data.newReplicants = newReplicants;
      data.newReplicantsViewId = newReplicantsViewId;
      String address = System.getProperty("jboss.bind.address");
      long id = nextSequence();
      Notification msg = new Notification("replicantsChanged", this, id, address);
      msg.setUserData(data);
      log.debug("replicantsChanged, "+msg);
      super.sendNotification(msg);
   }
}
