View Javadoc
1   /**
2    * Copyright By Grandsoft Company Limited.  
3    * 2012-10-15 上午09:16:21
4    */
5   package gboat2.base.core.web;
6   
7   import gboat2.base.core.Activator;
8   
9   import org.osgi.framework.BundleContext;
10  import org.osgi.util.tracker.ServiceTracker;
11  import org.slf4j.Logger;
12  import org.slf4j.LoggerFactory;
13  
14  /**
15   * 
16   * 跟踪SystemButtonProvider的服务实现
17   * @author tanxw
18   * @since jdk1.6
19   * @date 2012-10-15
20   *  
21   */
22  
23  public abstract class SystemButtonProviderTracker {
24  	
25  	@SuppressWarnings("rawtypes")
26      private static ServiceTracker tracker = null;
27  	
28  	protected static Logger logger = LoggerFactory.getLogger(SystemButtonProviderTracker.class);
29  	
30  	private static byte[] lock = new byte[0];
31  	
32  	/**
33  	 * 开启服务跟踪,使用者必须保证在调用服务获取方法{@see #getProviders()}之前调用
34  	 * @param context bundle上下文
35  	 */
36  	@SuppressWarnings({ "rawtypes", "unchecked" })
37      public static void open(BundleContext context) {
38  		if (null != tracker) {//如果多次调用本方法打开跟踪器,在先关闭以前的,防止泄露
39  			tracker.close();
40  		}
41  		tracker = new ServiceTracker(context, SystemButtonProvider.class.getName(), null);
42  		tracker.open();
43  	}
44  	
45  	/**
46  	 *关闭跟踪器,建议的bundle关闭时,或者不在需要跟踪 WidgetService服务时,调用本方法,以便释放资源
47  	 */
48  	public static void close() {
49  		if (null != tracker) {
50  			tracker.close();
51  			tracker = null;
52  		}
53  	}
54  	
55  	/**
56  	 * 获取所有SystemButtonProvider的实现 ,由于服务时动态的,不要缓存本方法返回的结果
57  	 * @return 所有SystemButtonProvider的实现
58  	 */
59  	public static SystemButtonProvider[] getProviders() {
60  		synchronized (lock) {//打开跟踪器
61  			if (null == tracker) {
62  				open(Activator.LOCAL_BUNDLE.getBundleContext());
63  			}
64  		}
65  		
66  		Object[] objs = tracker.getServices();
67  		if (null != objs) {
68  			SystemButtonProvider[] services = new SystemButtonProvider[objs.length];
69  			int i;
70  			for (i = 0; i < objs.length; i++) {
71  				services[i] = (SystemButtonProvider) objs[i];
72  			}
73  			return services;
74  		}
75  		
76  		return null;
77  	}
78  }