/*
 * 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.Field;
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.4.2.5 $
 */
public class EntityManagerFieldInjector extends EntityManagerInjector
{
   protected Field field;

   public EntityManagerFieldInjector(Field field, Container container, ManagedEntityManagerFactory factory, PersistenceContextType type)
   {
      super(container, factory, type);
      this.field = field;
      this.field.setAccessible(true);
   }

   public void inject(BeanContext ctx)
   {
      try
      {
         Object entityManager = null;
         boolean isTransient = ((EJBContainer) container).resolveAnnotation(field, Transient.class) != null;
         entityManager = getEntityManager(ctx, isTransient, field.getType());
         field.set(ctx.getInstance(), entityManager);
      }
      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 field: " + field.toString());
      }
   }

}
