Created
June 8, 2014 20:45
-
-
Save Romain-P/a020702a19c0957c4d60 to your computer and use it in GitHub Desktop.
better ;)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package org.heater.core.plugin; | |
| import com.google.inject.AbstractModule; | |
| import com.google.inject.Inject; | |
| import com.google.inject.multibindings.Multibinder; | |
| import org.heater.api.HeaterActivator; | |
| import java.io.File; | |
| import java.io.FileFilter; | |
| import java.net.MalformedURLException; | |
| import java.net.URL; | |
| import java.net.URLClassLoader; | |
| import java.util.*; | |
| public class PluginManager { | |
| private final List<HeaterActivator> instances; | |
| private AbstractModule module; | |
| @Inject Set<HeaterActivator> plugins; | |
| public PluginManager() { | |
| this.instances = new ArrayList<>(); | |
| } | |
| public PluginManager initialize() { | |
| File[] files = new File("plugins").listFiles(file -> file.getPath().toLowerCase().endsWith(".jar")); | |
| URL[] urls = new URL[files.length]; | |
| for (int i = 0; i < files.length; i++) { | |
| try { | |
| urls[i] = files[i].toURI().toURL(); | |
| } catch (MalformedURLException e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| ServiceLoader<HeaterActivator> loader = ServiceLoader.load(HeaterActivator.class, new URLClassLoader(urls)); | |
| for(HeaterActivator instance: loader) | |
| this.instances.add(instance); | |
| return this; | |
| } | |
| public void terminate() { | |
| if(plugins == null) return; | |
| for(HeaterActivator plugin: plugins) | |
| plugin.stop(); | |
| } | |
| public void installPlugins() { | |
| if(plugins == null) return; | |
| for(HeaterActivator plugin: plugins) | |
| plugin.start(); | |
| } | |
| private AbstractModule buildModule() { | |
| return new AbstractModule() { | |
| @Override | |
| protected void configure() { | |
| bind(PluginManager.class).toInstance(PluginManager.this); | |
| Multibinder<HeaterActivator> binder = Multibinder.newSetBinder(binder(), HeaterActivator.class); | |
| for(HeaterActivator instance: instances) { | |
| binder.addBinding().toInstance(instance); | |
| install(instance.pluginModule()); | |
| } | |
| } | |
| }; | |
| } | |
| public AbstractModule getModule() { | |
| return module != null ? module : (module = buildModule()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment