• 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 
22 import javax.naming.Context;
23 import javax.naming.NamingException;
24 
25 /**
26  * Integrates Guice with JNDI. Requires a binding to
27  * {@link javax.naming.Context}.
28  *
29  * @author crazybob@google.com (Bob Lee)
30  */
31 public class JndiIntegration {
32 
JndiIntegration()33   private JndiIntegration() {}
34 
35   /**
36    * Creates a provider which looks up objects in JNDI using the given name.
37    * Example usage:
38    *
39    * <pre>
40    * bind(DataSource.class).toProvider(fromJndi(DataSource.class, "java:..."));
41    * </pre>
42    */
fromJndi(Class<T> type, String name)43   public static <T> Provider<T> fromJndi(Class<T> type, String name) {
44     return new JndiProvider<T>(type, name);
45   }
46 
47   static class JndiProvider<T> implements Provider<T> {
48 
49     @Inject Context context;
50     final Class<T> type;
51     final String name;
52 
JndiProvider(Class<T> type, String name)53     public JndiProvider(Class<T> type, String name) {
54       this.type = type;
55       this.name = name;
56     }
57 
get()58     public T get() {
59       try {
60         return type.cast(context.lookup(name));
61       }
62       catch (NamingException e) {
63         throw new RuntimeException(e);
64       }
65     }
66   }
67 }
68