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.google.inject.example;
16:
17: import com.google.inject.Inject;
18: import com.google.inject.Provider;
19: import javax.naming.Context;
20: import javax.naming.NamingException;
21:
22: class JndiProvider<T> implements Provider<T> {
23:
24: @Inject
25: Context context;
26: final String name;
27: final Class<T> type;
28:
29: JndiProvider(Class<T> type, String name) {
30: this .name = name;
31: this .type = type;
32: }
33:
34: public T get() {
35: try {
36: return type.cast(context.lookup(name));
37: } catch (NamingException e) {
38: throw new RuntimeException(e);
39: }
40: }
41:
42: /**
43: * Creates a JNDI provider for the given
44: * type and name.
45: */
46: static <T> Provider<T> fromJndi(Class<T> type, String name) {
47: return new JndiProvider<T>(type, name);
48: }
49: }
|