001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018 package org.apache.geronimo.naming.java; 019 020 import java.util.Collections; 021 022 import javax.naming.Context; 023 import javax.naming.NameNotFoundException; 024 import javax.naming.NamingException; 025 026 import org.apache.xbean.naming.context.ImmutableContext; 027 028 /** 029 * The root context for the java: namespace. 030 * Automatically handles switching the "java:comp" sub-context to the 031 * appropriate one for the current thread. 032 * 033 * @version $Rev: 476049 $ $Date: 2006-11-16 23:35:17 -0500 (Thu, 16 Nov 2006) $ 034 */ 035 public class RootContext extends ImmutableContext { 036 private static InheritableThreadLocal compContext = new InheritableThreadLocal(); 037 038 public RootContext() throws NamingException { 039 super(Collections.EMPTY_MAP); 040 } 041 042 public Object lookup(String name) throws NamingException { 043 if (name.startsWith("java:")) { 044 name = name.substring(5); 045 if (name.length() == 0) { 046 return this; 047 } 048 049 Context compCtx = (Context) compContext.get(); 050 if (compCtx == null) { 051 // the component context was not set for this thread 052 throw new NameNotFoundException(name); 053 } 054 055 if ("comp".equals(name)) { 056 return compCtx; 057 } else if (name.startsWith("comp/")) { 058 return compCtx.lookup(name.substring(5)); 059 } else if ("/comp".equals(name)) { 060 return compCtx; 061 } else if (name.startsWith("/comp/")) { 062 return compCtx.lookup(name.substring(6)); 063 } else { 064 throw new NameNotFoundException("Unrecognized name, does not start with expected 'comp': " + name); 065 } 066 } 067 return super.lookup(name); 068 } 069 070 /** 071 * Set the component context for the current thread. This will be returned 072 * for all lookups of "java:comp" 073 * @param ctx the current components context 074 */ 075 public static void setComponentContext(Context ctx) { 076 compContext.set(ctx); 077 } 078 079 /** 080 * Get the component context for the current thread. 081 * @return the current components context 082 */ 083 public static Context getComponentContext() { 084 return (Context) compContext.get(); 085 } 086 }