Search in sources :

Example 6 with ClassWriter

use of org.apache.xbean.asm9.ClassWriter in project component-runtime by Talend.

the class ProxyGenerator method generateProxy.

public Class<?> generateProxy(final ClassLoader loader, final Class<?> classToProxy, final String plugin, final String key) {
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    final String proxyClassName = fixPreservedPackages((classToProxy.getSigners() != null ? getSignedClassProxyName(classToProxy) : classToProxy.getName()) + "$$TalendServiceProxy");
    final String classFileName = proxyClassName.replace('.', '/');
    final String[] interfaceNames = { Type.getInternalName(Serializable.class) };
    final String superClassName = Type.getInternalName(classToProxy);
    cw.visit(findJavaVersion(classToProxy), ACC_PUBLIC + ACC_SUPER + ACC_SYNTHETIC, classFileName, null, superClassName, interfaceNames);
    cw.visitSource(classFileName + ".java", null);
    if (!Serializable.class.isAssignableFrom(classToProxy)) {
        try {
            classToProxy.getMethod("writeReplace");
        } catch (final NoSuchMethodException e) {
            createSerialisation(cw, plugin, key);
        }
    }
    final boolean hasInterceptors = hasInterceptors(classToProxy);
    if (hasInterceptors) {
        cw.visitField(ACC_PRIVATE, FIELD_INTERCEPTOR_HANDLER, Type.getDescriptor(InterceptorHandler.class), null, null).visitEnd();
        cw.visitField(ACC_PRIVATE | ACC_STATIC, FIELD_INTERCEPTED_METHODS, Type.getDescriptor(Method[].class), null, null).visitEnd();
    }
    createConstructor(cw, classToProxy, superClassName, classFileName, Stream.of(classToProxy.getDeclaredConstructors()).filter(c -> {
        final int modifiers = c.getModifiers();
        return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers);
    }).sorted((o1, o2) -> {
        // prefer public constructor and then the smallest parameter count
        final int mod1 = o1.getModifiers();
        final int mod2 = o2.getModifiers();
        if (Modifier.isProtected(mod1) && !Modifier.isPublic(mod2)) {
            return 1;
        }
        if (Modifier.isProtected(mod2) && !Modifier.isPublic(mod1)) {
            return -1;
        }
        return o1.getParameterCount() - o2.getParameterCount();
    }).findFirst().orElseThrow(() -> new IllegalArgumentException(classToProxy + " has no default constructor, put at least a protected one")), hasInterceptors);
    final Method[] interceptedMethods;
    if (hasInterceptors) {
        final Collection<Annotation> globalInterceptors = Stream.of(classToProxy.getAnnotations()).filter(this::isInterceptor).collect(toList());
        final AtomicInteger methodIndex = new AtomicInteger();
        interceptedMethods = Stream.of(classToProxy.getMethods()).filter(m -> !"<init>".equals(m.getName()) && (!globalInterceptors.isEmpty() || Stream.of(m.getAnnotations()).anyMatch(this::isInterceptor))).peek(method -> delegateMethod(cw, method, classFileName, methodIndex.getAndIncrement())).toArray(Method[]::new);
    } else {
        interceptedMethods = null;
    }
    final Class<Object> objectClass = Unsafes.defineAndLoadClass(loader, proxyClassName, cw.toByteArray());
    if (hasInterceptors) {
        try {
            final Field interceptedMethodsField = objectClass.getDeclaredField(FIELD_INTERCEPTED_METHODS);
            interceptedMethodsField.setAccessible(true);
            interceptedMethodsField.set(null, interceptedMethods);
        } catch (final Exception e) {
            throw new IllegalStateException(e);
        }
    }
    return objectClass;
}
Also used : ILOAD(org.apache.xbean.asm6.Opcodes.ILOAD) IRETURN(org.apache.xbean.asm6.Opcodes.IRETURN) Intercepts(org.talend.sdk.component.api.service.interceptor.Intercepts) ClassReader(org.apache.xbean.asm6.ClassReader) LRETURN(org.apache.xbean.asm6.Opcodes.LRETURN) V1_8(org.apache.xbean.asm6.Opcodes.V1_8) Type(org.apache.xbean.asm6.Type) ACC_PUBLIC(org.apache.xbean.asm6.Opcodes.ACC_PUBLIC) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ACC_PRIVATE(org.apache.xbean.asm6.Opcodes.ACC_PRIVATE) ALOAD(org.apache.xbean.asm6.Opcodes.ALOAD) ACC_SUPER(org.apache.xbean.asm6.Opcodes.ACC_SUPER) Method(java.lang.reflect.Method) IFEQ(org.apache.xbean.asm6.Opcodes.IFEQ) PUTFIELD(org.apache.xbean.asm6.Opcodes.PUTFIELD) GETFIELD(org.apache.xbean.asm6.Opcodes.GETFIELD) BIPUSH(org.apache.xbean.asm6.Opcodes.BIPUSH) ACC_SYNTHETIC(org.apache.xbean.asm6.Opcodes.ACC_SYNTHETIC) Collection(java.util.Collection) NEW(org.apache.xbean.asm6.Opcodes.NEW) LLOAD(org.apache.xbean.asm6.Opcodes.LLOAD) Serializable(java.io.Serializable) AASTORE(org.apache.xbean.asm6.Opcodes.AASTORE) ACC_VARARGS(org.apache.xbean.asm6.Opcodes.ACC_VARARGS) Stream(java.util.stream.Stream) EmptyVisitor(org.apache.xbean.asm6.shade.commons.EmptyVisitor) INVOKEVIRTUAL(org.apache.xbean.asm6.Opcodes.INVOKEVIRTUAL) Modifier(java.lang.reflect.Modifier) SIPUSH(org.apache.xbean.asm6.Opcodes.SIPUSH) Annotation(java.lang.annotation.Annotation) FRETURN(org.apache.xbean.asm6.Opcodes.FRETURN) CHECKCAST(org.apache.xbean.asm6.Opcodes.CHECKCAST) ASTORE(org.apache.xbean.asm6.Opcodes.ASTORE) InterceptorHandler(org.talend.sdk.component.api.service.interceptor.InterceptorHandler) DLOAD(org.apache.xbean.asm6.Opcodes.DLOAD) INVOKESTATIC(org.apache.xbean.asm6.Opcodes.INVOKESTATIC) Label(org.apache.xbean.asm6.Label) ATHROW(org.apache.xbean.asm6.Opcodes.ATHROW) Constructor(java.lang.reflect.Constructor) ANEWARRAY(org.apache.xbean.asm6.Opcodes.ANEWARRAY) AALOAD(org.apache.xbean.asm6.Opcodes.AALOAD) ACC_PROTECTED(org.apache.xbean.asm6.Opcodes.ACC_PROTECTED) POP(org.apache.xbean.asm6.Opcodes.POP) ICONST_0(org.apache.xbean.asm6.Opcodes.ICONST_0) ICONST_2(org.apache.xbean.asm6.Opcodes.ICONST_2) SKIP_DEBUG(org.apache.xbean.asm6.ClassReader.SKIP_DEBUG) ICONST_1(org.apache.xbean.asm6.Opcodes.ICONST_1) INVOKEINTERFACE(org.apache.xbean.asm6.Opcodes.INVOKEINTERFACE) INVOKESPECIAL(org.apache.xbean.asm6.Opcodes.INVOKESPECIAL) ICONST_4(org.apache.xbean.asm6.Opcodes.ICONST_4) ICONST_3(org.apache.xbean.asm6.Opcodes.ICONST_3) FLOAD(org.apache.xbean.asm6.Opcodes.FLOAD) ACONST_NULL(org.apache.xbean.asm6.Opcodes.ACONST_NULL) RETURN(org.apache.xbean.asm6.Opcodes.RETURN) Field(java.lang.reflect.Field) MethodVisitor(org.apache.xbean.asm6.MethodVisitor) ACC_STATIC(org.apache.xbean.asm6.Opcodes.ACC_STATIC) ObjectStreamException(java.io.ObjectStreamException) Collectors.toList(java.util.stream.Collectors.toList) DRETURN(org.apache.xbean.asm6.Opcodes.DRETURN) GETSTATIC(org.apache.xbean.asm6.Opcodes.GETSTATIC) DUP(org.apache.xbean.asm6.Opcodes.DUP) ClassWriter(org.apache.xbean.asm6.ClassWriter) ICONST_5(org.apache.xbean.asm6.Opcodes.ICONST_5) ARETURN(org.apache.xbean.asm6.Opcodes.ARETURN) AllArgsConstructor(lombok.AllArgsConstructor) InputStream(java.io.InputStream) Serializable(java.io.Serializable) Method(java.lang.reflect.Method) ClassWriter(org.apache.xbean.asm6.ClassWriter) Annotation(java.lang.annotation.Annotation) ObjectStreamException(java.io.ObjectStreamException) Field(java.lang.reflect.Field) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 7 with ClassWriter

