Example usage for org.objectweb.asm MethodVisitor visitAnnotation

List of usage examples for org.objectweb.asm MethodVisitor visitAnnotation

Introduction

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

Prototype

public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) 

Source Link

Document

Visits an annotation of this method.

Usage

From source file:org.apache.felix.ipojo.manipulator.metadata.annotation.model.parser.replay.AnnotationVisitorPlayback.java

License:Apache License

public void accept(final MethodVisitor visitor) {
    AnnotationVisitor av = visitor.visitAnnotation(m_desc, m_visible);
    if (av != null) {
        accept(av);/*from  www  .  j a  v a  2  s.c  o  m*/
    }
}

From source file:org.apache.tuscany.sca.interfacedef.java.jaxrs.RootResourceClassGenerator.java

License:Apache License

private static void annotateContentTypes(MethodVisitor mv, String consumes, String produces) {
    AnnotationVisitor av = null;//from w  ww  . j  a va 2s  . com
    if (consumes != null) {
        av = mv.visitAnnotation("Ljavax/ws/rs/Consumes;", true);
        AnnotationVisitor av1 = av.visitArray("value");
        for (String s : consumes.split("(,| )")) {
            av1.visit(null, s.trim());
        }
        av1.visitEnd();
        av.visitEnd();
    }
    if (produces != null) {
        av = mv.visitAnnotation("Ljavax/ws/rs/Produces;", true);
        AnnotationVisitor av1 = av.visitArray("value");
        for (String s : produces.split("(,| )")) {
            av1.visit(null, s.trim());
        }
        av1.visitEnd();
        av.visitEnd();
    }
}

From source file:org.boretti.drools.integration.drools5.DroolsClassVisitor.java

License:Open Source License

@Override
public void visitEnd() {
    FieldVisitor fv = null;//from   w ww.java 2  s.com
    if (isNeedChangeForBoth()) {
        fv = super.visitField(Opcodes.ACC_PRIVATE, DROOLS_FIELD_NAME, Type.BOOLEAN_TYPE.getDescriptor(), null,
                null);
        if (fv != null) {
            AnnotationVisitor av = fv.visitAnnotation(Type.getType(Generated.class).getDescriptor(), true);
            AnnotationVisitor value = av.visitArray("value");
            value.visit("", "Generated by Drools5IntegrationHelper Maven plugin");
            value.visitEnd();
            av.visit("date", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz").format(current));
            av.visitEnd();
            fv.visitEnd();
        }
    }
    if (isNeedChangeForField()) {
        fv = super.visitField(Opcodes.ACC_PRIVATE, DROOLS_FIELD_RULE,
                Type.getType(RuleBase.class).getDescriptor(), null, null);
        if (fv != null) {
            AnnotationVisitor av = fv.visitAnnotation(Type.getType(Generated.class).getDescriptor(), true);
            AnnotationVisitor value = av.visitArray("value");
            value.visit("", "Generated by Drools5IntegrationHelper Maven plugin");
            value.visitEnd();
            av.visit("date", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz").format(current));
            av.visitEnd();
            fv.visitEnd();
        }
        MethodVisitor mv = super.visitMethod(Opcodes.ACC_PRIVATE, DROOLS_METHOD_RUN, "()V", null, null);
        AnnotationVisitor av = mv.visitAnnotation(Type.getType(Generated.class).getDescriptor(), true);
        AnnotationVisitor value = av.visitArray("value");
        value.visit("", "Generated by Drools5IntegrationHelper Maven plugin");
        value.visitEnd();
        av.visit("date", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz").format(current));
        av.visitEnd();
        mv.visitCode();
        Label start = new Label();
        mv.visitLabel(start);
        Label doIt = new Label();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, Type.getObjectType(me).getInternalName(), DROOLS_FIELD_NAME,
                Type.BOOLEAN_TYPE.getDescriptor());
        mv.visitJumpInsn(Opcodes.IFEQ, doIt);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitLabel(doIt);
        mv.visitFrame(Opcodes.F_SAME, 1, new Object[] { Type.getObjectType(me).getInternalName() }, 0,
                new Object[] {});
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitFieldInsn(Opcodes.GETFIELD, Type.getObjectType(me).getInternalName(), DROOLS_FIELD_RULE,
                Type.getType(RuleBase.class).getDescriptor());
        mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getType(RuleBase.class).getInternalName(),
                "newStatelessSession", "()Lorg/drools/StatelessSession;");
        mv.visitInsn(Opcodes.DUP);
        mv.visitLdcInsn(FIELD_NAME_LOGGER);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getType(Object.class).getInternalName(), "getClass",
                "()Ljava/lang/Class;");
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getType(org.apache.log4j.Logger.class).getInternalName(),
                "getLogger", "(Ljava/lang/Class;)Lorg/apache/log4j/Logger;");
        mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getType(StatelessSession.class).getInternalName(),
                "setGlobal", "(Ljava/lang/String;Ljava/lang/Object;)V");
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getType(StatelessSession.class).getInternalName(),
                "execute", "(Ljava/lang/Object;)V");
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitInsn(Opcodes.ICONST_1);
        mv.visitFieldInsn(Opcodes.PUTFIELD, Type.getObjectType(me).getInternalName(), DROOLS_FIELD_NAME,
                Type.BOOLEAN_TYPE.getDescriptor());
        mv.visitInsn(Opcodes.RETURN);
        Label end = new Label();
        mv.visitLabel(end);
        mv.visitLocalVariable("this", Type.getObjectType(me).getDescriptor(), null, start, end, 0);
        mv.visitMaxs(4, 1);
        mv.visitEnd();
    }
    super.visitEnd();
}

