Search in sources :

Example 1 with CtMethod

use of javassist.CtMethod in project Hystrix by Netflix.

the class NetworkClassTransform method wrapClass.

/**
     * Wrap all signatures of a given method name.
     * 
     * @param className
     * @param methodName
     * @throws NotFoundException
     * @throws CannotCompileException
     * @throws IOException
     */
private byte[] wrapClass(String className, boolean wrapConstructors, String... methodNames) throws NotFoundException, IOException, CannotCompileException {
    ClassPool cp = ClassPool.getDefault();
    CtClass ctClazz = cp.get(className);
    // constructors
    if (wrapConstructors) {
        CtConstructor[] constructors = ctClazz.getConstructors();
        for (CtConstructor constructor : constructors) {
            try {
                constructor.insertBefore("{ com.netflix.hystrix.contrib.networkauditor.HystrixNetworkAuditorAgent.notifyOfNetworkEvent(); }");
            } catch (Exception e) {
                throw new RuntimeException("Failed trying to wrap constructor of class: " + className, e);
            }
        }
    }
    // methods
    CtMethod[] methods = ctClazz.getDeclaredMethods();
    for (CtMethod method : methods) {
        try {
            for (String methodName : methodNames) {
                if (method.getName().equals(methodName)) {
                    method.insertBefore("{ com.netflix.hystrix.contrib.networkauditor.HystrixNetworkAuditorAgent.handleNetworkEvent(); }");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed trying to wrap method [" + method.getName() + "] of class: " + className, e);
        }
    }
    return ctClazz.toBytecode();
}
Also used : CtClass(javassist.CtClass) ClassPool(javassist.ClassPool) CannotCompileException(javassist.CannotCompileException) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) NotFoundException(javassist.NotFoundException) IOException(java.io.IOException) CtMethod(javassist.CtMethod) CtConstructor(javassist.CtConstructor)

Example 2 with CtMethod

use of javassist.CtMethod in project jersey by jersey.

the class PerfTestAgent method premain.

public static void premain(String agentArgs, Instrumentation instrumentation) {
    final String handlerClassName = (agentArgs != null && !agentArgs.isEmpty()) ? agentArgs.substring(0, agentArgs.lastIndexOf('.')) : HANDLER_CLASS_NAME;
    final String handlerMethodName = (agentArgs != null && !agentArgs.isEmpty()) ? agentArgs.substring(agentArgs.lastIndexOf('.') + 1) : HANDLER_METHOD_NAME;
    instrumentation.addTransformer(new ClassFileTransformer() {

        @Override
        public byte[] transform(ClassLoader loader, String className, Class<?> aClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException {
            if (handlerClassName.replaceAll("\\.", "/").equals(className)) {
                try {
                    ClassPool cp = ClassPool.getDefault();
                    cp.appendSystemPath();
                    CtClass cc = cp.makeClass(new java.io.ByteArrayInputStream(bytes));
                    final CtField ctxField = CtField.make("public static final agent.metrics.Timer.Context agentTimerCtx;", cc);
                    final CtField registryField = CtField.make("public static final agent.metrics.MetricRegistry agentREG = new agent.metrics.MetricRegistry();", cc);
                    final CtField reporterField = CtField.make("public static final agent.metrics.JmxReporter agentReporter = agent.metrics.JmxReporter.forRegistry(agentREG).build();", cc);
                    final CtField timerField = CtField.make("public static final agent.metrics.Timer agentTimer = " + "agentREG.timer(agent.metrics.MetricRegistry.name(\"" + handlerClassName + "\", new String[] {\"" + handlerMethodName + "\"}));", cc);
                    cc.addField(registryField);
                    cc.addField(reporterField);
                    cc.addField(timerField);
                    cc.makeClassInitializer().insertAfter("agentReporter.start();");
                    CtMethod m = cc.getDeclaredMethod(handlerMethodName);
                    m.addLocalVariable("agentCtx", ctxField.getType());
                    m.insertBefore("agentCtx = agentTimer.time();");
                    m.insertAfter("agentCtx.stop();", true);
                    byte[] byteCode = cc.toBytecode();
                    cc.detach();
                    System.out.printf("Jersey Perf Agent Instrumentation Done! (instrumented method: %s)\n", m.getLongName());
                    return byteCode;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            return null;
        }
    });
}
Also used : ProtectionDomain(java.security.ProtectionDomain) ClassFileTransformer(java.lang.instrument.ClassFileTransformer) ClassPool(javassist.ClassPool) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) CtClass(javassist.CtClass) CtField(javassist.CtField) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) CtMethod(javassist.CtMethod)

Example 3 with CtMethod

use of javassist.CtMethod in project pinpoint by naver.

the class JavassistClass method addGetter.

@Override
public void addGetter(String getterTypeName, String fieldName) throws InstrumentException {
    try {
        Class<?> getterType = pluginContext.injectClass(classLoader, getterTypeName);
        GetterAnalyzer getterAnalyzer = new GetterAnalyzer();
        GetterDetails getterDetails = getterAnalyzer.analyze(getterType);
        CtField field = ctClass.getField(fieldName);
        String fieldTypeName = JavaAssistUtils.javaClassNameToObjectName(getterDetails.getFieldType().getName());
        if (!field.getType().getName().equals(fieldTypeName)) {
            throw new IllegalArgumentException("Return type of the getter is different with the field type. getterMethod: " + getterDetails.getGetter() + ", fieldType: " + field.getType().getName());
        }
        CtMethod getterMethod = CtNewMethod.getter(getterDetails.getGetter().getName(), field);
        if (getterMethod.getDeclaringClass() != ctClass) {
            getterMethod = CtNewMethod.copy(getterMethod, ctClass, null);
        }
        ctClass.addMethod(getterMethod);
        CtClass ctInterface = getCtClass(getterTypeName);
        ctClass.addInterface(ctInterface);
    } catch (Exception e) {
        throw new InstrumentException("Failed to add getter: " + getterTypeName, e);
    }
}
Also used : CtClass(javassist.CtClass) CtField(javassist.CtField) GetterDetails(com.navercorp.pinpoint.profiler.instrument.GetterAnalyzer.GetterDetails) CtMethod(javassist.CtMethod) PinpointException(com.navercorp.pinpoint.exception.PinpointException) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException) IOException(java.io.IOException)

Example 4 with CtMethod

use of javassist.CtMethod in project pinpoint by naver.

the class JavassistClass method addSetter.

@Override
public void addSetter(String setterTypeName, String fieldName, boolean removeFinalFlag) throws InstrumentException {
    try {
        Class<?> setterType = pluginContext.injectClass(classLoader, setterTypeName);
        SetterAnalyzer setterAnalyzer = new SetterAnalyzer();
        SetterDetails setterDetails = setterAnalyzer.analyze(setterType);
        CtField field = ctClass.getField(fieldName);
        String fieldTypeName = JavaAssistUtils.javaClassNameToObjectName(setterDetails.getFieldType().getName());
        if (!field.getType().getName().equals(fieldTypeName)) {
            throw new IllegalArgumentException("Argument type of the setter is different with the field type. setterMethod: " + setterDetails.getSetter() + ", fieldType: " + field.getType().getName());
        }
        final int originalModifiers = field.getModifiers();
        if (Modifier.isStatic(originalModifiers)) {
            throw new IllegalArgumentException("Cannot add setter to static fields. setterMethod: " + setterDetails.getSetter().getName() + ", fieldName: " + fieldName);
        }
        boolean finalRemoved = false;
        if (Modifier.isFinal(originalModifiers)) {
            if (!removeFinalFlag) {
                throw new IllegalArgumentException("Cannot add setter to final field. setterMethod: " + setterDetails.getSetter().getName() + ", fieldName: " + fieldName);
            } else {
                final int modifiersWithFinalRemoved = Modifier.clear(originalModifiers, Modifier.FINAL);
                field.setModifiers(modifiersWithFinalRemoved);
                finalRemoved = true;
            }
        }
        try {
            CtMethod setterMethod = CtNewMethod.setter(setterDetails.getSetter().getName(), field);
            if (setterMethod.getDeclaringClass() != ctClass) {
                setterMethod = CtNewMethod.copy(setterMethod, ctClass, null);
            }
            ctClass.addMethod(setterMethod);
            CtClass ctInterface = getCtClass(setterTypeName);
            ctClass.addInterface(ctInterface);
        } catch (Exception e) {
            if (finalRemoved) {
                field.setModifiers(originalModifiers);
            }
            throw e;
        }
    } catch (Exception e) {
        throw new InstrumentException("Failed to add setter: " + setterTypeName, e);
    }
}
Also used : CtClass(javassist.CtClass) SetterDetails(com.navercorp.pinpoint.profiler.instrument.SetterAnalyzer.SetterDetails) CtField(javassist.CtField) CtMethod(javassist.CtMethod) PinpointException(com.navercorp.pinpoint.exception.PinpointException) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException) IOException(java.io.IOException)