use of org.apache.xbean.asm9.ClassWriter in project component-runtime by Talend.

the class RepositoryModelBuilderTest method createChainPlugin.

private File createChainPlugin(final File dir, final String plugin) {
    final File target = new File(dir, plugin);
    try (final JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(target))) {
        final String packageName = toPackage(target.getParentFile().getParentFile().getName()).replace(".", "/");
        final String sourcePackage = "org/talend/test";
        final String fromPack = sourcePackage.replace('/', '.');
        final String toPack = packageName.replace('.', '/');
        final File root = new File(jarLocation(getClass()), sourcePackage);
        ofNullable(root.listFiles()).map(Stream::of).orElseGet(Stream::empty).filter(c -> c.getName().endsWith(".class")).forEach(clazz -> {
            try (final InputStream is = new FileInputStream(clazz)) {
                final ClassReader reader = new ClassReader(is);
                final ClassWriter writer = new ClassWriter(COMPUTE_FRAMES);
                reader.accept(new ClassRemapper(writer, new Remapper() {

                    @Override
                    public String map(final String key) {
                        return key.replace(sourcePackage, toPack).replace(fromPack, packageName);
                    }
                }), EXPAND_FRAMES);
                outputStream.putNextEntry(new JarEntry(toPack + '/' + clazz.getName()));
                outputStream.write(writer.toByteArray());
            } catch (final IOException e) {
                fail(e.getMessage());
            }
        });
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
    return target;
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) ComponentFamilyMeta(org.talend.sdk.component.runtime.manager.ComponentFamilyMeta) HashMap(java.util.HashMap) ClassReader(org.apache.xbean.asm6.ClassReader) Collections.singletonList(java.util.Collections.singletonList) DataStore1(org.talend.test.DataStore1) JarEntry(java.util.jar.JarEntry) Collections.singleton(java.util.Collections.singleton) ClassRemapper(org.apache.xbean.asm6.commons.ClassRemapper) WithTemporaryFolder(org.talend.sdk.component.junit.base.junit5.WithTemporaryFolder) ParameterModelService(org.talend.sdk.component.runtime.manager.reflect.ParameterModelService) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) EXPAND_FRAMES(org.apache.xbean.asm6.ClassReader.EXPAND_FRAMES) JarOutputStream(java.util.jar.JarOutputStream) Remapper(org.apache.xbean.asm6.commons.Remapper) ParameterMeta(org.talend.sdk.component.runtime.manager.ParameterMeta) Collections.emptyMap(java.util.Collections.emptyMap) COMPUTE_FRAMES(org.apache.xbean.asm6.ClassWriter.COMPUTE_FRAMES) Container(org.talend.sdk.component.container.Container) Collections.emptyList(java.util.Collections.emptyList) Optional.ofNullable(java.util.Optional.ofNullable) FileOutputStream(java.io.FileOutputStream) WrappingStore(org.talend.test.WrappingStore) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IdGenerator(org.talend.sdk.component.runtime.manager.util.IdGenerator) File(java.io.File) TestInfo(org.junit.jupiter.api.TestInfo) RepositoryModel(org.talend.sdk.component.design.extension.RepositoryModel) Test(org.junit.jupiter.api.Test) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) Stream(java.util.stream.Stream) TemporaryFolder(org.talend.sdk.component.junit.base.junit5.TemporaryFolder) JarLocation.jarLocation(org.apache.ziplock.JarLocation.jarLocation) ClassWriter(org.apache.xbean.asm6.ClassWriter) ComponentManager(org.talend.sdk.component.runtime.manager.ComponentManager) MigrationHandlerFactory(org.talend.sdk.component.runtime.manager.reflect.MigrationHandlerFactory) ReflectionService(org.talend.sdk.component.runtime.manager.reflect.ReflectionService) InputStream(java.io.InputStream) PartitionMapper1(org.talend.test.PartitionMapper1) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JarOutputStream(java.util.jar.JarOutputStream) IOException(java.io.IOException) JarEntry(java.util.jar.JarEntry) ClassRemapper(org.apache.xbean.asm6.commons.ClassRemapper) FileInputStream(java.io.FileInputStream) ClassWriter(org.apache.xbean.asm6.ClassWriter) ClassRemapper(org.apache.xbean.asm6.commons.ClassRemapper) Remapper(org.apache.xbean.asm6.commons.Remapper) FileOutputStream(java.io.FileOutputStream) ClassReader(org.apache.xbean.asm6.ClassReader) JarOutputStream(java.util.jar.JarOutputStream) FileOutputStream(java.io.FileOutputStream) FileInputStream(java.io.FileInputStream) Stream(java.util.stream.Stream) InputStream(java.io.InputStream) File(java.io.File)

