package org.jboss.cache;

import java.util.List;

import junit.framework.TestCase;

public class ViewManagementTest extends TestCase
{
   private TreeCache cache1;
   private TreeCache cache2;
   
   protected void setUp() throws Exception
   {
      super.setUp();
      PropertyConfigurator conf = new PropertyConfigurator();
      
      cache1 = new TreeCache();
      cache2 = new TreeCache();
      
      conf.configure(cache1, "META-INF/replSync-service.xml");
      conf.configure(cache2, "META-INF/replSync-service.xml");
   }

   protected void tearDown() throws Exception
   {
      super.tearDown();
      
      if (cache1 != null)
      {
         try
         {
            cache1.stopService();
         }
         catch (Exception e) {}
      }
      
      if (cache2 != null)
      {
         try
         {
            cache2.stopService();
         }
         catch (Exception e) {}
      }
   }

   public void testGetMembers() throws Exception
   {
      cache1.startService();
      Thread.sleep(500);
      List memb1 = cache1.getMembers();
      assertEquals("View has one member", 1, memb1.size());
      
      Object coord = memb1.get(0);
      
      cache2.startService();
      Thread.sleep(500);
      memb1 = cache1.getMembers();      
      List memb2 = cache2.getMembers();
      assertEquals("View has two members", 2, memb1.size());
      assertEquals("Both caches have same view", memb1, memb2);
      
      cache1.stopService();
      Thread.sleep(500);
      memb2 = cache2.getMembers();
      assertEquals("View has one member", 1, memb2.size());
      assertFalse("Coordinator changed", coord.equals(memb2.get(0)));
   }
   
   public void testIsCoordinator() throws Exception
   {      
      cache1.startService();
      assertTrue("Cache1 is coordinator", cache1.isCoordinator());
      
      cache2.startService();
      assertTrue("Cache1 is still coordinator", cache1.isCoordinator());
      assertFalse("Cache2 is not coordinator", cache2.isCoordinator());
      
      cache1.stopService();
      assertTrue("Cache2 is coordinator", cache2.isCoordinator());
      
   }

}
