source: trunk/quest-plugin-core/src/main/java/de/ugoe/cs/quest/plugin/PluginLoader.java @ 766

Last change on this file since 766 was 766, checked in by sherbold, 12 years ago
  • Property svn:mime-type set to text/plain
File size: 6.9 KB
Line 
1package de.ugoe.cs.quest.plugin;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.FileNotFoundException;
6import java.io.FilenameFilter;
7import java.io.IOException;
8import java.lang.reflect.InvocationTargetException;
9import java.lang.reflect.Method;
10import java.net.MalformedURLException;
11import java.net.URL;
12import java.net.URLClassLoader;
13import java.util.Collection;
14import java.util.Collections;
15import java.util.LinkedList;
16import java.util.jar.JarInputStream;
17import java.util.jar.Manifest;
18
19/**
20 * <p>
21 * This class provides the functionality to load QUEST plug-ins from a
22 * pre-defined folder.
23 * </p>
24 *
25 * @author Steffen Herbold
26 * @version 1.0
27 */
28public class PluginLoader {
29
30        /**
31         * <p>
32         * Handle of the plug-in directory.
33         * </p>
34         */
35        private final File pluginDir;
36
37        /**
38         * <p>
39         * Collection of the loaded plug-ins.
40         * </p>
41         */
42        private final Collection<QuestPlugin> plugins;
43
44        /**
45         * <p>
46         * Constructor. Creates a new PluginLoader that can load plug-ins the
47         * defined directory.
48         * </p>
49         *
50         * @param pluginDir
51         *            handle of the directory; in case the handle is
52         *            <code>null</code> or does not describe a directory, an
53         *            {@link IllegalArgumentException} is thrown
54         */
55        public PluginLoader(File pluginDir) {
56                if (pluginDir == null) {
57                        throw new IllegalArgumentException(
58                                        "Parameter pluginDir must not be null!");
59                }
60                if (!pluginDir.isDirectory()) {
61                        throw new IllegalArgumentException("File " + pluginDir.getPath()
62                                        + " is not a directory");
63                }
64                this.pluginDir = pluginDir;
65                plugins = new LinkedList<QuestPlugin>();
66        }
67
68        /**
69         * <p>
70         * Loads plug-ins from {@link #pluginDir}.
71         * </p>
72         *
73         * @throws PluginLoaderException
74         *             thrown if there is a problem loading a plug-in or updating
75         *             the classpath
76         */
77        public void load() throws PluginLoaderException {
78                File[] jarFiles = pluginDir.listFiles(new FilenameFilter() {
79                        @Override
80                        public boolean accept(File dir, String name) {
81                                return checkNameConformity(name);
82                        }
83                });
84
85                for (File jarFile : jarFiles) {
86                        updateClassLoader(jarFile);
87
88                        String pluginName = jarFile.getName().split("-")[2];
89                        String pluginClassName = "de.ugoe.cs.quest.plugin." + pluginName
90                                        + "." + pluginName.toUpperCase() + "Plugin";
91
92                        Class<?> pluginClass = null;
93                        try {
94                                pluginClass = Class.forName(pluginClassName);
95                        } catch (ClassNotFoundException e) {
96                                throw new PluginLoaderException("No class '" + pluginClassName
97                                                + "' found in " + pluginDir + "/" + jarFile.getName());
98                        }
99                        try {
100                                QuestPlugin pluginObject = (QuestPlugin) pluginClass
101                                                .newInstance();
102                                plugins.add(pluginObject);
103                        } catch (InstantiationException e) {
104                                throw new PluginLoaderException("Could not instantiate "
105                                                + pluginClassName);
106                        } catch (IllegalAccessException e) {
107                                throw new PluginLoaderException("Could not access "
108                                                + pluginClassName);
109                        } catch (ClassCastException e) {
110                                throw new PluginLoaderException("Class " + pluginClassName
111                                                + " not instance of QuestPlugin");
112                        }
113                }
114        }
115
116        /**
117         * <p>
118         * Retrieves the classpath from a Jar file's MANIFEST.
119         * </p>
120         *
121         * @throws IOException
122         * @throws FileNotFoundException
123         */
124        protected String[] getClassPathFromJar(File jarFile) {
125                String[] classPath;
126
127                JarInputStream jarInputStream = null;
128                try {
129                        jarInputStream = new JarInputStream(new FileInputStream(jarFile));
130                } catch (FileNotFoundException e) {
131                        throw new AssertionError(
132                                        "FileNotFoundException should be impossible!");
133                } catch (IOException e) {
134                        throw new PluginLoaderException(e);
135                }
136
137                Manifest manifest = jarInputStream.getManifest();
138
139                String jarClassPath = manifest.getMainAttributes().getValue(
140                                "Class-Path");
141
142                if (jarClassPath != null) {
143                        String[] jarClassPathElements = jarClassPath.split(" ");
144                        classPath = new String[jarClassPathElements.length];
145                        for (int i = 0; i < jarClassPathElements.length; i++) {
146                                classPath[i] = "file:"
147                                                + jarFile.getParentFile().getAbsolutePath() + "/"
148                                                + jarClassPathElements[i];
149                        }
150                        try {
151                                jarInputStream.close();
152                        } catch (IOException e) {
153                                throw new PluginLoaderException(e);
154                        }
155                } else {
156                        classPath = new String[] {};
157                }
158                return classPath;
159        }
160
161        /**
162         * <p>
163         * Updates the classpath of the {@link ClassLoader} to include the plug-in
164         * jar as well as further libraries required by the plug-in jar as defined
165         * in the <code>Class-Path</code> section of its manifest.
166         * </p>
167         *
168         * @param jarFile
169         *            handle of the plug-in jar file
170         * @throws PluginLoaderException
171         *             thrown if there is a problem updating the class loader or
172         *             loading the plug-in jar
173         */
174        private void updateClassLoader(File jarFile) throws PluginLoaderException {
175                String[] classPath = getClassPathFromJar(jarFile);
176                URLClassLoader classLoader = (URLClassLoader) ClassLoader
177                                .getSystemClassLoader();
178                Method method;
179
180                try {
181                        method = URLClassLoader.class.getDeclaredMethod("addURL",
182                                        new Class[] { URL.class });
183                } catch (SecurityException e) {
184                        throw new PluginLoaderException(
185                                        "addURL method of URLClassLoader not accessible via reflection.");
186                } catch (NoSuchMethodException e) {
187                        throw new AssertionError(
188                                        "URLClassLoader does not have addURL method. Should be impossible!!");
189                }
190                method.setAccessible(true);
191
192                try {
193                        method.invoke(
194                                        classLoader,
195                                        new Object[] { new URL("file:" + jarFile.getAbsoluteFile()) });
196                        for (String element : classPath) {
197                                method.invoke(classLoader, new Object[] { new URL(element) });
198                        }
199                } catch (IllegalArgumentException e) {
200                        throw new AssertionError(
201                                        "Illegal arguments for addURL method. Should be impossible!!");
202                } catch (MalformedURLException e) {
203                        throw new PluginLoaderException(e);
204                } catch (IllegalAccessException e) {
205                        throw new PluginLoaderException(
206                                        "addURL method of URLClassLoader not accessible via reflection.");
207                } catch (InvocationTargetException e) {
208                        throw new PluginLoaderException(e);
209                }
210        }
211
212        /**
213         * <p>
214         * Checks if the name of a file indicates that it defines a QUEST plug-in.
215         * The structure of valid plug-in filenames is
216         * <code>quest-plugin-%PLUGIN_NAME%-version.jar</code>, where
217         * <code>%PLUGIN_NAME%</code> is replaced by the name of the plug-in. Note
218         * that plug-in names must not contain any dashes.
219         * </p>
220         *
221         * @param filename
222         *            filename that is checked
223         * @return true if filename matches pattern of QUEST plug-in; false
224         *         otherwise
225         */
226        protected boolean checkNameConformity(String filename) {
227                if (filename == null) {
228                        return false;
229                }
230                return filename.startsWith("quest-plugin-") && !filename.startsWith("quest-plugin-core")
231                                &&
232                                ((filename.split("-").length == 4 && filename.endsWith(".jar")) ||
233                                  filename.split("-").length == 5 && filename.endsWith("SNAPSHOT.jar"));
234        }
235       
236        public Collection<QuestPlugin> getPlugins() {
237                return Collections.unmodifiableCollection(plugins);
238        }
239}
Note: See TracBrowser for help on using the repository browser.