/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.test.cache.bean;

import org.jboss.aop.Advised;
import org.jboss.cache.aop.TreeCacheAop;
import org.jboss.logging.Logger;
import org.jboss.test.cache.test.standAloneAop.Address;
import org.jboss.test.cache.test.standAloneAop.Person;
import org.jboss.util.NestedRuntimeException;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import java.lang.reflect.Field;
import java.rmi.RemoteException;
import java.util.*;

/**
 * Proxy to the TreeCacheAop MBean.
 * The AOP framework requires that classes are loaded by special classloaders (e.g UCL).
 * This bean is used to execute tests within the server.
 *
 * @author <a href="mailto:harald@gliebe.de">Harald Gliebe</a>
 * @version $Revision: 1.14.4.1 $
 * @ejb.bean type="Stateful"
 * name="test/TreeCacheAopTester"
 * jndi-name="test/TreeCacheAopTester"
 * view-type="remote"
 * @ejb.transaction type="Supports"
 */

public class TreeCacheAopTesterBean implements SessionBean
{

   SessionContext ctx;
   TreeCacheAop cache;
   TreeCacheAop cache2;

   Logger logger_ = Logger.getLogger(TreeCacheAopTesterBean.class);

   public void ejbActivate() throws EJBException, RemoteException
   {
   }

   public void ejbPassivate() throws EJBException, RemoteException
   {
   }

   public void ejbRemove() throws EJBException, RemoteException
   {
   }

   public void setSessionContext(SessionContext ctx) throws EJBException
   {
      this.ctx = ctx;
   }

   /**
    * @ejb.create-method
    */
   public void ejbCreate(String cluster_name, String props, int caching_mode) throws CreateException
   {
      try {
         cache = new TreeCacheAop(cluster_name, props, 10000);
         cache.startService();
         cache2 = new TreeCacheAop(cluster_name, props, 10000);
         cache2.startService();
      } catch (Exception e) {
         throw new CreateException(e.toString());
      }
   }


   /**
    * @ejb.interface-method
    */
   public void testSetup()
   {
      Person p = new Person();
      if (!(p instanceof Advised)) {
         logger_.error("testSetup(): p is not an instance of Advised");
         throw new RuntimeException("Person must be advised!");
      }
      Address a = new Address();
      if (!(a instanceof Advised)) {
         logger_.error("testSetup(): a is not an instance of Advised");
         throw new RuntimeException("Address must be advised!");
      }
   }