Example 8 with ClassWriter

use of org.apache.xbean.asm9.ClassWriter in project tomee by apache.

the class ValidationGenerator method generate.

public byte[] generate() throws ProxyGenerationException {
    generatedMethods.clear();
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    final String generatedClassName = getName().replace('.', '/');
    cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER, generatedClassName, null, "java/lang/Object", null);
    {
        // public constructor
        final MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        mv.visitInsn(RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    generateMethods(cw);
    /**
     * Read all parent classes and copy the public methods we need
     * into our new class.
     */
    Class current = clazz;
    while (current != null && !current.equals(Object.class)) {
        try {
            final ClassReader classReader = new ClassReader(DynamicSubclass.readClassFile(current));
            classReader.accept(new CopyMethodAnnotations(), ClassReader.SKIP_CODE);
        } catch (final IOException e) {
            throw new ProxyGenerationException(e);
        }
        current = current.getSuperclass();
    }
    return cw.toByteArray();
}
Also used : ProxyGenerationException(org.apache.openejb.util.proxy.ProxyGenerationException) ClassReader(org.apache.xbean.asm9.ClassReader) IOException(java.io.IOException) ClassWriter(org.apache.xbean.asm9.ClassWriter) MethodVisitor(org.apache.xbean.asm9.MethodVisitor)

Example 9 with ClassWriter

use of org.apache.xbean.asm9.ClassWriter in project tomee by apache.

the class ServiceClasspathTest method subclass.

public static File subclass(final Class<?> parent, final String subclassName) throws Exception {
    final String subclassNameInternal = subclassName.replace('.', '/');
    final byte[] bytes;
    {
        final ClassWriter cw = new ClassWriter(0);
        final String parentClassNameInternal = parent.getName().replace('.', '/');
        cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + ACC_SUPER, subclassNameInternal, null, parentClassNameInternal, null);
        final MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, parentClassNameInternal, "<init>", "()V", false);
        mv.visitInsn(RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
        cw.visitEnd();
        bytes = cw.toByteArray();
    }
    return Archive.archive().add(subclassNameInternal + ".class", bytes).asJar();
}
Also used : ClassWriter(org.apache.xbean.asm9.ClassWriter) MethodVisitor(org.apache.xbean.asm9.MethodVisitor)

