View Javadoc
1   /**
2    * copyright by Grandsoft Company Limited.  
3    * 2011-12-31
4    */
5   package gboat2.base.core;
6   
7   import gboat2.base.core.exception.NouniqueActionException;
8   
9   import java.util.HashMap;
10  import java.util.Map;
11  
12  import org.osgi.framework.Bundle;
13  
14  public final class GBoatClassLoader extends ClassLoader {
15  
16  	//todo
17  	private static GBoatClassLoader _classLoader = new GBoatClassLoader();
18  
19  	private static Map<String, Bundle> bundleClassLoaders = new HashMap<String, Bundle>();
20  
21  	private static Map<String, String> bundleActionPackage = new HashMap<String, String>();
22  
23  	private GBoatClassLoader() {
24  	}
25  
26  	public static GBoatClassLoader getInstance() {
27  		return _classLoader;
28  	}
29  
30  	public void add(String packageName, Bundle bundle) {
31  		String bundleName = bundle.getSymbolicName();
32  		Bundle finalBundle = bundleClassLoaders.get(packageName);
33  		if (null == finalBundle) {
34  			bundleClassLoaders.put(packageName, bundle);
35  			bundleActionPackage.put(bundleName, packageName);
36  		} else {
37  			if (bundle.getSymbolicName().equals(finalBundle.getSymbolicName())) {
38  				bundleClassLoaders.put(packageName, bundle);
39  				bundleActionPackage.put(bundleName, packageName);
40  			} else {
41  				throw new NouniqueActionException("there are more than one package named " + packageName + " in different bundle!");
42  			}
43  		}
44  	}
45  	
46  	public Bundle getBundle(String packageName) {
47  		return bundleClassLoaders.get(packageName);
48  	}
49  
50  	/**
51  	 * 
52  	 * 根据Bundle名称获取该Bundle下的Action包名
53  	 * @param bundleName
54  	 * @return
55  	 */
56  	public String getActionPackage(String bundleName) {
57  		return bundleActionPackage.get(bundleName);
58  	}
59  
60  	public Class<?> findClass(String className) throws ClassNotFoundException {
61  		if (className.indexOf(".") != -1) {
62  			String packageName = className.substring(0, className.lastIndexOf("."));
63  			if (bundleClassLoaders.containsKey(packageName)) {
64  				Bundle bundle = bundleClassLoaders.get(packageName);
65  				if (bundle != null) {
66  					return bundle.loadClass(className);
67  				}
68  			}
69  		} else {
70  			throw new ClassNotFoundException(className + " should have a package.");
71  		}
72  
73  		throw new ClassNotFoundException(className);
74  	}
75  
76  	public Map<String, Bundle> getBundleClassLoaders() {
77  		return bundleClassLoaders;
78  	}
79  
80  	public Map<String, String> getBundleActionPackage() {
81  		return bundleActionPackage;
82  	}
83  }