• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2006 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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  */
16 
17 package com.google.inject.jndi;
18 
19 import com.google.inject.Inject;
20 import com.google.inject.Provider;
21 import javax.naming.Context;
22 import javax.naming.NamingException;
23 
24 /**
25  * Integrates Guice with JNDI. Requires a binding to {@link javax.naming.Context}.
26  *
27  * @author crazybob@google.com (Bob Lee)
28  */
29 public class JndiIntegration {
30 
JndiIntegration()31   private JndiIntegration() {}
32 
33   /**
34    * Creates a provider which looks up objects in JNDI using the given name. Example usage:
35    *
36    * <pre>
37    * bind(DataSource.class).toProvider(fromJndi(DataSource.class, "java:..."));
38    * </pre>
39    */
fromJndi(Class<T> type, String name)40   public static <T> Provider<T> fromJndi(Class<T> type, String name) {
41     return new JndiProvider<T>(type, name);
42   }
43 
44   static class JndiProvider<T> implements Provider<T> {
45 
46     @Inject Context context;
47     final Class<T> type;
48     final String name;
49 
JndiProvider(Class<T> type, String name)50     public JndiProvider(Class<T> type, String name) {
51       this.type = type;
52       this.name = name;
53     }
54 
55     @Override
get()56     public T get() {
57       try {
58         return type.cast(context.lookup(name));
59       } catch (NamingException e) {
60         throw new RuntimeException(e);
61       }
62     }
63   }
64 }
65