1 22 package org.jboss.injection; 23 24 import java.lang.reflect.Field ; 25 import javax.naming.Context ; 26 import javax.naming.NamingException ; 27 28 import org.jboss.logging.Logger; 29 30 import org.jboss.ejb3.BeanContext; 31 32 38 public class JndiFieldInjector implements Injector, PojoInjector 39 { 40 private static final Logger log = Logger.getLogger(JndiFieldInjector.class); 41 42 private Field field; 43 private String jndiName; 44 private Context ctx; 45 46 public JndiFieldInjector(Field field, String jndiName, Context ctx) 47 { 48 this.field = field; 49 this.field.setAccessible(true); 50 this.jndiName = jndiName; 51 this.ctx = ctx; 52 } 53 54 public JndiFieldInjector(Field field, Context ctx) 55 { 56 this(field, field.getName(), ctx); 57 } 58 59 public void inject(BeanContext bctx) 60 { 61 inject(bctx, bctx.getInstance()); 62 } 63 64 public Class getInjectionClass() 65 { 66 return field.getType(); 67 } 68 69 public Field getField() 70 { 71 return field; 72 } 73 74 protected Object lookup(String jndiName, Class field) 75 { 76 Object dependency = null; 77 78 try 79 { 80 dependency = ctx.lookup(jndiName); 81 } 82 catch (NamingException e) 83 { 84 e.printStackTrace(); 85 throw new RuntimeException ("Unable to inject jndi dependency: " + jndiName + " into field " + field, e); 86 } 87 88 return dependency; 89 } 90 91 public void inject(BeanContext bctx, Object instance) 92 { 93 inject(instance); 94 } 95 96 public void inject(Object instance) 97 { 98 99 Object dependency = lookup(jndiName, field.getType()); 100 102 try 103 { 104 field.set(instance, dependency); 109 } 110 catch (IllegalArgumentException e) 111 { 112 String type = "UNKNOWN"; 113 String interfaces = ""; 114 if (dependency != null) 115 { 116 type = dependency.getClass().getName(); 121 Class [] intfs = dependency.getClass().getInterfaces(); 122 for (Class intf : intfs) interfaces += ", " + intf.getName(); 123 } 124 throw new RuntimeException ("Non matching type for inject of field: " + field + " for type: " + type + " of jndiName " + jndiName + "\nintfs: " + interfaces, e); 125 } 126 catch (IllegalAccessException e) 127 { 128 throw new RuntimeException (e); 129 } 130 } 131 132 public String toString() 133 { 134 return super.toString() + "{field=" + field + ",jndiName=" + jndiName + "}"; 135 } 136 } 137 | Popular Tags |