1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.log4j.chainsaw.plugins;
18
19 import java.io.File;
20 import java.io.FilenameFilter;
21 import java.net.URL;
22 import java.net.URLClassLoader;
23 import java.util.ArrayList;
24 import java.util.List;
25
26 import org.apache.log4j.chainsaw.prefs.SettingsManager;
27
28
29
30
31
32
33
34
35
36
37
38
39 public class PluginClassLoaderFactory {
40 private final ClassLoader pluginClassLoader;
41
42 private static final PluginClassLoaderFactory instance = new PluginClassLoaderFactory();
43
44 private PluginClassLoaderFactory() {
45 this.pluginClassLoader= PluginClassLoaderFactory.create(new File(SettingsManager.getInstance().getSettingsDirectory() + File.separator + "plugins"));
46
47 }
48
49 public static PluginClassLoaderFactory getInstance() {
50 return instance;
51 }
52
53 public ClassLoader getClassLoader() {
54 return this.pluginClassLoader;
55 }
56
57
58
59
60
61
62
63
64
65
66
67
68 private static final ClassLoader create(File pluginDirectory) {
69 if(pluginDirectory == null || !pluginDirectory.exists() || !pluginDirectory.canRead()) {
70 return PluginClassLoaderFactory.class.getClassLoader();
71 }
72
73 String[] strings = pluginDirectory.list(new FilenameFilter() {
74
75 public boolean accept(File dir, String name) {
76 return name.toUpperCase().endsWith(".JAR");
77 }});
78
79
80 List list = new ArrayList();
81
82 try {
83 list.add(pluginDirectory.toURI().toURL());
84 } catch (Exception e) {
85 throw new RuntimeException(e.getMessage());
86 }
87 if (strings !=null) {
88 for (int i = 0; i < strings.length; i++) {
89 String name = strings[i];
90 File file = new File(pluginDirectory, name);
91 try {
92 list.add(file.toURI().toURL());
93 System.out.println("Added " + file.getAbsolutePath()
94 + " to Plugin class loader list");
95 } catch (Exception e) {
96 System.err.println("Failed to retrieve the URL for file: "
97 + file.getAbsolutePath());
98 throw new RuntimeException(e.getMessage());
99 }
100 }
101 }
102 ClassLoader parent = PluginClassLoaderFactory.class.getClassLoader();
103 URL[] urls = (URL[]) list.toArray(new URL[list.size()]);
104 return new URLClassLoader(urls, parent);
105 }
106
107 }