private void load(File jarFile) { ClassLoader loader; try { loader = URLClassLoader.newInstance( new URL[] {jarFile.toURI().toURL()}, getClass().getClassLoader()); } catch (MalformedURLException e) { Application.LOGGER.error( "Error while loading plugin file - " + jarFile.getAbsolutePath(), e); return; } InputStream stream = loader.getResourceAsStream(MANIFEST_FILE); Properties properties = new Properties(); try { properties.load(stream); } catch (IOException e) { Application.LOGGER.error( "Manifest file - " + MANIFEST_FILE + " not found in the plugin jar - " + jarFile.getAbsolutePath(), e); return; } String pluginClassName = properties.getProperty("plugin.class"); if (!properties.containsKey("plugin.class")) { Application.LOGGER.error( "plugin.class not defined in the manifest file in the plugin jar - " + jarFile.getAbsolutePath()); return; } Class<?> clazz; try { clazz = Class.forName(pluginClassName, true, loader); } catch (ClassNotFoundException e) { Application.LOGGER.error( "Plugin main class - " + pluginClassName + " defined in manifest not found in the plugin jar - " + jarFile.getAbsolutePath(), e); return; } if (!Plugin.class.isAssignableFrom(clazz)) { Application.LOGGER.error( "Plugin class - " + clazz + " is not a Plugin, in the plugin jar - " + jarFile.getAbsolutePath()); } load((Class<? extends Plugin>) clazz, properties); }
private void load(Class<? extends Plugin> pluginClass, Properties properties) { // A plugin can be instantiated only once if (PLUGINS.containsKey(pluginClass)) { Application.LOGGER.error("Plugin for " + pluginClass + " is already loaded"); return; } Plugin plugin; try { plugin = pluginClass.newInstance(); } catch (InstantiationException e) { Application.LOGGER.error("Error while instantiating plugin from " + pluginClass, e); return; } catch (IllegalAccessException e) { Application.LOGGER.error( "Plugin class default constructor not accessible for " + pluginClass, e); return; } // register the plugin PLUGINS.put(pluginClass, plugin); // Load the properties if available if (properties != null) { plugin.name = properties.getProperty("plugin.name"); plugin.version = Version.parse(properties.getProperty("plugin.version")); plugin.description = properties.getProperty("plugin.description"); } else { // in case the application is loading the plugin directly plugin.name = pluginClass.getSimpleName(); plugin.version = null; plugin.description = null; } // Let the plugin initialize Application.LOGGER.trace( "Initializing Plugin - " + plugin.name + " - " + pluginClass.getCanonicalName()); plugin.onInit(app); }
void loadPlugins() { // go through all the jar files within the plugin folder File folder = new File(pluginFolder); if (folder.isDirectory()) { for (File jarFile : folder.listFiles()) { if (jarFile.isFile() && jarFile.getName().endsWith(".jar")) { load(jarFile); } } } else { Application.LOGGER.error("Error loading plugins - " + pluginFolder + " is not a directory"); } }