1 package hudson.remoting; 2 3 import java.io.ByteArrayOutputStream ; 4 import java.io.File ; 5 import java.io.IOException ; 6 import java.io.UnsupportedEncodingException ; 7 import java.net.URL ; 8 9 14 public class Which { 15 public static File jarFile(Class clazz) throws IOException { 16 String res = clazz.getClassLoader().getResource(clazz.getName().replace('.', '/') + ".class").toExternalForm(); 17 if(res.startsWith("jar:")) { 18 res = res.substring(4,res.lastIndexOf('!')); return new File (decode(new URL (res).getPath())); 20 } 21 22 if(res.startsWith("file:")) { 23 int n = clazz.getName().split("\\.").length; for( ; n>0; n-- ) { 26 int idx = Math.max(res.lastIndexOf('/'), res.lastIndexOf('\\')); 27 res = res.substring(0,idx); 28 } 29 30 35 return new File (decode(new URL (res).getPath())); 36 } 37 38 throw new IllegalArgumentException (res); 39 } 40 41 44 private static String decode(String s) { 45 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 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 (baos.toByteArray(),"UTF-8"); 57 } catch (UnsupportedEncodingException e) { 58 throw new Error (e); } 60 } 61 62 private static int hexToInt(int ch) { 63 return Character.getNumericValue(ch); 64 } 65 } 66 | Popular Tags |