Search in sources :

Example 16 with CtMethod

use of javassist.CtMethod in project hibernate-orm by hibernate.

the class PersistentAttributesHelper method getterOrNull.

private static CtMethod getterOrNull(CtClass containerClass, String propertyName) {
    for (CtMethod method : containerClass.getDeclaredMethods()) {
        try {
            // if the method has parameters, skip it
            if (method.isEmpty() || method.getParameterTypes().length != 0) {
                continue;
            }
        } catch (NotFoundException e) {
            continue;
        }
        final String methodName = method.getName();
        // try "get"
        if (methodName.startsWith("get")) {
            String testStdMethod = Introspector.decapitalize(methodName.substring(3));
            String testOldMethod = methodName.substring(3);
            if (testStdMethod.equals(propertyName) || testOldMethod.equals(propertyName)) {
                return method;
            }
        }
        // if not "get", then try "is"
        if (methodName.startsWith("is")) {
            String testStdMethod = Introspector.decapitalize(methodName.substring(2));
            String testOldMethod = methodName.substring(2);
            if (testStdMethod.equals(propertyName) || testOldMethod.equals(propertyName)) {
                return method;
            }
        }
    }
    return null;
}
Also used : NotFoundException(javassist.NotFoundException) CtMethod(javassist.CtMethod)

Example 17 with CtMethod

use of javassist.CtMethod in project powermock by powermock.

the class TestClassTransformer method forTestClass.

public static ForTestClass forTestClass(final Class<?> testClass) {
    return new ForTestClass() {

        @Override
        public RemovesTestMethodAnnotation removesTestMethodAnnotation(final Class<? extends Annotation> testMethodAnnotation) {
            return new RemovesTestMethodAnnotation() {

                @Override
                public TestClassTransformer fromMethods(final Collection<Method> testMethodsThatRunOnOtherClassLoaders) {
                    return new TestClassTransformer(testClass, testMethodAnnotation) {

                        /**
                             * Is lazily initilized because of
                             * AbstractTestSuiteChunkerImpl#chunkClass(Class)
                             */
                        Collection<String> methodsThatRunOnOtherClassLoaders;

                        @Override
                        boolean mustHaveTestAnnotationRemoved(CtMethod method) throws NotFoundException {
                            if (null == methodsThatRunOnOtherClassLoaders) {
                                /* This lazy initialization is necessary - see above */
                                methodsThatRunOnOtherClassLoaders = new HashSet<String>();
                                for (Method m : testMethodsThatRunOnOtherClassLoaders) {
                                    methodsThatRunOnOtherClassLoaders.add(signatureOf(m));
                                }
                                testMethodsThatRunOnOtherClassLoaders.clear();
                            }
                            return methodsThatRunOnOtherClassLoaders.contains(signatureOf(method));
                        }
                    };
                }

                @Override
                public TestClassTransformer fromAllMethodsExcept(Method singleMethodToRunOnTargetClassLoader) {
                    final String targetMethodSignature = signatureOf(singleMethodToRunOnTargetClassLoader);
                    return new TestClassTransformer(testClass, testMethodAnnotation) {

                        @Override
                        boolean mustHaveTestAnnotationRemoved(CtMethod method) throws Exception {
                            return !signatureOf(method).equals(targetMethodSignature);
                        }
                    };
                }
            };
        }
    };
}
Also used : Collection(java.util.Collection) CtClass(javassist.CtClass) IndicateReloadClass(org.powermock.core.IndicateReloadClass) CtMethod(javassist.CtMethod) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) CtMethod(javassist.CtMethod)

Example 18 with CtMethod

use of javassist.CtMethod in project powermock by powermock.

the class ClassMockTransformerTest method addSyntheticMethod.

private void addSyntheticMethod(ClassPool classPool, CtClass ctClass, String body) throws NotFoundException, CannotCompileException {
    CtMethod ctMethod = CtNewMethod.make(AccessFlag.SYNTHETIC, CtClass.voidType, SYNTHETIC_METHOD_NAME, new CtClass[] { classPool.get(String.class.getName()) }, null, body, ctClass);
    ctClass.addMethod(ctMethod);
    for (CtMethod method : ctClass.getDeclaredMethods()) {
        if (!method.getName().equals(SYNTHETIC_METHOD_NAME)) {
            method.insertBefore("$synth(\"" + method.getLongName() + "\");");
        }
    }
}
Also used : CtMethod(javassist.CtMethod)

Example 19 with CtMethod

use of javassist.CtMethod in project powermock by powermock.

the class AbstractMainMockTransformer method ensureJvmMethodSizeLimit.

/**
     * According to JVM specification method size must be lower than 65536 bytes.
     * When that limit is exceeded class loader will fail to load the class.
     * Since instrumentation can increase method size significantly it must be
     * ensured that JVM limit is not exceeded.
     * <p/>
     * When the limit is exceeded method's body is replaced by exception throw.
     * Method is then instrumented again to allow mocking and suppression.
     *
     * @see <a href="http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.3">JVM specification</a>
     */
protected CtClass ensureJvmMethodSizeLimit(CtClass clazz) throws CannotCompileException, NotFoundException {
    for (CtMethod method : clazz.getDeclaredMethods()) {
        if (isMethodSizeExceeded(method)) {
            String code = "{throw new IllegalAccessException(\"" + "Method was too large and after instrumentation exceeded JVM limit. " + "PowerMock modified the method to allow JVM to load the class. " + "You can use PowerMock API to suppress or mock this method behaviour." + "\");}";
            method.setBody(code);
            modifyMethod(method);
        }
    }
    return clazz;
}
Also used : CtMethod(javassist.CtMethod)

Example 20 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)

Aggregations

CtMethod (javassist.CtMethod)76 CtClass (javassist.CtClass)46 NotFoundException (javassist.NotFoundException)23 CannotCompileException (javassist.CannotCompileException)20 ClassPool (javassist.ClassPool)18 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