Example usage for org.objectweb.asm AnnotationVisitor AnnotationVisitor

List of usage examples for org.objectweb.asm AnnotationVisitor AnnotationVisitor

Introduction

In this page you can find the example usage for org.objectweb.asm AnnotationVisitor AnnotationVisitor.

Prototype

public AnnotationVisitor(final int api, final AnnotationVisitor annotationVisitor) 

Source Link

Document

Constructs a new AnnotationVisitor .

Usage

From source file:cn.annoreg.asm.DelegateGenerator.java

License:Open Source License

public static MethodVisitor generateStaticMethod(ClassVisitor parentClass, MethodVisitor parent,
        String className, String methodName, String desc, final Side side) {

    //This method is a little bit complicated.
    //We need to generate a delegate class implementing NetworkCallDelegate and a redirect
    //the code that originally generated here in parent, into the delegate class,
    //by returning a MethodVisitor under the ClassVisitor of the delegate class.
    //Besides, we should generate a call to NetworkCallManager into parent.

    //Above is the original method. Now it has a little bit change. To allow private call in
    //here, we need to generate the delegate method in this class instead of in a delegate class.
    //We make the delegate method public so that the delegate class can call it.

    //delegateName is a string used by both sides to identify a network-call delegate.
    final String delegateName = className + ":" + methodName + ":" + desc;
    final Type[] args = Type.getArgumentTypes(desc);
    final Type ret = Type.getReturnType(desc);

    //Check types
    for (Type t : args) {
        //TODO support these types
        if (!t.getDescriptor().startsWith("L") && !t.getDescriptor().startsWith("[")) {
            throw new RuntimeException("Unsupported argument type in network call. in method " + methodName
                    + ", " + t.getDescriptor());
        }/*  w w w . j a va2 s .  c o  m*/
    }
    if (!ret.equals(Type.VOID_TYPE)) {
        throw new RuntimeException(
                "Unsupported return value type in network call. " + "Only void is supported.");
    }

    //Generate call to NetworkCallManager in parent.
    parent.visitCode();
    //First parameter
    parent.visitLdcInsn(delegateName);
    //Second parameter: object array
    pushIntegerConst(parent, args.length); //array size
    parent.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(Object.class));
    for (int i = 0; i < args.length; ++i) {
        parent.visitInsn(Opcodes.DUP);
        pushIntegerConst(parent, i);
        parent.visitVarInsn(Opcodes.ALOAD, i);
        parent.visitInsn(Opcodes.AASTORE);
    }
    //Call cn.annoreg.mc.network.NetworkCallManager.onNetworkCall
    parent.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(NetworkCallManager.class),
            "onNetworkCall",
            Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class), Type.getType(Object[].class)));
    parent.visitInsn(Opcodes.RETURN);
    parent.visitMaxs(5, args.length);
    parent.visitEnd();

    //Create delegate object.
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    final String delegateId = Integer.toString(delegateNextID++);
    final Type delegateClassType = Type.getType("cn/annoreg/asm/NetworkCallDelegate_" + delegateId);
    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, delegateClassType.getInternalName(), null,
            Type.getInternalName(Object.class),
            new String[] { Type.getInternalName(NetworkCallDelegate.class) });
    //package cn.annoreg.asm;
    //class NetworkCallDelegate_? implements NetworkCallDelegate {
    {
        MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V");
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    //public NetworkCallDelegate_?() {}

    final String delegateFunctionName = methodName + "_delegate_" + delegateId;
    {
        MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke",
                Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object[].class)), null, null);
        mv.visitCode();
        for (int i = 0; i < args.length; ++i) {
            mv.visitVarInsn(Opcodes.ALOAD, 1); //0 is this
            pushIntegerConst(mv, i);
            mv.visitInsn(Opcodes.AALOAD);
            mv.visitTypeInsn(Opcodes.CHECKCAST, args[i].getInternalName());
        }
        mv.visitMethodInsn(Opcodes.INVOKESTATIC,
                //delegateClassType.getInternalName(), //changed to original class
                className.replace('.', '/'), delegateFunctionName, desc);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(args.length + 2, 2);
        mv.visitEnd();
    }
    //@Override public void invoke(Object[] args) {
    //    xxxx.xxxx_delegated_xxx((Type0) args[0], (Type1) args[1], ...);
    //}

    //The returned MethodVisitor will visit the original version of the method,
    //including its annotation, where we can get StorageOptions.
    return new MethodVisitor(Opcodes.ASM4, parentClass.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC,
            delegateFunctionName, desc, null, null)) {

        //Remember storage options for each argument
        StorageOption.Option[] options = new StorageOption.Option[args.length];
        int targetIndex = -1;
        StorageOption.Target.RangeOption range = StorageOption.Target.RangeOption.SINGLE;
        double sendRange = -1;

        {
            for (int i = 0; i < options.length; ++i) {
                options[i] = StorageOption.Option.NULL; //set default value
            }
        }

        @Override
        public AnnotationVisitor visitParameterAnnotation(final int parameter, String desc, boolean visible) {
            Type type = Type.getType(desc);
            if (type.equals(Type.getType(StorageOption.Data.class))) {
                options[parameter] = StorageOption.Option.DATA;
            } else if (type.equals(Type.getType(StorageOption.Instance.class))) {
                //INSTANCE as defualt
                options[parameter] = StorageOption.Option.INSTANCE;

                //Change to NULLABLE_INSTANCE if nullable set to true
                return new AnnotationVisitor(this.api,
                        super.visitParameterAnnotation(parameter, desc, visible)) {
                    @Override
                    public void visit(String name, Object value) {
                        if (name.equals("nullable")) {
                            if ((Boolean) value == true) {
                                options[parameter] = StorageOption.Option.NULLABLE_INSTANCE;
                            }
                        }
                        super.visit(name, value);
                    }
                };
            } else if (type.equals(Type.getType(StorageOption.Update.class))) {
                options[parameter] = StorageOption.Option.UPDATE;
            } else if (type.equals(Type.getType(StorageOption.Null.class))) {
                options[parameter] = StorageOption.Option.NULL;
            } else if (type.equals(Type.getType(StorageOption.Target.class))) {
                if (!args[parameter].equals(Type.getType(EntityPlayer.class))) {
                    throw new RuntimeException("Target annotation can only be used on EntityPlayer.");
                }
                if (targetIndex != -1) {
                    throw new RuntimeException("You can not specify multiple targets.");
                }
                options[parameter] = StorageOption.Option.INSTANCE;
                targetIndex = parameter;
                return new AnnotationVisitor(this.api,
                        super.visitParameterAnnotation(parameter, desc, visible)) {
                    @Override
                    public void visitEnum(String name, String desc, String value) {
                        super.visitEnum(name, desc, value);
                        range = StorageOption.Target.RangeOption.valueOf(value);
                    }
                };
            } else if (type.equals(Type.getType(StorageOption.RangedTarget.class))) {
                if (targetIndex != -1) {
                    throw new RuntimeException("You can not specify multiple targets.");
                }
                range = null;
                targetIndex = parameter;
                return new AnnotationVisitor(this.api,
                        super.visitParameterAnnotation(parameter, desc, visible)) {
                    @Override
                    public void visit(String name, Object value) {
                        super.visit(name, value);
                        sendRange = (double) value;
                    }
                };
            }
            return super.visitParameterAnnotation(parameter, desc, visible);
        }

        @Override
        public void visitEnd() {
            super.visitEnd();
            //This is the last method in the delegate class.
            //Finish the class and do the registration.
            cw.visitEnd();
            try {
                Class<?> clazz = classLoader.defineClass(delegateClassType.getClassName(), cw.toByteArray());
                NetworkCallDelegate delegateObj = (NetworkCallDelegate) clazz.newInstance();
                if (side == Side.CLIENT) {
                    NetworkCallManager.registerClientDelegateClass(delegateName, delegateObj, options,
                            targetIndex, range, sendRange);
                } else {
                    NetworkCallManager.registerServerDelegateClass(delegateName, delegateObj, options);
                }
            } catch (Throwable e) {
                throw new RuntimeException("Can not create delegate for network call.", e);
            }
        }
    };
    //public static void delegated(Type0 arg0, Type1, arg1, ...) {
    //    //Code generated by caller.
    //}
    //}
}

