1 4 package com.tc.aspectwerkz.hook; 5 6 import java.io.BufferedOutputStream ; 7 import java.io.ByteArrayOutputStream ; 8 import java.io.DataOutputStream ; 9 import java.io.File ; 10 import java.io.FileOutputStream ; 11 import java.io.IOException ; 12 import java.io.InputStream ; 13 14 19 public class ClassLoaderPatcher { 20 23 public static byte[] inputStreamToByteArray(InputStream is) throws IOException { 24 ByteArrayOutputStream os = new ByteArrayOutputStream (); 25 for (int b = is.read(); b != -1; b = is.read()) { 26 os.write(b); 27 } 28 return os.toByteArray(); 29 } 30 31 34 static byte[] getPatchedClassLoader(String preProcessorName) { 35 byte[] abyte = null; 36 InputStream is = null; 37 try { 38 is = ClassLoader.getSystemClassLoader().getParent().getResourceAsStream("java/lang/ClassLoader.class"); 39 abyte = inputStreamToByteArray(is); 40 } catch (IOException e) { 41 throw new Error ("failed to read java.lang.ClassLoader: " + e.toString()); 42 } finally { 43 try { 44 is.close(); 45 } catch (Exception e) { 46 ; 47 } 48 } 49 if (preProcessorName != null) { 50 try { 51 ClassLoaderPreProcessor clpi = (ClassLoaderPreProcessor) Class.forName(preProcessorName).newInstance(); 52 abyte = clpi.preProcess(abyte); 53 } catch (Exception e) { 54 System.err.println("failed to instrument java.lang.ClassLoader: preprocessor not found"); 55 e.printStackTrace(); 56 } 57 } 58 return abyte; 59 } 60 61 64 private static void writeClass(String className, byte[] bytes, String dir) { 65 String filename = dir + File.separatorChar + className.replace('.', File.separatorChar) + ".class"; 66 int pos = filename.lastIndexOf(File.separatorChar); 67 if (pos > 0) { 68 String finalDir = filename.substring(0, pos); 69 (new File (finalDir)).mkdirs(); 70 } 71 try { 72 DataOutputStream out = new DataOutputStream (new BufferedOutputStream (new FileOutputStream (filename))); 73 out.write(bytes); 74 out.close(); 75 } catch (IOException e) { 76 System.err.println("failed to write " + className + " in " + dir); 77 e.printStackTrace(); 78 } 79 } 80 81 84 public static void patchClassLoader(String preProcessorName, String dir) { 85 byte[] cl = getPatchedClassLoader(preProcessorName); 86 writeClass("java.lang.ClassLoader", cl, dir); 87 } 88 89 } | Popular Tags |