Example 10 with ClassWriter

use of org.apache.xbean.asm9.ClassWriter in project tomee by apache.

the class JpaTest method addNewField.

public static byte[] addNewField(final byte[] origBytes) {
    final ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    final FieldAdderClassVisitor visitor = new FieldAdderClassVisitor(classWriter);
    final ClassReader classReader = new ClassReader(origBytes);
    classReader.accept(visitor, 0);
    return classWriter.toByteArray();
}
Also used : ClassReader(org.apache.xbean.asm9.ClassReader) ClassWriter(org.apache.xbean.asm9.ClassWriter)

Aggregations

MethodVisitor (org.apache.xbean.asm9.MethodVisitor)10 ClassWriter (org.apache.xbean.asm9.ClassWriter)8 ClassWriter (org.apache.xbean.asm6.ClassWriter)7 Method (java.lang.reflect.Method)6 IOException (java.io.IOException)5 InputStream (java.io.InputStream)4 HashMap (java.util.HashMap)4 List (java.util.List)4 Stream (java.util.stream.Stream)4 ZipEntry (java.util.zip.ZipEntry)4 ClassReader (org.apache.xbean.asm6.ClassReader)4 MethodVisitor (org.apache.xbean.asm6.MethodVisitor)4 File (java.io.File)3 FileInputStream (java.io.FileInputStream)3 FileOutputStream (java.io.FileOutputStream)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 Optional.ofNullable (java.util.Optional.ofNullable)3 JarEntry (java.util.jar.JarEntry)3 JarOutputStream (java.util.jar.JarOutputStream)3