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

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