1 package org.ocltf.common;
2
3 import java.net.URL;
4 import java.util.Iterator;
5
6 import org.apache.commons.lang.StringUtils;
7 import org.apache.commons.logging.Log;
8 import org.apache.commons.logging.LogFactory;
9 import org.ocltf.utils.ClassUtils;
10
11 /***
12 * Discovers and loads all available Plugin objects
13 * from the current classpath.
14 *
15 * @author Chad Brandon
16 */
17 public class PluginDiscoverer {
18
19 private static final Log logger =
20 LogFactory.getLog(PluginDiscoverer.class);
21
22 private static final Configuration config =
23 Configuration.getInstance(PluginDiscoverer.class);
24
25 /***
26 * The prefix to those configuration properties that are plugins
27 */
28 private static final String PLUGIN_PREFIX = "plugin.";
29
30 /***
31 * The shared instance.
32 */
33 private static final PluginDiscoverer instance = new PluginDiscoverer();
34
35 /***
36 * Gets the default static instance of the PluginDicoverer.
37 * @return PluginDiscoverer the static instance.
38 */
39 public static PluginDiscoverer instance() {
40 return instance;
41 }
42
43 /***
44 * Finds and initializes all Plugin objects on the current classpath.
45 */
46 public void discoverPlugins() {
47 String methodName = "discoverPlugins";
48 if (logger.isDebugEnabled()) {
49 logger.debug("performing " + methodName);
50 }
51
52 try {
53
54 Iterator pluginNameIt = config.getKeys(PLUGIN_PREFIX);
55
56 while (pluginNameIt.hasNext()) {
57 String pluginName = StringUtils.trimToEmpty((String)pluginNameIt.next());
58 String pluginClassName = config.getRequiredString(pluginName);
59 Class pluginClass = ClassUtils.loadClass(pluginClassName);
60 if (!Plugin.class.isAssignableFrom(pluginClass)) {
61 throw new PluginDiscovererException(methodName
62 + " plugin class '" + pluginClassName + "' must implement --> '"
63 + Plugin.class + "'");
64 }
65 Plugin plugin = (Plugin)pluginClass.newInstance();
66 String resourceName = plugin.getResourceName();
67
68 URL[] pluginResources = ResourceFinder.findResources(resourceName);
69
70 if (pluginResources != null && pluginResources.length > 0) {
71 for (int ctr = 0; ctr < pluginResources.length; ctr++) {
72
73 URL pluginUri = pluginResources[ctr];
74 plugin = (Plugin)XmlObjectFactory.getInstance(pluginClass, pluginUri);
75
76 if (logger.isInfoEnabled()) {
77 logger.info(
78 "found " +
79 pluginName.replaceAll(PLUGIN_PREFIX, "")
80 + " --> '" + plugin.getName() + "'");
81 }
82
83 ComponentContainer.instance().registerComponent(plugin.getName(), plugin);
84 }
85 }
86
87 }
88
89 } catch (Exception ex) {
90 String errMsg = "Error performing " + methodName;
91 logger.error(errMsg, ex);
92 throw new PluginDiscovererException(errMsg, ex);
93 }
94 }
95 }