01: /**
02: * Copyright (C) 2006 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */package com.bm.ejb3guice.jndi;
16:
17: import com.bm.ejb3guice.inject.Inject;
18: import com.bm.ejb3guice.inject.Provider;
19:
20: import javax.naming.Context;
21: import javax.naming.NamingException;
22:
23: /**
24: * Integrates Guice with JNDI. Requires a binding to
25: * {@link javax.naming.Context}.
26: *
27: * @author crazybob@google.com (Bob Lee)
28: */
29: public class JndiIntegration {
30:
31: private JndiIntegration() {
32: }
33:
34: /**
35: * Creates a provider which looks up objects in JNDI using the given name.
36: * Example usage:
37: *
38: * <pre>
39: * bind(DataSource.class).toProvider(fromJndi(DataSource.class, "java:..."));
40: * </pre>
41: */
42: public static <T> Provider<T> fromJndi(Class<T> type, String name) {
43: return new JndiProvider<T>(type, name);
44: }
45:
46: static class JndiProvider<T> implements Provider<T> {
47:
48: @Inject
49: Context context;
50: final Class<T> type;
51: final String name;
52:
53: public JndiProvider(Class<T> type, String name) {
54: this .type = type;
55: this .name = name;
56: }
57:
58: public T get() {
59: try {
60: return type.cast(context.lookup(name));
61: } catch (NamingException e) {
62: throw new RuntimeException(e);
63: }
64: }
65: }
66: }
|