View Javadoc

1   /*
2    * Copyright 2006-2008 the original author or authors.
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 org.springframework.osgi.service.importer.support;
18  
19  import org.osgi.framework.BundleContext;
20  
21  /**
22   * Class containing static methods used to obtain information about the current
23   * OSGi service invocation.
24   * 
25   * <p>
26   * The <code>getInvokerBundleContext()</code> method offers access to the
27   * {@link BundleContext} of the entity accessing an OSGi service. The invoked
28   * entity can thus discover information about the caller context.
29   * 
30   * <p>
31   * The functionality in this class might be used by a target object that needed
32   * access to resources on the invocation. However, this approach should not be
33   * used when there is a reasonable alternative, as it makes application code
34   * dependent on usage under AOP and the Spring Dynamic Modules and AOP framework
35   * in particular.
36   * 
37   * @author Andy Piper
38   * @author Costin Leau
39   */
40  public abstract class LocalBundleContext {
41  
42  	/**
43  	 * ThreadLocal holder for the invoker context.
44  	 */
45  	private final static ThreadLocal invokerBundleContext = new InheritableThreadLocal();
46  
47  	/**
48  	 * Try to get the current invoker bundle context. Note that this can be
49  	 * <code>null</code> if the caller is not a Spring-DM importer.
50  	 * 
51  	 * @return the invoker bundle context (can be null)
52  	 */
53  	public static BundleContext getInvokerBundleContext() {
54  		return (BundleContext) invokerBundleContext.get();
55  	}
56  
57  	/**
58  	 * Set the invoker bundle context. Note that callers should take care in
59  	 * cleaning up the thread-local when the invocation ends.
60  	 * 
61  	 * @param bundleContext invoker bundle context
62  	 * @return the old context in case there was one; maybe <code>null</code>
63  	 * is none is set
64  	 */
65  	static BundleContext setInvokerBundleContext(BundleContext bundleContext) {
66  		BundleContext old = (BundleContext) invokerBundleContext.get();
67  		invokerBundleContext.set(bundleContext);
68  		return old;
69  	}
70  
71  }