Example 5 with CtMethod

use of javassist.CtMethod in project pinpoint by naver.

the class JavaAssistTest method genericTest.

@Test
public void genericTest() throws NotFoundException {
    CtClass testClass = pool.get("com.navercorp.pinpoint.test.javasssit.TestClass");
    //        CtMethod setb = testClass.getMethod("setb");
    CtMethod[] declaredMethods = testClass.getDeclaredMethods();
    for (CtMethod declaredMethod : declaredMethods) {
        logger.debug(declaredMethod.toString());
        logger.debug(declaredMethod.getGenericSignature());
        logger.debug(declaredMethod.getSignature());
        logger.debug("paramTypes:{}", Arrays.toString(declaredMethod.getParameterTypes()));
        logger.debug(declaredMethod.getMethodInfo2().getDescriptor());
        logger.debug(declaredMethod.getMethodInfo().getDescriptor());
    //            logger.debug(declaredMethod.());
    }
    CtMethod setb = testClass.getDeclaredMethod("setA", new CtClass[] { pool.get("int") });
    logger.debug(setb.toString());
    CtMethod setStringArray = testClass.getDeclaredMethod("setStringArray", new CtClass[] { pool.get("java.lang.String[]") });
    logger.debug(setStringArray.toString());
}
Also used : CtClass(javassist.CtClass) CtMethod(javassist.CtMethod) Test(org.junit.Test)

Aggregations

CtMethod (javassist.CtMethod)70 CtClass (javassist.CtClass)42 CannotCompileException (javassist.CannotCompileException)20 NotFoundException (javassist.NotFoundException)20 ClassPool (javassist.ClassPool)16 CtField (javassist.CtField)14 Test (org.junit.Test)12 IOException (java.io.IOException)10 InitMethod (com.googlecode.gwt.test.patchers.InitMethod)6 Method (java.lang.reflect.Method)5 CtConstructor (javassist.CtConstructor)5 EnhancementException (org.hibernate.bytecode.enhance.spi.EnhancementException)4 GwtTestPatchException (com.googlecode.gwt.test.exceptions.GwtTestPatchException)3 PinpointException (com.navercorp.pinpoint.exception.PinpointException)3 File (java.io.File)3 FileNotFoundException (java.io.FileNotFoundException)3 ArrayList (java.util.ArrayList)3 PatchMethod (com.googlecode.gwt.test.patchers.PatchMethod)2 FileFilter (java.io.FileFilter)2 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)2