01: /*
02: * JBoss, Home of Professional Open Source
03: * Copyright 2006, Red Hat Middleware LLC, and individual contributors as indicated
04: * by the @authors tag. See the copyright.txt in the distribution for a
05: * full listing of individual contributors.
06: *
07: * This is free software; you can redistribute it and/or modify it
08: * under the terms of the GNU Lesser General Public License as
09: * published by the Free Software Foundation; either version 2.1 of
10: * the License, or (at your option) any later version.
11: *
12: * This software is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15: * Lesser General Public License for more details.
16: *
17: * You should have received a copy of the GNU Lesser General Public
18: * License along with this software; if not, write to the Free
19: * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20: * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21: */
22: package org.jboss.injection;
23:
24: import javax.naming.Context;
25: import javax.naming.NamingException;
26:
27: import org.jboss.ejb3.BeanContext;
28: import org.jboss.injection.lang.reflect.BeanProperty;
29: import org.jboss.logging.Logger;
30:
31: /**
32: * Injects a jndi dependency into a bean property.
33: *
34: * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
35: * @author <a href="mailto:carlo.dewolf@jboss.com">Carlo de Wolf</a>
36: * @version $Revision: $
37: */
38: public class JndiPropertyInjector extends AbstractPropertyInjector
39: implements PojoInjector {
40: @SuppressWarnings("unused")
41: private static final Logger log = Logger
42: .getLogger(JndiPropertyInjector.class);
43:
44: private String jndiName;
45: private Context ctx;
46:
47: public JndiPropertyInjector(BeanProperty property, String jndiName,
48: Context ctx) {
49: super (property);
50: this .jndiName = jndiName;
51: this .ctx = ctx;
52: }
53:
54: public void inject(BeanContext bctx) {
55: inject(bctx, bctx.getInstance());
56: }
57:
58: public Class<?> getInjectionClass() {
59: return property.getType();
60: }
61:
62: protected Object lookup(String jndiName) {
63: Object dependency = null;
64:
65: try {
66: dependency = ctx.lookup(jndiName);
67: } catch (NamingException e) {
68: Throwable cause = e;
69: while (cause.getCause() != null)
70: cause = cause.getCause();
71: throw new RuntimeException(
72: "Unable to inject jndi dependency: " + jndiName
73: + " into property " + property + ": "
74: + cause.getMessage(), e);
75: }
76: return dependency;
77: }
78:
79: public void inject(BeanContext bctx, Object instance) {
80: inject(instance);
81: }
82:
83: public void inject(Object instance) {
84: Object value = lookup(jndiName);
85: property.set(instance, value);
86: }
87: }
|