From source file:org.codehaus.aspectwerkz.transform.inlining.weaver.MethodExecutionVisitor.java

License:Open Source License

/**
 * Visits the methods.//w  w w  .j av  a 2  s . c o  m
 *
 * @param access
 * @param name
 * @param desc
 * @param signature
 * @param exceptions
 * @return
 */
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature,
        final String[] exceptions) {

    if (INIT_METHOD_NAME.equals(name) || CLINIT_METHOD_NAME.equals(name) || name.startsWith(ASPECTWERKZ_PREFIX)
            || name.startsWith(SYNTHETIC_MEMBER_PREFIX) || name.startsWith(WRAPPER_METHOD_PREFIX)
            || (AdvisableImpl.ADD_ADVICE_METHOD_NAME.equals(name)
                    && AdvisableImpl.ADD_ADVICE_METHOD_DESC.equals(desc))
            || (AdvisableImpl.REMOVE_ADVICE_METHOD_NAME.equals(name)
                    && AdvisableImpl.REMOVE_ADVICE_METHOD_DESC.equals(desc))) {
        return cv.visitMethod(access, name, desc, signature, exceptions);
    }

    int hash = AsmHelper.calculateMethodHash(name, desc);
    MethodInfo methodInfo = m_classInfo.getMethod(hash);
    if (methodInfo == null) {
        System.err.println("AW::WARNING " + "metadata structure could not be build for method ["
                + m_classInfo.getName().replace('/', '.') + '.' + name + ':' + desc + ']');
        // bail out
        return cv.visitMethod(access, name, desc, signature, exceptions);
    }

    ExpressionContext ctx = new ExpressionContext(PointcutType.EXECUTION, methodInfo, methodInfo);

    if (methodFilter(m_ctx.getDefinitions(), ctx, methodInfo)) {
        return cv.visitMethod(access, name, desc, signature, exceptions);
    } else {
        String prefixedOriginalName = TransformationUtil.getPrefixedOriginalMethodName(name,
                m_declaringTypeName);
        if (m_addedMethods.contains(AlreadyAddedMethodAdapter.getMethodKey(prefixedOriginalName, desc))) {
            return cv.visitMethod(access, name, desc, signature, exceptions);
        }

        m_ctx.markAsAdvised();

        // create the proxy for the original method
        final MethodVisitor proxyMethod = createProxyMethod(access, name, desc, signature, exceptions,
                methodInfo);

        int modifiers = ACC_SYNTHETIC;
        if (Modifier.isStatic(access)) {
            modifiers |= ACC_STATIC;
        }
        // prefix the original method and make sure we copy method annotations to the proxyMethod
        // while keeping the body for the prefixed method
        return new MethodAdapter(cv.visitMethod(modifiers, prefixedOriginalName, desc, signature, exceptions)) {
            public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                return new AsmCopyAdapter.CopyAnnotationAdapter(super.visitAnnotation(desc, visible),
                        proxyMethod.visitAnnotation(desc, visible));
            }

            public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) {
                return new AsmCopyAdapter.CopyAnnotationAdapter(
                        super.visitParameterAnnotation(parameter, desc, visible),
                        proxyMethod.visitParameterAnnotation(parameter, desc, visible));
            }

            public void visitAttribute(Attribute attr) {
                super.visitAttribute(attr);
                proxyMethod.visitAttribute(attr);
            }
        };
    }
}

