(no commit message)
[utils] / support / src / main / java / org / wamblee / general / ClassPathHacker.java
1 /*
2  * Copyright 2006 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.wamblee.general;
18
19 import java.io.IOException;
20 import java.io.File;
21 import java.net.URLClassLoader;
22 import java.net.URL;
23 import java.lang.reflect.Method;
24
25 public class ClassPathHacker {
26
27     private static final Class[] PARAMETERS = new Class[] { URL.class };
28
29     private static final String JAR_SUFFIX = ".jar";
30
31     public static void addJarsInDirectory(File aDirectory) throws IOException {
32         System.out.println("directory '" + aDirectory + "'");
33
34         for (File aFile : aDirectory.listFiles()) {
35             System.out
36                     .println("Considering '" + aFile.getCanonicalPath() + "'");
37             if (aFile.getName().toLowerCase().endsWith(JAR_SUFFIX)) {
38                 System.out.println("Adding '" + aFile.getCanonicalPath()
39                         + "' to classpath.");
40                 addFile(aFile);
41             }
42         }
43     }
44
45     public static void addFile(String s) throws IOException {
46         File f = new File(s);
47         addFile(f);
48     }
49
50     public static void addFile(File f) throws IOException {
51         addURL(f.toURL());
52     }
53
54     public static void addURL(URL u) throws IOException {
55
56         URLClassLoader sysloader = (URLClassLoader) ClassLoader
57                 .getSystemClassLoader();
58         Class sysclass = URLClassLoader.class;
59
60         try {
61             Method method = sysclass.getDeclaredMethod("addURL", PARAMETERS);
62             method.setAccessible(true);
63             method.invoke(sysloader, new Object[] { u });
64         } catch (Throwable t) {
65             t.printStackTrace();
66             throw new IOException(
67                     "Error, could not add URL to system classloader");
68         }
69
70     }
71
72 }