Example usage for org.objectweb.asm MethodVisitor visitInsn

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

Introduction

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

Prototype

public void visitInsn(final int opcode) 

Source Link

Document

Visits a zero operand instruction.

Usage

From source file:com.nginious.http.xsp.StaticPart.java

License:Apache License

/**
 * Creates bytecode in a separate method for evaluating an expression.
 * /*  w  w w .  j av a 2  s.  c  o m*/
 * @param intClassName the binary class name of the class being created
 * @param writer the class writer
 * @throws XspException if unable to create bytecode
 */
void compileMethod(String intClassName, ClassWriter writer) throws XspException {
    if (!isExpression()) {
        return;
    }

    try {
        ExpressionParser parser = new ExpressionParser();
        TreeExpression expr = parser.parse(getExpressionContent());

        MethodVisitor visitor = writer.visitMethod(Opcodes.ACC_PRIVATE, this.methodName,
                "(Ljava/lang/StringBuffer;)V", null, null);
        visitor.visitCode();
        visitor.visitVarInsn(Opcodes.ALOAD, 1);

        if (expr.getType() == Type.ANY) {
            expr.compile(visitor, Type.STRING);
        } else {
            expr.compile(visitor);
        }

        if (expr.getType() == Type.BOOLEAN) {
            visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuffer", "append",
                    "(Z)Ljava/lang/StringBuffer;");
        } else if (expr.getType() == Type.DOUBLE) {
            visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuffer", "append",
                    "(D)Ljava/lang/StringBuffer;");
        } else if (expr.getType() == Type.INT) {
            visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuffer", "append",
                    "(I)Ljava/lang/StringBuffer;");
        } else if (expr.getType() == Type.STRING || expr.getType() == Type.ANY) {
            visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuffer", "append",
                    "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
        }

        visitor.visitInsn(Opcodes.POP);
        visitor.visitInsn(Opcodes.RETURN);
        visitor.visitMaxs(5, 5);
        visitor.visitEnd();
    } catch (ExpressionException e) {
        throw new XspException("Invalid expression at " + getLocationDescriptor(), e);
    }
}

From source file:com.nginious.http.xsp.XspCompiler.java

License:Apache License

/**
 * Creates subclass of {@link XspService} for the XSP file represented by the specified document
 * tree node structure./* w  ww.  java 2s  .  c om*/
 * 
 * @param document the document tree node structure
 * @param srcFilePath the XSP file source path
 * @return a descriptor for the generated subclass
 * @throws XspException if unable to create subclass
 */
private ClassDescriptor compileService(DocumentPart document, String srcFilePath) throws XspException {
    ClassWriter writer = new ClassWriter(0);

    // Create class
    String packageName = document.getMetaContent("package");
    String intServiceClazzName = createIntServiceClassName(packageName, srcFilePath);
    String serviceClazzName = createServiceClassName(packageName, srcFilePath);
    writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intServiceClazzName, "Lcom/nginious/http/xsp/XspService;",
            "com/nginious/http/xsp/XspService", null);

    // Create constructor
    createConstructor(writer, "com/nginious/http/xsp/XspService");

    // Create xsp service method
    MethodVisitor visitor = createXspMethod(writer);

    Label tryLabel = new Label();
    Label startCatchLabel = new Label();
    Label endCatchLabel = new Label();

    // Start try block
    visitor.visitTryCatchBlock(tryLabel, startCatchLabel, endCatchLabel, "java/lang/Throwable");

    visitor.visitLabel(tryLabel);

    visitor.visitTypeInsn(Opcodes.NEW, "com/nginious/http/xsp/expr/HttpRequestVariables");
    visitor.visitInsn(Opcodes.DUP);
    visitor.visitVarInsn(Opcodes.ALOAD, 1);
    visitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "com/nginious/http/xsp/expr/HttpRequestVariables", "<init>",
            "(Lcom/nginious/http/HttpRequest;)V");
    visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "com/nginious/http/xsp/expr/Expression", "setVariables",
            "(Lcom/nginious/http/xsp/expr/Variables;)V");

    document.compile(intServiceClazzName, writer, visitor);

    visitor.visitLabel(startCatchLabel);
    visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "com/nginious/http/xsp/expr/Expression", "removeVariables",
            "()V");

    visitor.visitLdcInsn(true);
    visitor.visitInsn(Opcodes.IRETURN);

    // Start finally block
    visitor.visitLabel(endCatchLabel);
    visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "com/nginious/http/xsp/expr/Expression", "removeVariables",
            "()V");
    visitor.visitInsn(Opcodes.ATHROW);

    visitor.visitMaxs(12, 12);
    visitor.visitEnd();

    document.compileMethod(intServiceClazzName, writer);

    writer.visitEnd();
    byte[] clazzBytes = writer.toByteArray();
    return new ClassDescriptor(serviceClazzName, clazzBytes);
}

