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