From source file:cn.annoreg.asm.DelegateGenerator.java

License:Open Source License

public static MethodVisitor generateNonStaticMethod(ClassVisitor parentClass, MethodVisitor parent,
        String className, String methodName, String desc, final Side side) {

    //convert desc to a non-static method form
    String nonstaticDesc;// ww w.  j a v a2s  .  c  om
    {
        Type staticType = Type.getMethodType(desc);
        Type retType = staticType.getReturnType();
        Type[] argsType = staticType.getArgumentTypes();
        Type[] argsTypeWithThis = new Type[argsType.length + 1];
        argsTypeWithThis[0] = Type.getType('L' + className.replace('.', '/') + ';');
        System.arraycopy(argsType, 0, argsTypeWithThis, 1, argsType.length);
        nonstaticDesc = Type.getMethodDescriptor(retType, argsTypeWithThis);
    }

    //delegateName is a string used by both sides to identify a network-call delegate.
    final String delegateName = className + ":" + methodName + ":" + desc;
    final Type[] args = Type.getArgumentTypes(nonstaticDesc);
    final Type ret = Type.getReturnType(nonstaticDesc);

    //Check types
    for (Type t : args) {
        //TODO support these types
        if (!t.getDescriptor().startsWith("L") && !t.getDescriptor().startsWith("[")) {
            throw new RuntimeException("Unsupported argument type in network call. ");
        }
    }
    if (!ret.equals(Type.VOID_TYPE)) {
        throw new RuntimeException(
                "Unsupported return value type in network call. " + "Only void is supported.");
    }

    //Generate call to NetworkCallManager in parent.
    parent.visitCode();
    //First parameter
    parent.visitLdcInsn(delegateName);
    //Second parameter: object array
    pushIntegerConst(parent, args.length); //this (0) has been included
    parent.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
    for (int i = 0; i < args.length; ++i) {
        parent.visitInsn(Opcodes.DUP);
        pushIntegerConst(parent, i);
        parent.visitVarInsn(Opcodes.ALOAD, i);
        parent.visitInsn(Opcodes.AASTORE);
    }
    //Call cn.annoreg.mc.network.NetworkCallManager.onNetworkCall
    parent.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(NetworkCallManager.class),
            "onNetworkCall", "(Ljava/lang/String;[Ljava/lang/Object;)V");
    parent.visitInsn(Opcodes.RETURN);
    parent.visitMaxs(5, args.length);
    parent.visitEnd();

    //Create delegate object.
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    final String delegateId = Integer.toString(delegateNextID++);
    final Type delegateClassType = Type.getType("cn/annoreg/asm/NetworkCallDelegate_" + delegateId);
    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, delegateClassType.getInternalName(), null,
            Type.getInternalName(Object.class),
            new String[] { Type.getInternalName(NetworkCallDelegate.class) });
    //package cn.annoreg.asm;
    //class NetworkCallDelegate_? implements NetworkCallDelegate {
    {
        MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V");
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    //public NetworkCallDelegate_?() {}

    final String delegateMethodName = methodName + "_delegate_" + delegateId;
    {
        MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke",
                Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object[].class)), null, null);
        mv.visitCode();

        //check if this is null
        mv.visitVarInsn(Opcodes.ALOAD, 1); //0 is this
        pushIntegerConst(mv, 0);
        mv.visitInsn(Opcodes.AALOAD);
        Label lblEnd = new Label();
        mv.visitJumpInsn(Opcodes.IFNULL, lblEnd);

        for (int i = 0; i < args.length; ++i) {
            mv.visitVarInsn(Opcodes.ALOAD, 1); //0 is this
            pushIntegerConst(mv, i);
            mv.visitInsn(Opcodes.AALOAD);
            mv.visitTypeInsn(Opcodes.CHECKCAST, args[i].getInternalName());
        }
        mv.visitMethodInsn(Opcodes.INVOKESTATIC,
                //delegateClassType.getInternalName(), 
                className.replace('.', '/'), delegateMethodName, nonstaticDesc);

        mv.visitLabel(lblEnd);

        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(args.length + 2, 2);
        mv.visitEnd();
    }
    //@Override public void invoke(Object[] args) {
    //    delegated((Type0) args[0], (Type1) args[1], ...);
    //}

    //The returned MethodVisitor will visit the original version of the method,
    //including its annotation, where we can get StorageOptions.
    return new MethodVisitor(Opcodes.ASM4, parentClass.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC,
            delegateMethodName, nonstaticDesc, null, null)) {

        //Remember storage options for each argument
        StorageOption.Option[] options = new StorageOption.Option[args.length];
        int targetIndex = -1;
        double sendRange = -1;
        StorageOption.Target.RangeOption range = StorageOption.Target.RangeOption.SINGLE;

        {
            for (int i = 0; i < options.length; ++i) {
                options[i] = StorageOption.Option.NULL; //set default value
            }
            options[0] = StorageOption.Option.INSTANCE;
        }

        @Override
        public AnnotationVisitor visitParameterAnnotation(int parameter_in_func, String desc, boolean visible) {
            final int parameter = parameter_in_func + 1; //skip this
            Type type = Type.getType(desc);
            if (type.equals(Type.getType(StorageOption.Data.class))) {
                options[parameter] = StorageOption.Option.DATA;
            } else if (type.equals(Type.getType(StorageOption.Instance.class))) {
                //INSTANCE as defualt
                options[parameter] = StorageOption.Option.INSTANCE;

                //Change to NULLABLE_INSTANCE if nullable set to true
                return new AnnotationVisitor(this.api,
                        super.visitParameterAnnotation(parameter, desc, visible)) {
                    @Override
                    public void visit(String name, Object value) {
                        if (name.equals("nullable")) {
                            if ((Boolean) value == true) {
                                options[parameter] = StorageOption.Option.NULLABLE_INSTANCE;
                            }
                        }
                        super.visit(name, value);
                    }
                };
            } else if (type.equals(Type.getType(StorageOption.Update.class))) {
                options[parameter] = StorageOption.Option.UPDATE;
            } else if (type.equals(Type.getType(StorageOption.Null.class))) {
                options[parameter] = StorageOption.Option.NULL;
            } else if (type.equals(Type.getType(StorageOption.Target.class))) {
                if (!args[parameter].equals(Type.getType(EntityPlayer.class))) {
                    throw new RuntimeException("Target annotation can only be used on EntityPlayer.");
                }
                if (targetIndex != -1) {
                    throw new RuntimeException("You can not specify multiple targets.");
                }
                options[parameter] = StorageOption.Option.INSTANCE;
                targetIndex = parameter;
                return new AnnotationVisitor(this.api,
                        super.visitParameterAnnotation(parameter, desc, visible)) {
                    @Override
                    public void visitEnum(String name, String desc, String value) {
                        super.visitEnum(name, desc, value);
                        range = StorageOption.Target.RangeOption.valueOf(value);
                    }
                };
            } else if (type.equals(Type.getType(StorageOption.RangedTarget.class))) {
                if (targetIndex != -1) {
                    throw new RuntimeException("You can not specify multiple targets.");
                }
                targetIndex = parameter;
                range = null;
                return new AnnotationVisitor(this.api,
                        super.visitParameterAnnotation(parameter, desc, visible)) {
                    @Override
                    public void visit(String name, Object value) {
                        super.visit(name, value);
                        sendRange = (double) value;
                    }
                };
            }
            return super.visitParameterAnnotation(parameter, desc, visible);
        }

        //TODO this option (from annotation)

        @Override
        public void visitEnd() {
            super.visitEnd();
            //This is the last method in the delegate class.
            //Finish the class and do the registration.
            cw.visitEnd();
            try {
                Class<?> clazz = classLoader.defineClass(delegateClassType.getClassName(), cw.toByteArray());
                NetworkCallDelegate delegateObj = (NetworkCallDelegate) clazz.newInstance();
                if (side == Side.CLIENT) {
                    NetworkCallManager.registerClientDelegateClass(delegateName, delegateObj, options,
                            targetIndex, range, sendRange);
                } else {
                    NetworkCallManager.registerServerDelegateClass(delegateName, delegateObj, options);
                }
            } catch (Throwable e) {
                throw new RuntimeException("Can not create delegate for network call.", e);
            }
        }
    };
    //public static void delegated(Type0 arg0, Type1, arg1, ...) {
    //    //Code generated by caller.
    //}
    //}
}