From source file:org.fabric3.binding.ws.metro.generator.java.codegen.InterfaceFromWsdlGeneratorImpl.java

License:Open Source License

private void generateMethod(ClassWriter cw, Method m, Definition definition,
        ReferenceEndpointDefinition endpointDefinition) {
    MethodVisitor mv;

    QName portTypeName = endpointDefinition.getPortTypeName();
    Binding binding = null;/*from   w  w  w .  j  a v a 2 s  .  c  o  m*/
    Collection<Binding> bindings = definition.getBindings().values();
    for (Binding entry : bindings) {
        if (entry.getPortType().getQName().equals(portTypeName)) {
            binding = entry;
            break;
        }
    }

    if (binding == null) {
        throw new AssertionError();
    }

    BindingOperation bindingOperation = null;
    List<BindingOperation> bindingOperations = binding.getBindingOperations();
    for (BindingOperation operation : bindingOperations) {
        if (operation.getName().equals(m.getName())) {
            bindingOperation = operation;
            break;
        }
    }

    SOAPOperation soapOperation = null;
    for (Object element : bindingOperation.getExtensibilityElements()) {
        if (element instanceof SOAPOperation) {
            soapOperation = (SOAPOperation) element;
        }
    }
    String action = soapOperation.getSoapActionURI();

    String signature = getSignature(m);
    mv = cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, m.getName(), signature, null, null);

    AnnotationVisitor av = mv.visitAnnotation(getSignature(WebMethod.class), true);
    av.visit("action", action);
    av.visitEnd();

    PortType portType = definition.getPortType(portTypeName);
    List<Operation> portTypeOperations = portType.getOperations();
    Operation portTypeOperation = null;
    for (Operation entry : portTypeOperations) {
        if (entry.getName().equals(m.getName())) {
            portTypeOperation = entry;
        }
    }
    av = mv.visitAnnotation(getSignature(WebResult.class), true);
    av.visit("name", portTypeOperation.getOutput().getMessage().getQName().getLocalPart());
    Collection<Part> parts = portTypeOperation.getOutput().getMessage().getParts().values();
    av.visit("partName", parts.iterator().next().getName());
    av.visitEnd();

    av = mv.visitParameterAnnotation(0, getSignature(WebParam.class), true);
    parts = portTypeOperation.getInput().getMessage().getParts().values();
    String partName = parts.iterator().next().getName();
    av.visit("name", partName);
    av.visit("partName", partName);
    av.visitEnd();
    mv.visitEnd();
}

From source file:org.fabric3.binding.ws.metro.generator.java.codegen.InterfaceGeneratorImpl.java

License:Open Source License

private void generateMethod(ClassWriter cw, Method m) {
    MethodVisitor mv;
    String signature = getSignature(m);
    mv = cw.visitMethod(ACC_PUBLIC + ACC_ABSTRACT, m.getName(), signature, null, null);

    if (!m.isAnnotationPresent(WebMethod.class)) {
        // add @WebMethod if it is not present
        AnnotationVisitor av = mv.visitAnnotation(getSignature(WebMethod.class), true);
        av.visitEnd();/*from   w w w .  j a v a  2s .  c  o m*/
    }
    if (!m.isAnnotationPresent(Oneway.class)) {
        if (m.isAnnotationPresent(OneWay.class)) {
            // add the JAX-WS one-way equivalent
            AnnotationVisitor oneWay = mv.visitAnnotation(getSignature(Oneway.class), true);
            oneWay.visitEnd();
        }
    }
    mv.visitEnd();
}

From source file:org.forgerock.openidm.shell.felixgogo.FelixGogoCommandsServiceGenerator.java

License:Apache License

/**
 * Generate CommandProvider class and newBuilder for this class based on parameters.
 *
 * @param service  commands service/*from w w  w . j  av a  2s. c o  m*/
 * @param commands commands map (name=help)
 * @param suffix   unique class suffix
 * @return generated CommandProvider newBuilder
 * @throws Exception if something went wrong
 */
