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

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.persistence.PersistenceContextType;
import javax.persistence.Transient;
import org.jboss.ejb3.BeanContext;
import org.jboss.ejb3.Container;
import org.jboss.ejb3.EJBContainer;
import org.jboss.ejb3.entity.ManagedEntityManagerFactory;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.3.2.5 $
 */
public class EntityManagerMethodInjector extends EntityManagerInjector
{
   private Method setMethod;

   public EntityManagerMethodInjector(Method setMethod, Container container, ManagedEntityManagerFactory factory, PersistenceContextType type)
   {
      super(container, factory, type);
      this.setMethod = setMethod;
   }

   public void inject(BeanContext ctx)
   {
      try
      {
         boolean isTransient = ((EJBContainer) container).resolveAnnotation(setMethod, Transient.class) != null;
         Object entityManager = getEntityManager(ctx, isTransient, setMethod.getParameterTypes()[0]);
         Object[] args = {entityManager};
         setMethod.invoke(ctx.getInstance(), args);
      }
      catch (IllegalAccessException e)
      {
         throw new RuntimeException(e);  //To change body of catch statement use Options | File Templates.
      }
      catch (IllegalArgumentException e)
      {
         throw new RuntimeException("Failed in setting EntityManager on setter method: " + setMethod.toString());
      }
      catch (InvocationTargetException e)
      {
         throw new RuntimeException(e.getCause());  //To change body of catch statement use Options | File Templates.
      }
   }
}
