View Javadoc
1   /**
2    * Copyright By Grandsoft Company Limited.  
3    * 2012-8-23 下午04:16:04
4    */
5   package gboat2.web.util;
6   
7   import gboat2.web.Activator;
8   
9   import java.net.URL;
10  
11  import org.osgi.framework.Bundle;
12  import org.osgi.framework.BundleContext;
13  
14  /**
15   * 
16   * 获取bundle的工具类
17   * @author tanxw
18   * @since jdk1.6
19   * @date 2012-8-23
20   *  
21   */
22  
23  public abstract class BundleUtil {
24  	
25  	private static BundleContext context = null;
26  	
27  	//private static Map<String, Bundle> bundlesMap = null;
28  	
29  	//private static byte[] lock = new byte[0]; // 特殊的instance变量
30  	
31  	private static BundleContext getBundleContext() {
32  		if (null == context) {
33  			context = Activator.LOCAL_BUNDLE.getBundleContext();
34  		}
35  		return context;
36  	}
37  	
38  	//	private static void cacheBundle() { //when bandle update,stop, the instance chenged
39  	//		bundlesMap = new HashMap<String, Bundle>();
40  	//		Bundle[] bs = getBundleContext().getBundles();
41  	//		for (Bundle b : bs) {
42  	//			bundlesMap.put(b.getSymbolicName(), b);
43  	//		}
44  	//	}
45  	
46  	//	public static Bundle getBundle(String bundleName) {
47  	//		synchronized (lock) {
48  	//			if (null == bundlesMap) {
49  	//				cacheBundle();
50  	//			}
51  	//		}
52  	//		return bundlesMap.get(bundleName);
53  	//	}
54  	//	
55  	/**
56  	 * 根据bunlde SymbolicName 取 bundle实例
57  	 * @param bundleName bunlde SymbolicName
58  	 * @return bunlde SymbolicName 对应的bundle实例
59  	 */
60  	public static Bundle getBundle(String bundleName) {
61  		Bundle[] bs = getBundleContext().getBundles();
62  		for (Bundle b : bs) {
63  			if (b.getSymbolicName().equals(bundleName)) {
64  				return b;
65  			}
66  		}
67  		return null;
68  	}
69  	
70  	/**
71  	 * 取得指定bundle下的资源
72  	 * @param bundleName bunlde SymbolicName
73  	 * @param path 资源路径
74  	 * @return 指定bundle下资源
75  	 */
76  	public static URL getResourceOfBundle(String bundleName, String path) {
77  		Bundle bundle = getBundle(bundleName);
78  		if (null == bundle) {
79  			return null;
80  		}
81  		return bundle.getResource(path);
82  	}
83  	
84  }