public static Object generate(CustomCommandScope service, Map<String, String> commands, String suffix)
        throws Exception {
    // generate class with unique name
    //javassist.CtClass ctClass = POOL.makeClass(AbstractFelixCommandsService.class.getName() + suffix);

    try {
        ClassWriter cw = new ClassWriter(0);
        MethodVisitor mv;
        AnnotationVisitor av0;
        String className = AbstractFelixCommandsService.class.getName().replace('.', '/') + suffix;
        cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, className, null,
                AbstractFelixCommandsService.class.getName().replace('.', '/'), null);

        //cw.visitSource("AbstractFelixCommandsServiceSample.java", null);

        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "(Ljava/lang/Object;)V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(10, l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, 1);
        mv.visitMethodInsn(INVOKESPECIAL, AbstractFelixCommandsService.class.getName().replace('.', '/'),
                "<init>", "(Ljava/lang/Object;)V");
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLineNumber(11, l1);
        mv.visitInsn(RETURN);
        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitLocalVariable("this", "L" + className + ";", null, l0, l2, 0);
        mv.visitLocalVariable("service", "Ljava/lang/Object;", null, l0, l2, 1);
        mv.visitMaxs(2, 2);
        mv.visitEnd();

        /*javassist.bytecode.ClassFile ccFile = ctClass.getClassFile();
        ccFile.setVersionToJava5();
        javassist.bytecode.ConstPool constPool = ccFile.getConstPool();
                
        // set superclass
        javassist.CtClass abstractCtClass = POOL.getCtClass(AbstractFelixCommandsService.class.getName());
        ctClass.setSuperclass(abstractCtClass);
                
        // add constructor
        javassist.CtClass serviceCtClass = POOL.getCtClass(Object.class.getName());
        javassist.CtConstructor ctConstructor = new javassist.CtConstructor(new javassist.CtClass[]{serviceCtClass},
            ctClass);
        ctConstructor.setModifiers(javassist.Modifier.PUBLIC);
        ctConstructor.setBody("super($1);");
        ctClass.addConstructor(ctConstructor);
                
        // add method for each command
        javassist.CtClass sessionCtClass = POOL.getCtClass(CommandSession.class.getName());
        javassist.CtClass stringArrayCtClass = POOL.getCtClass(String[].class.getName());*/
        Set<String> names = commands.keySet();
        for (String name : names) {
            if (isMethodAvailable(service, name)) {
                mv = cw.visitMethod(ACC_PUBLIC, name,
                        "(Lorg/apache/felix/service/command/CommandSession;[Ljava/lang/String;)V", null, null);

                av0 = mv.visitAnnotation("Lorg/apache/felix/service/command/Descriptor;", true);
                av0.visit("value", commands.get(name));
                av0.visitEnd();

                mv.visitCode();
                l0 = new Label();
                mv.visitLabel(l0);
                mv.visitLineNumber(15, l0);
                mv.visitVarInsn(ALOAD, 0);
                mv.visitLdcInsn(name);
                mv.visitVarInsn(ALOAD, 1);
                mv.visitVarInsn(ALOAD, 2);
                mv.visitMethodInsn(INVOKEVIRTUAL, className, "runCommand",
                        "(Ljava/lang/String;Lorg/apache/felix/service/command/CommandSession;"
                                + "[Ljava/lang/String;)V");
                l1 = new Label();
                mv.visitLabel(l1);
                mv.visitLineNumber(16, l1);
                mv.visitInsn(RETURN);
                l2 = new Label();
                mv.visitLabel(l2);
                mv.visitLocalVariable("this", "L" + className + ";", null, l0, l2, 0);
                mv.visitLocalVariable("session", "Lorg/apache/felix/service/command/CommandSession;", null, l0,
                        l2, 1);
                mv.visitLocalVariable("args", "[Ljava/lang/String;", null, l0, l2, 2);
                mv.visitMaxs(4, 3);
                mv.visitEnd();

                /*javassist.CtMethod ctMethod = new javassist.CtMethod(javassist.CtClass.voidType, name,
                    new javassist.CtClass[]{
                        sessionCtClass, stringArrayCtClass
                    }, ctClass);
                ctMethod.setModifiers(javassist.Modifier.PUBLIC);
                ctMethod.setBody("runCommand(\"" + name + "\", $1, $2);");
                ctClass.addMethod(ctMethod);
                        
                // add GoGo descriptor for this shell command
                javassist.bytecode.AnnotationsAttribute annotationsAttribute =
                    new javassist.bytecode.AnnotationsAttribute(constPool,
                        javassist.bytecode.AnnotationsAttribute.visibleTag);
                javassist.bytecode.annotation.Annotation annotation =
                    new javassist.bytecode.annotation.Annotation(Descriptor.class.getName(), constPool);
                annotation.addMemberValue("value",
                    new javassist.bytecode.annotation.StringMemberValue(commands.get(name), constPool));
                annotationsAttribute.addAnnotation(annotation);
                ctMethod.getMethodInfo().addAttribute(annotationsAttribute);*/
            }
        }

        cw.visitEnd();
        // create new newBuilder
        /*Class<?> aClass = ctClass.toClass(FelixGogoCommandsServiceGenerator.class.getClassLoader(), null);
        */
        Class<?> aClass = classLoader.defineClass(className, cw.toByteArray());
        Constructor<?> constructor = aClass.getConstructor(Object.class);
        return constructor.newInstance(service);
    } catch (Exception e) {
        //ctClass.detach();
        throw e;
    }
}