From source file:co.cask.cdap.internal.app.runtime.service.http.HttpHandlerGenerator.java

License:Apache License

/**
 * Inspects the given type and copy/rewrite handler methods from it into the newly generated class.
 *
 * @param delegateType The user handler type
 * @param inspectType The type that needs to be inspected. It's either the delegateType or one of its parents
 *///from  www.jav a  2  s  . co  m
private void inspectHandler(final TypeToken<?> delegateType, final TypeToken<?> inspectType,
        final String pathPrefix, final Type classType, final ClassWriter classWriter,
        final List<Class<?>> preservedClasses) throws IOException {
    Class<?> rawType = inspectType.getRawType();

    // Visit the delegate class, copy and rewrite handler method, with method body just do delegation
    try (InputStream sourceBytes = rawType.getClassLoader()
            .getResourceAsStream(Type.getInternalName(rawType) + ".class")) {
        ClassReader classReader = new ClassReader(sourceBytes);
        classReader.accept(new ClassVisitor(Opcodes.ASM5) {

            // Only need to visit @Path at the class level if we are inspecting the user handler class
            private final boolean inspectDelegate = delegateType.equals(inspectType);
            private boolean visitedPath = !inspectDelegate;

            @Override
            public void visit(int version, int access, String name, String signature, String superName,
                    String[] interfaces) {
                super.visit(version, access, name, signature, superName, interfaces);
            }

            @Override
            public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                // Copy the class annotation if it is @Path. Only do it for one time
                Type type = Type.getType(desc);
                if (inspectDelegate && type.equals(Type.getType(Path.class))) {
                    visitedPath = true;
                    AnnotationVisitor annotationVisitor = classWriter.visitAnnotation(desc, visible);
                    return new AnnotationVisitor(Opcodes.ASM5, annotationVisitor) {
                        @Override
                        public void visit(String name, Object value) {
                            // "value" is the key for the Path annotation string.
                            if (name.equals("value")) {
                                super.visit(name, pathPrefix + value.toString());
                            } else {
                                super.visit(name, value);
                            }
                        }
                    };

                } else {
                    return super.visitAnnotation(desc, visible);
                }
            }

            @Override
            public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                    String[] exceptions) {
                // Create a class-level annotation with the prefix, if the user has not specified any class-level
                // annotation.
                if (!visitedPath) {
                    String pathDesc = Type.getType(Path.class).getDescriptor();
                    AnnotationVisitor annotationVisitor = classWriter.visitAnnotation(pathDesc, true);
                    annotationVisitor.visit("value", pathPrefix);
                    annotationVisitor.visitEnd();
                    visitedPath = true;
                }

                // Copy the method if it is public and annotated with one of the HTTP request method
                MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
                if (!Modifier.isPublic(access)) {
                    return mv;
                }
                return new HandlerMethodVisitor(delegateType, mv, desc, signature, access, name, exceptions,
                        classType, classWriter, preservedClasses);
            }
        }, ClassReader.SKIP_DEBUG);
    }
}