From source file:com.nginious.http.xsp.XspCompiler.java

License:Apache License

/**
 * Creates a constructor with no arguments for the XSP service class being created with the
 * specified class writer. Bytecode is created for calling the superclass constructor in the
 * superclass with the specified supperclass name.
 * /*w w  w.j a v a2s.  c o m*/
 * @param writer the class writer
 * @param superclassName the superclass name
 * @see XspService
 */
void createConstructor(ClassWriter writer, String superclassName) {
    MethodVisitor visitor = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
    visitor.visitCode();
    visitor.visitVarInsn(Opcodes.ALOAD, 0);
    visitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassName, "<init>", "()V");
    visitor.visitInsn(Opcodes.RETURN);
    visitor.visitMaxs(1, 1);
    visitor.visitEnd();
}

From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java

License:Apache License

private void visitInsn(MethodVisitor mv, int index) {

    switch (index) {
    case 1:/*  w w w. ja v  a2 s .  com*/
        mv.visitInsn(Opcodes.ICONST_1);
        break;
    case 2:
        mv.visitInsn(Opcodes.ICONST_2);
        break;
    case 3:
        mv.visitInsn(Opcodes.ICONST_3);
        break;
    case 4:
        mv.visitInsn(Opcodes.ICONST_4);
        break;
    case 5:
        mv.visitInsn(Opcodes.ICONST_5);
        break;
    default:
        mv.visitIntInsn(Opcodes.BIPUSH, index);
    }
}

From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java

License:Apache License

/**
 *
 * //from  ww w .  j  ava2  s . c o  m
 *
 * @param cw
 * @param mv
 * @param processorName com/nway/commons/dbutils/DynamicBeanProcessorImpl
 * @param beanName com/nway/commons/dbutils/test/User
 * @return [0]:bean[1]createBean
 */
private Object[] prepScript(ClassWriter cw, MethodVisitor mv, String processorName, String beanName) {

    Object[] lab = new Object[2];

    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, processorName, null,
            "com/nway/spring/jdbc/bean/DbBeanFactory", null);

    cw.visitSource(processorName.substring(processorName.lastIndexOf('/') + 1) + ".java", null);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(6, l0);
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "com/nway/spring/jdbc/bean/DbBeanFactory", "<init>", "()V",
                false);
        mv.visitInsn(Opcodes.RETURN);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLocalVariable("this", "L" + processorName + ";", null, l0, l1, 0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "createBean",
                "(Ljava/sql/ResultSet;Ljava/lang/Class;)Ljava/lang/Object;",
                "<T:Ljava/lang/Object;>(Ljava/sql/ResultSet;Ljava/lang/Class<TT;>;)TT;",
                new String[] { "java/sql/SQLException" });
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(10, l0);
        mv.visitTypeInsn(Opcodes.NEW, beanName);
        mv.visitInsn(Opcodes.DUP);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, beanName, "<init>", "()V", false);
        mv.visitVarInsn(Opcodes.ASTORE, 3);

        lab[0] = l0;
        lab[1] = mv;
    }

    return lab;
}

From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java

License:Apache License

/**
 *
 * /*from  w w  w.  j  a  va2s . c om*/
 *
 * @param mv MethodVisitor
 * @param processorName com/nway/commons/dbutils/DynamicBeanProcessorImpl
 * @param beanName com/nway/commons/dbutils/test/User
 */
private void endScript(MethodVisitor mv, Label processorLabel, Label beanStart, int lineNumber,
        String processorName, String beanName) {

    Label l10 = new Label();
    mv.visitLabel(l10);
    mv.visitLineNumber(lineNumber, l10);
    mv.visitVarInsn(Opcodes.ALOAD, 3);
    mv.visitInsn(Opcodes.ARETURN);
    Label l11 = new Label();
    mv.visitLabel(l11);
    mv.visitLocalVariable("this", "L" + processorName + ";", null, processorLabel, l11, 0);
    mv.visitLocalVariable("rs", "Ljava/sql/ResultSet;", null, processorLabel, l11, 1);
    mv.visitLocalVariable("type", "Ljava/lang/Class;", "Ljava/lang/Class<TT;>;", processorLabel, l11, 2);
    mv.visitLocalVariable("bean", "L" + beanName + ";", null, beanStart, l11, 3);
    mv.visitMaxs(5, 4);
    mv.visitEnd();
}