From source file:org.glowroot.advicegen.AdviceGenerator.java

License:Apache License

private void addIsEnabledMethod(ClassWriter cw) {
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "isEnabled", "()Z", null, null);
    mv.visitAnnotation("Lorg/glowroot/api/weaving/IsEnabled;", true).visitEnd();
    mv.visitCode();//from  w  w  w.  j a v  a2s  .c  o m
    if (config.enabledProperty().isEmpty()) {
        mv.visitFieldInsn(GETSTATIC, adviceInternalName, "pluginServices", "Lorg/glowroot/api/PluginServices;");
        mv.visitMethodInsn(INVOKEVIRTUAL, "org/glowroot/api/PluginServices", "isEnabled", "()Z", false);
        mv.visitInsn(IRETURN);
    } else {
        mv.visitFieldInsn(GETSTATIC, adviceInternalName, "enabled",
                "Lorg/glowroot/api/PluginServices$BooleanProperty;");
        mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/api/PluginServices$BooleanProperty", "value", "()Z",
                true);
        mv.visitInsn(IRETURN);
    }
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}

From source file:org.glowroot.advicegen.AdviceGenerator.java

License:Apache License

private MethodVisitor visitOnBeforeMethod(ClassWriter cw, String returnInternalName) {
    String desc;//from  ww  w  . ja va2 s .  c o m
    if (methodMetaInternalName != null) {
        desc = "(Ljava/lang/Object;Ljava/lang/String;[Ljava/lang/Object;L" + methodMetaInternalName + ";)"
                + returnInternalName;
    } else {
        desc = "()" + returnInternalName;
    }
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "onBefore", desc, null, null);
    mv.visitAnnotation("Lorg/glowroot/api/weaving/OnBefore;", true).visitEnd();
    if (methodMetaInternalName != null) {
        mv.visitParameterAnnotation(0, "Lorg/glowroot/api/weaving/BindReceiver;", true).visitEnd();
        mv.visitParameterAnnotation(1, "Lorg/glowroot/api/weaving/BindMethodName;", true).visitEnd();
        mv.visitParameterAnnotation(2, "Lorg/glowroot/api/weaving/BindParameterArray;", true).visitEnd();
        mv.visitParameterAnnotation(3, "Lorg/glowroot/api/weaving/BindMethodMeta;", true).visitEnd();
    }
    return mv;
}

From source file:org.glowroot.advicegen.AdviceGenerator.java

License:Apache License

private void addOnAfterMethodTimerOnly(ClassWriter cw) {
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "onAfter", "(Lorg/glowroot/api/Timer;)V", null,
            null);/*from www . jav  a  2s .c  om*/
    mv.visitAnnotation("Lorg/glowroot/api/weaving/OnAfter;", true).visitEnd();
    mv.visitParameterAnnotation(0, "Lorg/glowroot/api/weaving/BindTraveler;", true).visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/api/Timer", "stop", "()V", true);
    mv.visitInsn(RETURN);
    mv.visitMaxs(0, 0);
    mv.visitEnd();
}