From source file:com.gargoylesoftware.js.nashorn.internal.tools.nasgen.ScriptClassInfoCollector.java

License:Open Source License

@Override
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
    final AnnotationVisitor delegateAV = super.visitAnnotation(desc, visible);
    if (SCRIPT_CLASS_ANNO_DESC.equals(desc)) {
        return new AnnotationVisitor(Main.ASM_VERSION, delegateAV) {
            @Override/*from   w w  w. ja  v  a2 s.c om*/
            public void visit(final String name, final Object value) {
                if ("value".equals(name)) {
                    scriptClassName = (String) value;
                }
                super.visit(name, value);
            }
        };
    }

    return delegateAV;
}

From source file:com.gargoylesoftware.js.nashorn.internal.tools.nasgen.ScriptClassInfoCollector.java

License:Open Source License

@Override
public FieldVisitor visitField(final int fieldAccess, final String fieldName, final String fieldDesc,
        final String signature, final Object value) {
    final FieldVisitor delegateFV = super.visitField(fieldAccess, fieldName, fieldDesc, signature, value);

    return new FieldVisitor(Main.ASM_VERSION, delegateFV) {
        @Override/*w  w w. j  ava 2  s. c  om*/
        public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
            final AnnotationVisitor delegateAV = super.visitAnnotation(descriptor, visible);

            if (ScriptClassInfo.PROPERTY_ANNO_DESC.equals(descriptor)) {
                final MemberInfo memInfo = new MemberInfo();

                memInfo.setKind(Kind.PROPERTY);
                memInfo.setJavaName(fieldName);
                memInfo.setJavaDesc(fieldDesc);
                memInfo.setJavaAccess(fieldAccess);

                if ((fieldAccess & Opcodes.ACC_STATIC) != 0) {
                    memInfo.setValue(value);
                }

                addScriptMember(memInfo);

                return new AnnotationVisitor(Main.ASM_VERSION, delegateAV) {
                    // These could be "null" if values are not supplied,
                    // in which case we have to use the default values.
                    private String name;
                    private Integer attributes;
                    private String clazz = "";
                    private Where where;

                    @Override
                    public void visit(final String annotationName, final Object annotationValue) {
                        switch (annotationName) {
                        case "name":
                            this.name = (String) annotationValue;
                            break;
                        case "attributes":
                            this.attributes = (Integer) annotationValue;
                            break;
                        case "clazz":
                            this.clazz = (annotationValue == null) ? "" : annotationValue.toString();
                            break;
                        default:
                            break;
                        }
                        super.visit(annotationName, annotationValue);
                    }

                    @Override
                    public void visitEnum(final String enumName, final String desc, final String enumValue) {
                        if ("where".equals(enumName) && WHERE_ENUM_DESC.equals(desc)) {
                            this.where = Where.valueOf(enumValue);
                        }
                        super.visitEnum(enumName, desc, enumValue);
                    }

                    @Override
                    public void visitEnd() {
                        super.visitEnd();
                        memInfo.setName(name == null ? fieldName : name);
                        memInfo.setAttributes(attributes == null ? MemberInfo.DEFAULT_ATTRIBUTES : attributes);
                        clazz = clazz.replace('.', '/');
                        memInfo.setInitClass(clazz);
                        memInfo.setWhere(where == null ? Where.INSTANCE : where);
                    }
                };
            }

            return delegateAV;
        }
    };
}