From source file:com.openpojo.reflection.java.bytecode.asm.SubClassCreator.java

License:Open Source License

/**
 * This method will copy over the constructors to the subclass.
 *//*from   w  w w.j a v  a2 s.  c  om*/
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    LOGGER.debug("Method: " + name + " access:" + access + " desc:" + desc + " signature:" + signature
            + " exceptions:" + Arrays.toString(exceptions));
    if (name.equals("<init>") && access == ACC_PUBLIC || access == ACC_PROTECTED) {
        MethodVisitor mv = cw.visitMethod(access, name, desc, signature, exceptions);
        int counter = getParameterCount(desc);
        // wire constructor method to super
        {
            mv.visitCode();
            for (int idx = 0; idx <= counter; idx++) {
                mv.visitVarInsn(ALOAD, idx);
            }
            mv.visitMethodInsn(INVOKESPECIAL, className.replace(Java.PACKAGE_DELIMITER, Java.PATH_DELIMITER),
                    "<init>", desc, false);
            mv.visitInsn(RETURN);
            mv.visitMaxs(counter + 1, counter + 1);
            mv.visitEnd();
        }
    }

    return super.visitMethod(access, name, desc, signature, exceptions);
}

From source file:com.peergreen.arquillian.generator.CommonClassAdapter.java

License:Open Source License

public MethodVisitor callToSuperClass() {
    MethodVisitor mv = super.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();//ww  w.  jav a  2  s.c o m
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(superClass), "<init>", "()V");
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 1);
    mv.visitEnd();
    return mv;
}

From source file:com.peergreen.jartransformer.adapter.expiration.ExpirationDateClassAdapter.java

License:Apache License

/**
 * Visits the end of the class. This method, which is the last one to be
 * called, is used to inform the visitor that all the fields and methods of
 * the class have been visited.// www  .j ava2 s  .c  o m
 */
@Override
public void visitEnd() {
    if (isClass && !visitedStaticMethod) {
        // add static block if it doesn't exists
        MethodVisitor mv = cv.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
        mv = new ExpirationDateMethodAdapter(mv, expirationDate);
        mv.visitCode();
        mv.visitInsn(RETURN);
        mv.visitMaxs(0, 0);
        mv.visitEnd();
    }

    super.visitEnd();
}

From source file:com.quartercode.jtimber.rh.agent.util.ASMUtils.java

License:Open Source License

/**
 * Generates the instructions to call the {@code addParent()} or {@code removeParent()} method on an object using {@code this} as the parent.
 * Note that an instanceof check is be executed beforehand in order to check whether the object is non-null and parent-aware.<br>
 * <br>/*from www  . j av a  2 s  .  co  m*/
 * The object the operation should be performed on needs to be the topmost value on the stack when the generated instructions are entered.
 * The rest of the stack is ignored by the generated instructions.
 * 
 * @param mv The {@link MethodVisitor} that should be used to generate the instructions.
 * @param methodName The name of the method to call ({@code "addParent"} or {@code "removeParent"}).
 */
public static void generateAddOrRemoveThisAsParent(MethodVisitor mv, String methodName) {

    // Skip the if-block if the condition below isn't true
    Label endIf = new Label();
    mv.visitInsn(DUP);
    mv.visitTypeInsn(INSTANCEOF, PARENT_AWARE_CLASS);
    mv.visitJumpInsn(IFEQ, endIf);

    /* if (object instanceof ParentAware) */
    {
        // Push a copy of the value because the parent watcher method will be invoked on it
        mv.visitInsn(DUP);

        // Push "this" because it will be used as the first argument for the following method call
        mv.visitVarInsn(ALOAD, 0);

        // Invoke the parent watcher method on the value (which implements the "ParentAware" interface) using "this" as the first argument
        mv.visitMethodInsn(INVOKEINTERFACE, PARENT_AWARE_CLASS, methodName, "(" + NODE_DESC + ")V", true);
    }

    mv.visitLabel(endIf);
}