KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hudson > remoting > Which


1 package hudson.remoting;
2
3 import java.io.ByteArrayOutputStream JavaDoc;
4 import java.io.File JavaDoc;
5 import java.io.IOException JavaDoc;
6 import java.io.UnsupportedEncodingException JavaDoc;
7 import java.net.URL JavaDoc;
8
9 /**
10  * Locates where a given class is loaded from.
11  *
12  * @author Kohsuke Kawaguchi
13  */

14 public class Which {
15     public static File JavaDoc jarFile(Class JavaDoc clazz) throws IOException JavaDoc {
16         String JavaDoc res = clazz.getClassLoader().getResource(clazz.getName().replace('.', '/') + ".class").toExternalForm();
17         if(res.startsWith("jar:")) {
18             res = res.substring(4,res.lastIndexOf('!')); // cut off jar: and the file name portion
19
return new File JavaDoc(decode(new URL JavaDoc(res).getPath()));
20         }
21
22         if(res.startsWith("file:")) {
23             // unpackaged classes
24
int n = clazz.getName().split("\\.").length; // how many slashes do wo need to cut?
25
for( ; n>0; n-- ) {
26                 int idx = Math.max(res.lastIndexOf('/'), res.lastIndexOf('\\'));
27                 res = res.substring(0,idx);
28             }
29
30             // won't work if res URL contains ' '
31
// return new File(new URI(null,new URL(res).toExternalForm(),null));
32
// won't work if res URL contains '%20'
33
// return new File(new URL(res).toURI());
34

35             return new File JavaDoc(decode(new URL JavaDoc(res).getPath()));
36         }
37
38         throw new IllegalArgumentException JavaDoc(res);
39     }
40
41     /**
42      * Decode '%HH'.
43      */

44     private static String JavaDoc decode(String JavaDoc s) {
45         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
46         for( int i=0; i<s.length();i++ ) {
47             char ch = s.charAt(i);
48             if(ch=='%') {
49                 baos.write(hexToInt(s.charAt(i+1))*16 + hexToInt(s.charAt(i+2)));
50                 i+=2;
51                 continue;
52             }
53             baos.write(ch);
54         }
55         try {
56             return new String JavaDoc(baos.toByteArray(),"UTF-8");
57         } catch (UnsupportedEncodingException JavaDoc e) {
58             throw new Error JavaDoc(e); // impossible
59
}
60     }
61
62     private static int hexToInt(int ch) {
63         return Character.getNumericValue(ch);
64     }
65 }
66
Popular Tags