From source file:com.gargoylesoftware.js.nashorn.internal.tools.nasgen.ScriptClassInfoCollector.java

License:Open Source License

@Override
public MethodVisitor visitMethod(final int methodAccess, final String methodName, final String methodDesc,
        final String signature, final String[] exceptions) {

    final MethodVisitor delegateMV = super.visitMethod(methodAccess, methodName, methodDesc, signature,
            exceptions);//from  w  ww  .  j ava  2 s.com

    return new MethodVisitor(Main.ASM_VERSION, delegateMV) {

        @Override
        public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
            final AnnotationVisitor delegateAV = super.visitAnnotation(descriptor, visible);
            final Kind annoKind = ScriptClassInfo.annotations.get(descriptor);

            if (annoKind != null) {
                if ((methodAccess & Opcodes.ACC_STATIC) == 0) {
                    error(methodName, methodDesc, "nasgen method annotations cannot be on instance methods");
                }

                final MemberInfo memInfo = new MemberInfo();

                // annoKind == GETTER or SPECIALIZED_FUNCTION
                memInfo.setKind(annoKind);
                memInfo.setJavaName(methodName);
                memInfo.setJavaDesc(methodDesc);
                memInfo.setJavaAccess(methodAccess);

                addScriptMember(memInfo);

                return new AnnotationVisitor(Main.ASM_VERSION, delegateAV) {
                    // These could be "null" if values are not supplied,
                    // in which case we have to use the default values.
                    private String name;
                    private Integer attributes;
                    private Integer arity;
                    private Where where;
                    private boolean isSpecializedConstructor;
                    private boolean isOptimistic;
                    private Type linkLogicClass = MethodGenerator.EMPTY_LINK_LOGIC_TYPE;

                    @Override
                    public void visit(final String annotationName, final Object annotationValue) {
                        switch (annotationName) {
                        case "name":
                            this.name = (String) annotationValue;
                            if (name.isEmpty()) {
                                name = null;
                            }
                            break;
                        case "attributes":
                            this.attributes = (Integer) annotationValue;
                            break;
                        case "arity":
                            this.arity = (Integer) annotationValue;
                            break;
                        case "isConstructor":
                            assert annoKind == Kind.SPECIALIZED_FUNCTION;
                            this.isSpecializedConstructor = (Boolean) annotationValue;
                            break;
                        case "isOptimistic":
                            assert annoKind == Kind.SPECIALIZED_FUNCTION;
                            this.isOptimistic = (Boolean) annotationValue;
                            break;
                        case "linkLogic":
                            this.linkLogicClass = (Type) annotationValue;
                            break;
                        default:
                            break;
                        }

                        super.visit(annotationName, annotationValue);
                    }

                    @Override
                    public void visitEnum(final String enumName, final String desc, final String enumValue) {
                        switch (enumName) {
                        case "where":
                            if (WHERE_ENUM_DESC.equals(desc)) {
                                this.where = Where.valueOf(enumValue);
                            }
                            break;
                        default:
                            break;
                        }
                        super.visitEnum(enumName, desc, enumValue);
                    }

                    @SuppressWarnings("fallthrough")
                    @Override
                    public void visitEnd() {
                        super.visitEnd();

                        if (memInfo.getKind() == Kind.CONSTRUCTOR) {
                            memInfo.setName(name == null ? scriptClassName : name);
                        } else {
                            memInfo.setName(name == null ? methodName : name);
                        }
                        memInfo.setAttributes(attributes == null ? MemberInfo.DEFAULT_ATTRIBUTES : attributes);

                        memInfo.setArity((arity == null) ? MemberInfo.DEFAULT_ARITY : arity);
                        if (where == null) {
                            // by default @Getter/@Setter belongs to INSTANCE
                            // @Function belong to PROTOTYPE.
                            switch (memInfo.getKind()) {
                            case GETTER:
                            case SETTER:
                                where = Where.INSTANCE;
                                break;
                            case CONSTRUCTOR:
                                where = Where.CONSTRUCTOR;
                                break;
                            case FUNCTION:
                                where = Where.PROTOTYPE;
                                break;
                            case SPECIALIZED_FUNCTION:
                                where = isSpecializedConstructor ? Where.CONSTRUCTOR : Where.PROTOTYPE;
                                //fallthru
                            default:
                                break;
                            }
                        }
                        memInfo.setWhere(where);
                        memInfo.setLinkLogicClass(linkLogicClass);
                        memInfo.setIsSpecializedConstructor(isSpecializedConstructor);
                        memInfo.setIsOptimistic(isOptimistic);
                    }
                };
            }

            return delegateAV;
        }
    };
}

