1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package nl.toolforge.karma.launcher;
21
22 import java.io.File;
23 import java.io.FileNotFoundException;
24 import java.io.FilenameFilter;
25 import java.net.MalformedURLException;
26 import java.net.URL;
27 import java.net.URLClassLoader;
28
29 /***
30 * @author oosterom
31 */
32 public class KarmaClassLoader extends URLClassLoader {
33 KarmaClassLoader(ClassLoader parentLoader) {
34 super(new URL[0], parentLoader);
35 }
36
37 /***
38 * Overloaded version of <code>addRepository(File repository)</code>
39 */
40 public void addClassPathEntry(String classPathEntry) throws FileNotFoundException {
41 addClassPathEntry(new File(classPathEntry));
42 }
43
44 /***
45 * Add a file to the classpath of the classloader. If the file is a regular
46 * file and ends with ".jar/.zip" it is added to the classpath. If the file
47 * is a directory the directory is added to the classpath. If the directory
48 * contains jar/zip files, also the jar/zip files are added to the classpath
49 *
50 * @param classPathEntry
51 * The file to be added to the classpath
52 */
53 public void addClassPathEntry(File classPathEntry) throws FileNotFoundException {
54
55
56 if (classPathEntry == null) {
57 throw new NullPointerException("classPathEntry == null.");
58 }
59
60 if (!classPathEntry.exists()) {
61 throw new FileNotFoundException(classPathEntry.getName()
62 + " does not exist.");
63 }
64
65
66
67
68 try {
69
70
71
72 if (classPathEntry.isFile()) {
73 if (classPathEntry.getAbsolutePath().endsWith(".jar")
74 || classPathEntry.getAbsolutePath().endsWith(".zip")) {
75 addURL(classPathEntry.toURL());
76 }
77
78 return;
79 }
80
81
82
83
84 addURL(classPathEntry.toURL());
85
86
87
88
89 File[] jars = classPathEntry.listFiles(new FilenameFilter() {
90 public boolean accept(File dir, String name) {
91 if (name.endsWith(".jar") || name.endsWith(".zip")) {
92 return true;
93 } else {
94 return false;
95 }
96 }
97 });
98
99
100
101 if (jars != null) {
102 for (int i = 0; i < jars.length; i++) {
103 addURL(jars[i].toURL());
104 }
105 }
106 } catch (MalformedURLException e) {
107 throw new FileNotFoundException(e.getMessage());
108 }
109 }
110 }