   /**
    * @ejb.interface-method
    */
   public void createPerson(String key, String name, int age)
   {
      Person p = new Person();
      p.setName(name);
      p.setAge(age);
      p.setAddress(new Address());
      try {
         cache.putObject(key, p);
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   /**
    * @ejb.interface-method
    */
   public void removePerson(String key)
   {
      try {
         cache.removeObject(key);
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }


   Object getPerson(String key)
   {
      try {
         return (Person) cache.getObject(key);
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }

   /**
    * @ejb.interface-method
    */
   public void setName(String key, String name)
   {
      ((Person) getPerson(key)).setName(name);
   }

   /**
    * @ejb.interface-method
    */
   public String getName(String key)
   {
      return ((Person) getPerson(key)).getName();
   }

   /**
    * @ejb.interface-method
    */
   public void setAge(String key, int age)
   {
      ((Person) getPerson(key)).setAge(age);
   }

   /**
    * @ejb.interface-method
    */
   public int getAge(String key)
   {
      return ((Person) getPerson(key)).getAge();
   }

   /**
    * @ejb.interface-method
    */
   public void setStreet(String key, String street)
   {
      ((Person) getPerson(key)).getAddress().setStreet(street);
   }

   /**
    * @ejb.interface-method
    */
   public String getStreet(String key)
   {
      return ((Person) getPerson(key)).getAddress().getStreet();
   }

   /**
    * @ejb.interface-method
    */
   public void setCity(String key, String city)
   {
      ((Person) getPerson(key)).getAddress().setCity(city);
   }

   /**
    * @ejb.interface-method
    */
   public String getCity(String key)
   {
      return ((Person) getPerson(key)).getAddress().getCity();
   }

   /**
    * @ejb.interface-method
    */
   public void setZip(String key, int zip)
   {
      ((Person) getPerson(key)).getAddress().setZip(zip);
   }

   /**
    * @ejb.interface-method
    */
   public int getZip(String key)
   {
      return ((Person) getPerson(key)).getAddress().getZip();
   }

   // Map operations

   /**
    * @ejb.interface-method
    */
   public Object getHobby(String key, Object hobbyKey)
   {
      Map hobbies = ((Person) getPerson(key)).getHobbies();
      return hobbies == null ? null : hobbies.get(hobbyKey);
   }

   /**
    * @ejb.interface-method
    */
   public void setHobby(String key, Object hobbyKey, Object value)
   {
      Person person = ((Person) getPerson(key));
      Map hobbies = person.getHobbies();
      if (hobbies == null) {
         hobbies = new HashMap();
         person.setHobbies(hobbies);
         // NB: it is neccessary to get hobbies again to get advised version
         hobbies = person.getHobbies();
      }
      hobbies.put(hobbyKey, value);
   }

   // List operations

   /**
    * @ejb.interface-method
    */
   public Object getLanguage(String key, int index)
   {
      List languages = ((Person) getPerson(key)).getLanguages();
      return languages == null ? null : languages.get(index);
   }

   /**
    * @ejb.interface-method
    */
   public void addLanguage(String key, Object language)
   {
      Person person = ((Person) getPerson(key));
      List languages = person.getLanguages();
      if (languages == null) {
         person.setLanguages(new ArrayList());
         languages = person.getLanguages();
      }
      languages.add(language);
   }

   /**
    * @ejb.interface-method
    */
   public void removeLanguage(String key, Object language)
   {
      List languages = ((Person) getPerson(key)).getLanguages();
      if (languages == null) return;
      languages.remove(language);
   }

   /**
    * @ejb.interface-method
    */
   public int getLanguagesSize(String key)
   {
      List languages = ((Person) getPerson(key)).getLanguages();
      return languages == null ? 0 : languages.size();
   }

   /**
    * @ejb.interface-method
    */
   public Set getSkills(String key)
   {
      return new HashSet(((Person) getPerson(key)).getSkills());
   }

   /**
    * @ejb.interface-method
    */
   public void addSkill(String key, String skill)
   {
      Person person = ((Person) getPerson(key));
      Set skills = person.getSkills();
      if (skills == null) {
         person.setSkills(new HashSet());
         skills = person.getSkills();
      }
      skills.add(skill);
   }

   /**
    * @ejb.interface-method
    */
   public void removeSkill(String key, String skill)
   {
      Person person = ((Person) getPerson(key));
      Set skills = person.getSkills();
      if (skills != null) {
         skills.remove(skill);
      }
   }

   /**
    * @ejb.interface-method
    */
   public Object testSerialization()
   {
      try {
         Person p = new Person();
         /*
         if (!(p instanceof Externalizable)) {
        throw new RuntimeException("p not Externalizable");
         }
         */
         p.setName("Harald Gliebe");
         Address address = new Address();
         address.setCity("Mannheim");
         p.setAddress(address);
         cache.putObject("/person/harald", p);
         return (Person) cache.getObject("/person/harald");
      } catch (Throwable t) {
         throw new RuntimeException(t);
      }
   }

   /**
    * @ejb.interface-method
    */
   public void testDeserialization(String key, Object value)
   {
      try {
         cache.putObject(key, value);
      } catch (Throwable t) {
         throw new RuntimeException(t);
      }
   }

   /**
    * @ejb.interface-method
    */
   public void printPerson(String key)
   {
      System.out.println(getPerson(key));
   }

   /**
    * @ejb.interface-method
    */
   public void printCache()
   {
      System.out.println(cache);
   }

   /**
    * @ejb.interface-method
    */
   public Object getFieldValue(String key, String name)
   {
      try {
         Object object = cache.getObject(key);
         Field f = object.getClass().getDeclaredField(name);
         f.setAccessible(true);
         return f.get(object);
      } catch (Exception e) {
         throw new NestedRuntimeException(e);
      }
   }

}