Search in sources :

Example 31 with CtClass

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

the class MapProxyTool method generate.

/**
	 * Protected for test only
	 */
protected static Class generate(String className, Map<String, Class<?>> properties) {
    try {
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.makeClass(className);
        cc.addInterface(resolveCtClass(Serializable.class));
        cc.addField(new CtField(resolveCtClass(Map.class), "theMap", cc));
        cc.addConstructor(generateConstructor(className, cc));
        for (Entry<String, Class<?>> entry : properties.entrySet()) {
            // add getter
            cc.addMethod(generateGetter(cc, entry.getKey(), entry.getValue()));
            // add setter
            cc.addMethod(generateSetter(cc, entry.getKey(), entry.getValue()));
        }
        return cc.toClass();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : CtClass(javassist.CtClass) Serializable(java.io.Serializable) CtField(javassist.CtField) ClassPool(javassist.ClassPool) CtClass(javassist.CtClass) CannotCompileException(javassist.CannotCompileException) NotFoundException(javassist.NotFoundException) ClassLoadingException(org.hibernate.boot.registry.classloading.spi.ClassLoadingException)

Example 32 with CtClass

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

the class EnhancerTestUtils method enhanceAndDecompile.

/**
	 * method that performs the enhancement of a class
	 * also checks the signature of enhanced entities methods using 'javap' decompiler
	 */
public static Class<?> enhanceAndDecompile(Class<?> classToEnhance, ClassLoader cl) throws Exception {
    CtClass entityCtClass = generateCtClassForAnEntity(classToEnhance);
    byte[] original = entityCtClass.toBytecode();
    byte[] enhanced = Environment.getBytecodeProvider().getEnhancer(new EnhancerTestContext()).enhance(entityCtClass.getName(), original);
    assertFalse("entity was not enhanced", enhanced == null);
    log.infof("enhanced entity [%s]", entityCtClass.getName());
    ClassPool cp = new ClassPool(false);
    cp.appendClassPath(new LoaderClassPath(cl));
    CtClass enhancedCtClass = cp.makeClass(new ByteArrayInputStream(enhanced));
    enhancedCtClass.debugWriteFile(workingDir);
    DecompileUtils.decompileDumpedClass(workingDir, classToEnhance.getName());
    Class<?> enhancedClass = enhancedCtClass.toClass(cl, EnhancerTestUtils.class.getProtectionDomain());
    assertNotNull(enhancedClass);
    return enhancedClass;
}
Also used : CtClass(javassist.CtClass) ByteArrayInputStream(java.io.ByteArrayInputStream) ClassPool(javassist.ClassPool) LoaderClassPath(javassist.LoaderClassPath)

Example 33 with CtClass

use of javassist.CtClass 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 34 with CtClass

use of javassist.CtClass 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 35 with CtClass

use of javassist.CtClass in project pinpoint by naver.

the class JavaAssistTest method innerClass.

@Test
public void innerClass() throws NotFoundException {
    CtClass testClass = pool.get("com.navercorp.pinpoint.test.javasssit.TestClass");
    logger.debug(testClass.toString());
    CtClass[] nestedClasses = testClass.getNestedClasses();
    for (CtClass nested : nestedClasses) {
        logger.debug("nestedClass:{}", nested);
    }
    CtClass innerClass = pool.get("com.navercorp.pinpoint.test.javasssit.TestClass$InnerClass");
    logger.debug("{}", innerClass);
    CtClass class1 = pool.get("com.navercorp.pinpoint.test.javasssit.TestClass$1");
    logger.debug("{}", class1);
}
Also used : CtClass(javassist.CtClass) Test(org.junit.Test)

Aggregations

CtClass (javassist.CtClass)121 CtMethod (javassist.CtMethod)46 ClassPool (javassist.ClassPool)37 NotFoundException (javassist.NotFoundException)35 Test (org.junit.Test)32 CannotCompileException (javassist.CannotCompileException)23 CtField (javassist.CtField)20 IOException (java.io.IOException)11 CtConstructor (javassist.CtConstructor)8 Method (java.lang.reflect.Method)7 ArrayList (java.util.ArrayList)6 CtMethodJavaWriter (com.github.stephanenicolas.afterburner.inserts.CtMethodJavaWriter)4 FileNotFoundException (java.io.FileNotFoundException)4 LoaderClassPath (javassist.LoaderClassPath)4 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)4 CodeAttribute (javassist.bytecode.CodeAttribute)4 ConstPool (javassist.bytecode.ConstPool)4 GwtTestPatchException (com.googlecode.gwt.test.exceptions.GwtTestPatchException)3 PinpointException (com.navercorp.pinpoint.exception.PinpointException)3 NamedClassPool (com.navercorp.pinpoint.profiler.instrument.classpool.NamedClassPool)3