From source file:com.github.bmsantos.core.cola.injector.InfoClassVisitor.java

License:Apache License

@Override
public AnnotationVisitor visitAnnotation(final String descriptor, final boolean runtimeVisible) {
    if (descriptor.equals(FEATURES_DESCRIPTOR)) {
        return new AnnotationVisitor(ASM4, super.visitAnnotation(descriptor, runtimeVisible)) {
            @Override//from w w  w . j a v  a  2 s  .  co  m
            public AnnotationVisitor visitArray(final String name) {
                if (name.equals("value")) {
                    return new AnnotationVisitor(ASM4, super.visitArray(name)) {
                        @Override
                        public void visit(final String name, final Object value) {
                            super.visit(name, value);

                            final String featureUri = className.substring(0, className.lastIndexOf("/") + 1)
                                    + value.toString();

                            final InputStream in = findResource(featureUri);
                            if (in == null) {
                                raiseInvalidFeatureUri(featureUri,
                                        "Unable to find feature file (.feature|.stories|.story|.gherkin)");
                            }

                            String contents = null;
                            try {
                                contents = readFeatureContents(in).trim();
                                if (contents.isEmpty()) {
                                    raiseInvalidFeatureUri(featureUri, "Empty feature.");
                                }

                                features.add(FeatureFormatter.parse(contents, featureUri));
                            } catch (final NoSuchElementException | LexingError e) {
                                raiseInvalidFeatureUri(featureUri, e.getMessage());
                            }

                        }
                    };
                }
                return super.visitArray(name);
            }
        };
    } else if (descriptor.equals(COLA_INJECTED_DESCRIPTOR)) {
        isColaInjected = true;
    }
    return super.visitAnnotation(descriptor, runtimeVisible);
}

