001 package nl.cwi.sen1.gui.plugin;
002
003 import java.io.IOException;
004 import java.net.JarURLConnection;
005 import java.net.MalformedURLException;
006 import java.net.URL;
007 import java.net.URLClassLoader;
008 import java.util.StringTokenizer;
009 import java.util.jar.Attributes;
010
011
012 import aterm.ATermAppl;
013 import aterm.ATermList;
014
015 public class PluginLoader extends URLClassLoader {
016 private static final String CLASSPATH_SEPARATORS = ":";
017
018 private URL pluginURL;
019
020 public PluginLoader(String pluginName) {
021 super(new URL[] {});
022 this.pluginURL = createURL(pluginName);
023 addURL(pluginURL);
024 }
025
026 public PluginLoader(String pluginName, ATermList classPathEntries) {
027 this(pluginName);
028 for (int i = 0; !classPathEntries.isEmpty(); i++) {
029 String entry = ((ATermAppl) classPathEntries.getFirst()).getName();
030 addURL(createURL(entry));
031 classPathEntries = classPathEntries.getNext();
032 }
033 }
034
035 public PluginLoader(String pluginName, String classPath) {
036 this(pluginName);
037 StringTokenizer tok = new StringTokenizer(classPath,
038 CLASSPATH_SEPARATORS);
039 while (tok.hasMoreTokens()) {
040 String url = tok.nextToken();
041 try {
042 addURL(new URL("file:" + url));
043 } catch (MalformedURLException e) {
044 System.err.println("Ignoring malformed url: " + url);
045 }
046 }
047 }
048
049 private URL createURL(String jarName) {
050 URL url = null;
051 try {
052 url = new URL(jarName);
053 } catch (MalformedURLException e) {
054 System.err.println("Invalid URL: " + jarName);
055 }
056 return url;
057 }
058
059 /**
060 * Returns the name of the jar file main class, or null if no "Main-Class"
061 * manifest attribute was defined.
062 */
063 private String findPluginMain() throws IOException {
064 String pluginMain = null;
065 URL u = new URL("jar", "", pluginURL + "!/");
066 JarURLConnection uc = (JarURLConnection) u.openConnection();
067 Attributes attr = uc.getMainAttributes();
068 if (attr != null) {
069 pluginMain = attr.getValue(Attributes.Name.MAIN_CLASS);
070 } else {
071 System.err.println("Unable to find a Main-Class in plugin: " + pluginURL);
072 }
073 return pluginMain;
074 }
075
076 public StudioPlugin instantiatePlugin() {
077 try {
078 String pluginMain = findPluginMain();
079 StudioPlugin plugin = null;
080 Class<?> cl = loadClass(pluginMain);
081 return (StudioPlugin) cl.newInstance();
082 } catch (Exception e) {
083 System.err.println("Failed to instantiate plugin:" + pluginURL + "\n" + e.getMessage());
084 return null;
085 }
086 }
087 }