1 /**
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one or more
4 * contributor license agreements. See the NOTICE file distributed with
5 * this work for additional information regarding copyright ownership.
6 * The ASF licenses this file to You under the Apache License, Version 2.0
7 * (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package org.apache.geronimo.naming.java;
20
21 import java.util.Collections;
22
23 import javax.naming.Context;
24 import javax.naming.NameNotFoundException;
25 import javax.naming.NamingException;
26
27 import org.apache.xbean.naming.context.ImmutableContext;
28
29 /**
30 * The root context for the java: namespace.
31 * Automatically handles switching the "java:comp" sub-context to the
32 * appropriate one for the current thread.
33 *
34 * @version $Rev: 470597 $ $Date: 2006-11-02 15:30:55 -0800 (Thu, 02 Nov 2006) $
35 */
36 public class RootContext extends ImmutableContext {
37 private static InheritableThreadLocal compContext = new InheritableThreadLocal();
38
39 public RootContext() throws NamingException {
40 super(Collections.EMPTY_MAP);
41 }
42
43 public Object lookup(String name) throws NamingException {
44 if (name.startsWith("java:")) {
45 name = name.substring(5);
46 if (name.length() == 0) {
47 return this;
48 }
49
50 Context compCtx = (Context) compContext.get();
51 if (compCtx == null) {
52
53 throw new NameNotFoundException(name);
54 }
55
56 if ("comp".equals(name)) {
57 return compCtx;
58 } else if (name.startsWith("comp/")) {
59 return compCtx.lookup(name.substring(5));
60 } else if ("/comp".equals(name)) {
61 return compCtx;
62 } else if (name.startsWith("/comp/")) {
63 return compCtx.lookup(name.substring(6));
64 } else {
65 throw new NameNotFoundException("Unrecognized name, does not start with expected 'comp': " + name);
66 }
67 }
68 return super.lookup(name);
69 }
70
71 /**
72 * Set the component context for the current thread. This will be returned
73 * for all lookups of "java:comp"
74 * @param ctx the current components context
75 */
76 public static void setComponentContext(Context ctx) {
77 compContext.set(ctx);
78 }
79
80 /**
81 * Get the component context for the current thread.
82 * @return the current components context
83 */
84 public static Context getComponentContext() {
85 return (Context) compContext.get();
86 }
87 }