From source file:com.google.gwt.dev.javac.asm.CollectReferencesVisitor.java

License:Apache License

CollectReferencesVisitor() {
    this.av = new AnnotationVisitor(Opcodes.ASM6, this.av) {
        @Override/*w ww.  j a  v  a2 s .  c om*/
        public void visitEnum(String name, String desc, String value) {
            addTypeIfClass(desc);
        }

        @Override
        public void visit(String name, Object value) {
            // don't mark this annotation as a reference or its arguments, so we can
            // handle binary-only annotations.
            // TODO(jat): consider implications of updating the annotation class
        }

    };
}

From source file:org.apache.batchee.tools.maven.doc.ComponentDocumentationGenerator.java

License:Apache License

private String component(final Map<String, ClassDoc> commands, final File classFile) throws IOException {
    InputStream stream = null;/* w ww . jav a2 s .c om*/
    try {
        stream = new FileInputStream(classFile);
        final ClassReader reader = new ClassReader(stream);
        reader.accept(new ClassVisitor(ASM5) {
            public boolean isLeaf;
            private String parentName;
            private String configName;
            private String className;
            private String doc;
            private List<FieldDoc> configs;

            @Override
            public void visit(final int version, final int access, final String name, final String signature,
                    final String superName, final String[] interfaces) {
                parentName = superName == null || OBJECT_NAME.equals(superName) ? null
                        : superName.replace('/', '.');
                className = name.replace('/', '.');
                isLeaf = !Modifier.isAbstract(access); // TODO: interfaces?
            }

            @Override
            public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
                final AnnotationVisitor annotationVisitor = super.visitAnnotation(desc, visible);
                if (NAMED_MARKER.equals(desc)) {
                    configName = className;
                    final int dollar = configName.lastIndexOf('$');
                    if (dollar > 0) {
                        configName = configName.substring(dollar + 1);
                    } else {
                        final int dot = configName.lastIndexOf('.');
                        if (dot > 0) {
                            configName = configName.substring(dot + 1);
                        }
                    }

                    configName = Introspector.decapitalize(configName);
                    return new AnnotationVisitor(ASM5, annotationVisitor) {
                        @Override
                        public void visit(final String name, final Object value) {
                            super.visit(name, value);
                            if ("value".equals(name) && String.class.isInstance(value)
                                    && !String.class.cast(value).isEmpty()) {
                                configName = value.toString();
                            }
                        }
                    };
                }
                if (CONFIGURATION_MARKER.equals(desc)) {
                    return new AnnotationVisitor(ASM5, annotationVisitor) {
                        @Override
                        public void visit(final String name, final Object value) {
                            super.visit(name, value);
                            if ("value".equals(name) && String.class.isInstance(value)
                                    && !String.class.cast(value).isEmpty()) {
                                doc = value.toString();
                            }
                        }
                    };
                }
                return annotationVisitor;
            }

            @Override
            public FieldVisitor visitField(final int access, final String name, final String desc,
                    final String signature, final Object value) {
                return new FieldVisitor(ASM5, super.visitField(access, name, desc, signature, value)) {
                    private boolean marked = false;
                    private boolean hasInject = false;
                    private String configName = name;
                    private String doc = null;

                    @Override
                    public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) {
                        final AnnotationVisitor annotationVisitor = super.visitAnnotation(desc, visible);
                        if (PROPERTY_MARKER.equals(desc)) {
                            marked = true;
                            return new AnnotationVisitor(ASM5, annotationVisitor) {
                                @Override
                                public void visit(final String name, final Object value) {
                                    super.visit(name, value);
                                    if ("name".equals(name) && String.class.isInstance(value)
                                            && !String.class.cast(value).isEmpty()) {
                                        configName = value.toString();
                                    }
                                }
                            };
                        }
                        if (INJECT_MARKER.equals(desc)) {
                            hasInject = true;
                            return annotationVisitor;
                        }
                        if (CONFIGURATION_MARKER.equals(desc)) {
                            return new AnnotationVisitor(ASM5, annotationVisitor) {
                                @Override
                                public void visit(final String name, final Object value) {
                                    super.visit(name, value);
                                    if ("value".equals(name) && String.class.isInstance(value)
                                            && !String.class.cast(value).isEmpty()) {
                                        doc = value.toString();
                                    }
                                }
                            };
                        }
                        return annotationVisitor;
                    }

                    @Override
                    public void visitEnd() {
                        super.visitEnd();
                        if (marked && hasInject) {
                            if (configs == null) {
                                configs = new ArrayList<FieldDoc>();
                            }
                            configs.add(new FieldDoc(configName, doc));
                        }
                    }
                };
            }

            @Override
            public void visitEnd() {
                super.visitEnd();
                if (configs != null) {
                    Collections.sort(configs);
                    commands.put(className, new ClassDoc(isLeaf, parentName,
                            configName == null ? className : configName, doc, configs));
                }
            }
        }, SKIP_CODE + SKIP_DEBUG + SKIP_FRAMES);
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (final IOException e) {
            // no-op
        }
    }
    return null;
}

From source file:org.jephyr.activeobject.instrument.ActiveObjectClassAdapter.java

License:Open Source License

@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
    AnnotationVisitor av = super.visitAnnotation(desc, visible);
    if (instrument) {
        if (desc.equals("Lorg/jephyr/activeobject/instrument/Instrumented;")) {
            instrument = false;//from  w ww  . j  ava2s .c o  m
        } else if (desc.equals("Lorg/jephyr/activeobject/annotation/ActiveObject;")) {
            super.visitAnnotation("Lorg/jephyr/activeobject/instrument/Instrumented;", false);
            activeObject = true;
            classEntries = new ArrayList<>();
            methodNodes = new ArrayList<>();
            return new AnnotationVisitor(ASM5, av) {
                @Override
                public void visit(String name, Object value) {
                    if (name.equals("mailbox")) {
                        mailbox = (Type) value;
                    }
                    super.visit(name, value);
                }
            };
        }
    }
    return av;
}