/*
 * 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.naming.Context;
import javax.naming.NamingException;
import org.jboss.ejb3.BeanContext;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.2.2.4 $
 */
public class JndiMethodInjector implements Injector
{
   private Method setMethod;
   private String jndiName;
   private Context ctx;

   public JndiMethodInjector(Method setMethod, String jndiName, Context ctx)
   {
      this.setMethod = setMethod;
      this.jndiName = jndiName;
      this.ctx = ctx;
   }

   public void inject(BeanContext bctx)
   {
      Object dependency = null;
      try
      {
         dependency = ctx.lookup(jndiName);
      }
      catch (NamingException e)
      {
         throw new RuntimeException("Unable to @Inject jndi dependency: " + jndiName + " into method " + setMethod, e);
      }
      Object[] args = {dependency};
      try
      {
         setMethod.invoke(bctx.getInstance(), args);
      }
      catch (IllegalAccessException e)
      {
         throw new RuntimeException(e);  //To change body of catch statement use Options | File Templates.
      }
      catch (IllegalArgumentException e)
      {
         String type = "UNKNOWN";
         if (dependency != null) type = dependency.getClass().getName();
         throw new RuntimeException("Non matching type for @Inject of setter: " + setMethod + " for type: " + type, e);  //To change body of catch statement use Options | File Templates.
      }
      catch (InvocationTargetException e)
      {
         throw new RuntimeException(e.getCause());  //To change body of catch statement use Options | File Templates.
      }
   }
}
