1
2
3
4
5
6 package org.astrogrid.devtools;
7
8
9 /***
10 * Locates the jar file in a subdirectory of this one that has the given
11 * class in it. Used for all those nasty NoClassDefFoundError which means
12 * you haven't included some jar file in your classpath but you have no idea
13 * which one it is.
14 * <p>
15 * This does of course mean that you have to have that jar file present (so
16 * it can be found) but you can run this on a working system to find the name
17 * of it
18 * <p>
19 *
20 * @author M Hill
21 */
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.util.Enumeration;
26 import java.util.jar.JarFile;
27 import java.util.zip.ZipEntry;
28 import org.astrogrid.util.ClassPathUtils;
29
30 public class JarFinder
31 {
32 /***
33 * Looks for the class in the classpath - has ready made found jars/directories
34 */
35 public static String findInClasspath(String className) throws IOException
36 {
37
38
39
40
41 String[] paths = ClassPathUtils.getClassPathList();
42
43 for (int i=0; i<paths.length;i++)
44 {
45 String path = paths[i];
46
47 if (path.endsWith(".jar"))
48 {
49 if (isClassInJar(className, path))
50 {
51 return path;
52 }
53 }
54 }
55
56 return null;
57
58
59
60
61
62 }
63
64 /***
65 * Looks to see if the given class is in the given jar file. */
66 public static boolean isClassInJar(String className, String jarPath) throws IOException
67 {
68 JarFile jarFile = new JarFile(new File(jarPath));
69
70 Enumeration entries = jarFile.entries();
71
72 while (entries.hasMoreElements())
73 {
74 ZipEntry entry = (ZipEntry) entries.nextElement();
75
76 String entryName = entry.getName();
77
78 if (entryName.indexOf(className) >-1)
79 {
80 System.out.println("Found "+entryName+" in "+jarPath);
81 return true;
82 }
83
84 }
85
86
87 return false;
88 }
89
90
91
92
93 /***
94 * For running from the command line
95 */
96 public static void main(String[] args) throws IOException
97 {
98 String classname = args[0];
99
100 String jar = findInClasspath(classname);
101 System.out.println(jar);
102
103 }
104 }
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121