Package org.skayred

Source Code of org.skayred.Profiler

package org.skayred;

import javassist.ByteArrayClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

/**
* Created with IntelliJ IDEA.
* User: dmitry
* Date: 12/6/12
* Time: 8:54 PM
* To change this template use File | Settings | File Templates.
*/
public class Profiler implements ClassFileTransformer {
    protected static Profiler profilerInstance = null;
    protected Instrumentation instrumentation = null;
    protected ClassPool classPool;

    public static void premain(String agentArgs, Instrumentation inst) {
        Profiler profiler = new Profiler(inst);
    }

    public static Profiler getInstance() {
        return profilerInstance;
    }

    public Profiler(Instrumentation inst) {
        profilerInstance = this;
        instrumentation = inst;
        classPool = ClassPool.getDefault();
        instrumentation.addTransformer(this);
    }

    public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined,
                            ProtectionDomain protectionDomain, byte[] classFileBuffer)
            throws IllegalClassFormatException {
        System.out.println("Class " + className + " loaded. Size " + classFileBuffer.length + " bytes");

        try {
            classPool.insertClassPath(new ByteArrayClassPath(className, classFileBuffer));
            CtClass cc = classPool.get(className);
            CtMethod[] methods = cc.getMethods();
            for (int k = 0; k < methods.length; k++) {
                if (methods[k].getLongName().startsWith(className)) {
                    methods[k].insertBefore("System.out.println(\"Entering " + methods[k].getLongName() + "\");");
                    methods[k].insertAfter("System.out.println(\"Exiting " + methods[k].getLongName() + "\");");
                }
            }

            byte[] newClassfileBuffer = cc.toBytecode();
            return newClassfileBuffer;
        } catch (Exception ioe) {
//            System.err.println(ioe.getMessage() + " transforming class " + className + "; returning uninstrumented    class");
            return null;
        }
    }
}
TOP

Related Classes of org.skayred.Profiler

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.