Example usage for org.objectweb.asm Opcodes RETURN

List of usage examples for org.objectweb.asm Opcodes RETURN

Introduction

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

Prototype

int RETURN

To view the source code for org.objectweb.asm Opcodes RETURN.

Click Source Link

Usage

From source file:com.navercorp.pinpoint.profiler.instrument.ASMMethodVariables.java

License:Apache License

boolean isReturnCode(final int opcode) {
    return opcode == Opcodes.IRETURN || opcode == Opcodes.LRETURN || opcode == Opcodes.FRETURN
            || opcode == Opcodes.DRETURN || opcode == Opcodes.ARETURN || opcode == Opcodes.RETURN;
}

From source file:com.nginious.http.serialize.JsonSerializerCreator.java

License:Apache License

/**
 * Creates a JSON serializer for the specified bean class unless a serializer has already been
 * created. Created serializers are cached and returned on subsequent calls to this method.
 * //w ww  .ja va  2 s.  co m
 * @param factory serializer factory
 * @param <T> class type for bean
 * @param beanClazz bean class for which a serializer should be created
 * @return the created serializer
 * @throws SerializerFactoryException if unable to create serializer or class is not a bean
 */
@SuppressWarnings("unchecked")
<T> JsonSerializer<T> create(SerializerFactoryImpl factory, Class<T> beanClazz)
        throws SerializerFactoryException {
    JsonSerializer<T> serializer = (JsonSerializer<T>) serializers.get(beanClazz);

    if (serializer != null) {
        return serializer;
    }

    try {
        synchronized (this) {
            serializer = (JsonSerializer<T>) serializers.get(beanClazz);

            if (serializer != null) {
                return serializer;
            }

            checkSerializability(beanClazz, "json");
            String intBeanClazzName = Serialization.createInternalClassName(beanClazz);
            Method[] methods = beanClazz.getMethods();

            String intSerializerClazzName = new StringBuffer(intBeanClazzName).append("JsonSerializer")
                    .toString();

            // Create class
            ClassWriter writer = new ClassWriter(0);
            String signature = Serialization.createClassSignature("com/nginious/http/serialize/JsonSerializer",
                    intBeanClazzName);
            writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intSerializerClazzName, signature,
                    "com/nginious/http/serialize/JsonSerializer", null);

            // Create constructor
            Serialization.createConstructor(writer, "com/nginious/http/serialize/JsonSerializer");

            // Create serialize method
            MethodVisitor visitor = createSerializeMethod(writer, intBeanClazzName);

            for (Method method : methods) {
                Serializable info = method.getAnnotation(Serializable.class);
                boolean canSerialize = info == null
                        || (info != null && info.serialize() && info.types().indexOf("json") > -1);

                if (canSerialize && method.getName().startsWith("get") && !method.getName().equals("getClass")
                        && method.getReturnType() != null && method.getParameterTypes().length == 0) {
                    Class<?> returnType = method.getReturnType();
                    String propertyName = getPropertyName(method);

                    if (returnType.isPrimitive()) {
                        if (returnType.equals(boolean.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeBoolean",
                                    "Z", "Z", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(double.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDouble",
                                    "D", "D", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(float.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeFloat",
                                    "F", "F", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(int.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeInt",
                                    "I", "I", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(long.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeLong",
                                    "J", "J", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(short.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeShort",
                                    "S", "S", intBeanClazzName, method.getName(), propertyName);
                        }
                    } else if (Collection.class.isAssignableFrom(returnType)) {
                        Class<?> collectionType = canSerializeGenericCollectionType(method, "json");

                        if (collectionType != null) {
                            createBeanCollectionSerializationCode(visitor, intBeanClazzName, method.getName(),
                                    propertyName, returnType, collectionType);
                        } else {
                            createObjectCollectionSerializationCode(visitor, returnType, intBeanClazzName,
                                    method.getName(), propertyName);
                        }
                    } else if (returnType.equals(Calendar.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeCalendar",
                                "Ljava/util/Calendar;", "Ljava/util/Calendar;", intBeanClazzName,
                                method.getName(), propertyName);
                    } else if (returnType.equals(Date.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDate",
                                "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else if (returnType.equals(String.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeString",
                                "Ljava/lang/String;", "Ljava/lang/String;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else {
                        info = returnType.getAnnotation(Serializable.class);
                        canSerialize = info != null && info.serialize() && info.types().indexOf("json") > -1;

                        if (canSerialize) {
                            createBeanSerializationCode(visitor, method.getName(), propertyName, returnType,
                                    intBeanClazzName);
                        } else {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeObject",
                                    "Ljava/lang/Object;", "L" + returnType.getName().replace('.', '/') + ";",
                                    intBeanClazzName, method.getName(), propertyName);
                        }
                    }
                }
            }

            visitor.visitInsn(Opcodes.RETURN);
            visitor.visitMaxs(8, 7);
            visitor.visitEnd();

            writer.visitEnd();
            byte[] clazzBytes = writer.toByteArray();
            ClassLoader controllerLoader = null;

            if (classLoader.hasLoaded(beanClazz)) {
                controllerLoader = beanClazz.getClassLoader();
            } else {
                controllerLoader = this.classLoader;
            }

            Class<?> clazz = Serialization.loadClass(controllerLoader, intSerializerClazzName.replace('/', '.'),
                    clazzBytes);
            serializer = (JsonSerializer<T>) clazz.newInstance();
            String propertyName = Serialization.createPropertyNameFromClass(beanClazz);
            serializer.setName(propertyName);
            serializer.setType(beanClazz);
            serializer.setSerializerFactory(factory);
            serializers.put(beanClazz, serializer);
            return serializer;
        }
    } catch (IllegalAccessException e) {
        throw new SerializerFactoryException("Can't create JSON serializer for " + beanClazz.getName(), e);
    } catch (InstantiationException e) {
        throw new SerializerFactoryException("Can't create JSON serializer for " + beanClazz.getName(), e);
    }
}

From source file:com.nginious.http.serialize.JsonSerializerCreator.java

License:Apache License

/**
 * Creates bytecode which implements the {@link JsonSerializer#serializeProperties(org.json.JSONObject, Object)}
 * method for the serializer class being created.
 * //from w w w. j  av a 2 s  .  co  m
 * @param writer class byte code writer
 * @param intBeanClazzName binary name of serializer class being generated
 * @return a method visitor for writing bytecode inside the generated method
 */
private MethodVisitor createSerializeMethod(ClassWriter writer, String intBeanClazzName) {
    String[] exceptions = { "com/nginious/serialize/SerializerException" };
    MethodVisitor visitor = writer.visitMethod(Opcodes.ACC_PUBLIC, "serializeProperties",
            "(Lorg/json/JSONObject;Ljava/lang/Object;)V", null, exceptions);
    visitor.visitCode();

    Label label = new Label();
    visitor.visitVarInsn(Opcodes.ALOAD, 2);
    visitor.visitJumpInsn(Opcodes.IFNONNULL, label);
    visitor.visitInsn(Opcodes.RETURN);
    visitor.visitLabel(label);
    visitor.visitVarInsn(Opcodes.ALOAD, 2);
    visitor.visitTypeInsn(Opcodes.CHECKCAST, intBeanClazzName);
    visitor.visitIntInsn(Opcodes.ASTORE, 3);

    return visitor;
}

From source file:com.nginious.http.serialize.Serialization.java

License:Apache License

/**
 * Creates bytecode for a no argument constructor. The created bytecode also calls the no argument constructor
 * in the superclass with the specified name.
 * //w w w  .jav a2s  .  co m
 * @param writer bytecode writer
 * @param superclassName binary name of superclass
 */
static 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.nginious.http.serialize.XmlSerializerCreator.java

License:Apache License

/**
 * Creates a XML serializer for the specified bean class unless a serializer has already been
 * created. Created serializers are cached and returned on subsequent calls to this method.
 * //from   w  ww .j a  v a  2s. c  om
 * @param factory serializer factory
 * @param <T> class type for bean
 * @param beanClazz bean class for which a serializer should be created
 * @return the created serializer
 * @throws SerializerFactoryException if unable to create serializer or class is not a bean
 */
@SuppressWarnings("unchecked")
<T> XmlSerializer<T> create(SerializerFactoryImpl factory, Class<T> beanClazz)
        throws SerializerFactoryException {
    XmlSerializer<T> serializer = (XmlSerializer<T>) serializers.get(beanClazz);

    if (serializer != null) {
        return serializer;
    }

    try {
        synchronized (this) {
            checkSerializability(beanClazz, "xml");
            String intBeanClazzName = Serialization.createInternalClassName(beanClazz);
            Method[] methods = beanClazz.getMethods();

            String intSerializerClazzName = new StringBuffer(intBeanClazzName).append("XmlSerializer")
                    .toString();

            // Create class
            ClassWriter writer = new ClassWriter(0);
            String signature = Serialization.createClassSignature("com/nginious/http/serialize/XmlSerializer",
                    intBeanClazzName);
            writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intSerializerClazzName, signature,
                    "com/nginious/http/serialize/XmlSerializer", null);

            // Create constructor
            Serialization.createConstructor(writer, "com/nginious/http/serialize/XmlSerializer");

            // Create serialize method
            MethodVisitor visitor = createSerializeMethod(writer, intBeanClazzName);

            for (Method method : methods) {
                Serializable info = method.getAnnotation(Serializable.class);
                boolean canSerialize = info == null
                        || (info != null && info.serialize() && info.types().indexOf("xml") > -1);

                if (canSerialize && method.getName().startsWith("get") && !method.getName().equals("getClass")
                        && method.getReturnType() != null && method.getParameterTypes().length == 0) {
                    Class<?> returnType = method.getReturnType();
                    String propertyName = getPropertyName(method);

                    if (returnType.isPrimitive()) {
                        if (returnType.equals(boolean.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeBoolean",
                                    "Z", "Z", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(double.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDouble",
                                    "D", "D", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(float.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeFloat",
                                    "F", "F", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(int.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeInt",
                                    "I", "I", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(long.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeLong",
                                    "J", "J", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(short.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeShort",
                                    "S", "S", intBeanClazzName, method.getName(), propertyName);
                        }
                    } else if (Collection.class.isAssignableFrom(returnType)) {
                        Class<?> collectionType = canSerializeGenericCollectionType(method, "json");

                        if (collectionType != null) {
                            createBeanCollectionSerializationCode(visitor, intBeanClazzName, method.getName(),
                                    propertyName, returnType, collectionType);
                        } else {
                            createObjectCollectionSerializationCode(visitor, intBeanClazzName, method.getName(),
                                    propertyName, returnType);
                        }
                    } else if (returnType.equals(Calendar.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeCalendar",
                                "Ljava/util/Calendar;", "Ljava/util/Calendar;", intBeanClazzName,
                                method.getName(), propertyName);
                    } else if (returnType.equals(Date.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDate",
                                "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else if (returnType.equals(String.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeString",
                                "Ljava/lang/String;", "Ljava/lang/String;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else {
                        info = returnType.getAnnotation(Serializable.class);
                        canSerialize = info != null && info.serialize() && info.types().indexOf("json") > -1;

                        if (canSerialize) {
                            createBeanSerializationCode(visitor, method.getName(), propertyName, returnType,
                                    intBeanClazzName);
                        } else {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeObject",
                                    "Ljava/lang/Object;", "L" + returnType.getName().replace('.', '/') + ";",
                                    intBeanClazzName, method.getName(), propertyName);
                        }
                    }
                }
            }

            visitor.visitInsn(Opcodes.RETURN);
            visitor.visitMaxs(7, 6);
            visitor.visitEnd();

            writer.visitEnd();
            byte[] clazzBytes = writer.toByteArray();
            ClassLoader controllerLoader = null;

            if (classLoader.hasLoaded(beanClazz)) {
                controllerLoader = beanClazz.getClassLoader();
            } else {
                controllerLoader = this.classLoader;
            }

            Class<?> clazz = Serialization.loadClass(controllerLoader, intSerializerClazzName.replace('/', '.'),
                    clazzBytes);
            serializer = (XmlSerializer<T>) clazz.newInstance();
            serializer.setName(Serialization.createPropertyNameFromClass(beanClazz));
            serializer.setType(beanClazz);
            serializer.setSerializerFactory(factory);
            serializers.put(beanClazz, serializer);
            return serializer;
        }
    } catch (IllegalAccessException e) {
        throw new SerializerFactoryException("Can't create XML serializer for " + beanClazz.getName(), e);
    } catch (InstantiationException e) {
        throw new SerializerFactoryException("Can't create XML serializer for " + beanClazz.getName(), e);
    }
}

From source file:com.nginious.http.serialize.XmlSerializerCreator.java

License:Apache License

/**
 * Creates bytecode which implements the {@link XmlSerializer#serializeProperties(javax.xml.transform.sax.TransformerHandler, Object)}
 * method for the serializer class being created.
 * //  www.  jav a 2  s  . c o m
 * @param writer class byte code writer
 * @param intBeanClazzName binary name of serializer class being generated
 * @return a method visitor for writing bytecode inside the generated method
 */
private MethodVisitor createSerializeMethod(ClassWriter writer, String intBeanClazzName) {
    String[] exceptions = { "com/nginious/serialize/SerializerException" };
    MethodVisitor visitor = writer.visitMethod(Opcodes.ACC_PUBLIC, "serializeProperties",
            "(Ljavax/xml/transform/sax/TransformerHandler;Ljava/lang/Object;)V", null, exceptions);
    visitor.visitCode();

    Label label = new Label();
    visitor.visitVarInsn(Opcodes.ALOAD, 2);
    visitor.visitJumpInsn(Opcodes.IFNONNULL, label);
    visitor.visitInsn(Opcodes.RETURN);
    visitor.visitLabel(label);
    visitor.visitVarInsn(Opcodes.ALOAD, 0);
    visitor.visitVarInsn(Opcodes.ALOAD, 2);
    visitor.visitTypeInsn(Opcodes.CHECKCAST, intBeanClazzName);
    visitor.visitIntInsn(Opcodes.ASTORE, 3);
    return visitor;
}

From source file:com.nginious.http.xsp.expr.ExpressionCompiler.java

License:Apache License

/**
 * Creates a compiled expression from the specified tree value node expression. The class bytecode for the 
 * compiled expression is generated at runtime.
 * //w ww  .  j  av  a2 s  . c o m
 * @param uncompiled the uncompiled tree value node expression
 * @return the compiled expression
 * @throws ExpressionException if unable to compile expression
 */
public Expression compile(TreeExpression uncompiled) throws ExpressionException {
    ClassWriter writer = new ClassWriter(0);

    // Create class
    String className = classBaseName + classNameCounter.getAndIncrement();
    String classIdentifier = className.replace('.', '/');
    writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, classIdentifier, "L" + classIdentifier + ";",
            "com/nginious/http/xsp/expr/Expression", null);

    // Create constructor
    MethodVisitor visitor = writer.visitMethod(Opcodes.ACC_PROTECTED, "<init>", "()V", null, null);
    visitor.visitCode();
    visitor.visitVarInsn(Opcodes.ALOAD, 0);
    visitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "com/nginious/http/xsp/expr/Expression", "<init>", "()V");
    visitor.visitInsn(Opcodes.RETURN);
    visitor.visitMaxs(1, 1);
    visitor.visitEnd();

    // protected abstract boolean evaluateBoolean();
    visitor = writer.visitMethod(Opcodes.ACC_PROTECTED, "evaluateBoolean", "()Z", null, null);

    if (uncompiled.getType() == Type.BOOLEAN) {
        uncompiled.compile(visitor);
    } else if (uncompiled.getType() == Type.DOUBLE) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateDouble", "()D");

        Label endLabel = new Label();
        Label falseLabel = new Label();
        visitor.visitLdcInsn(0.0d);
        visitor.visitInsn(Opcodes.DCMPL);
        visitor.visitJumpInsn(Opcodes.IFEQ, falseLabel);
        visitor.visitLdcInsn(true);
        visitor.visitJumpInsn(Opcodes.GOTO, endLabel);
        visitor.visitLabel(falseLabel);
        visitor.visitLdcInsn(false);
        visitor.visitLabel(endLabel);
    } else if (uncompiled.getType() == Type.INT) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateInt", "()I");

        Label endLabel = new Label();
        Label falseLabel = new Label();
        visitor.visitLdcInsn(0);
        visitor.visitJumpInsn(Opcodes.IFNE, falseLabel);
        visitor.visitLdcInsn(true);
        visitor.visitJumpInsn(Opcodes.GOTO, endLabel);
        visitor.visitLabel(falseLabel);
        visitor.visitLdcInsn(false);
        visitor.visitLabel(endLabel);
    } else if (uncompiled.getType() == Type.STRING) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateString",
                "()Ljava/lang/String;");
        visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "parseBoolean",
                "(Ljava/lang/String;)Z");
    }

    visitor.visitInsn(Opcodes.IRETURN);
    visitor.visitMaxs(5, 5);
    visitor.visitEnd();

    // protected abstract int evaluateInt();
    visitor = writer.visitMethod(Opcodes.ACC_PROTECTED, "evaluateInt", "()I", null, null);

    if (uncompiled.getType() == Type.BOOLEAN) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateBoolean", "()Z");

        Label endLabel = new Label();
        Label falseLabel = new Label();
        visitor.visitJumpInsn(Opcodes.IFEQ, falseLabel);
        visitor.visitLdcInsn(1);
        visitor.visitJumpInsn(Opcodes.GOTO, endLabel);
        visitor.visitLabel(falseLabel);
        visitor.visitLdcInsn(0);
        visitor.visitLabel(endLabel);
    } else if (uncompiled.getType() == Type.DOUBLE) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateDouble", "()D");
        visitor.visitInsn(Opcodes.D2I);
    } else if (uncompiled.getType() == Type.INT) {
        uncompiled.compile(visitor);
    } else if (uncompiled.getType() == Type.STRING) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateString",
                "()Ljava/lang/String;");
        visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Integer", "parseInt", "(Ljava/lang/String;)I");
    }

    visitor.visitInsn(Opcodes.IRETURN);
    visitor.visitMaxs(5, 5);
    visitor.visitEnd();

    // protected abstract double evaluateDouble();
    visitor = writer.visitMethod(Opcodes.ACC_PROTECTED, "evaluateDouble", "()D", null, null);

    if (uncompiled.getType() == Type.BOOLEAN) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateBoolean", "()Z");

        Label endLabel = new Label();
        Label falseLabel = new Label();
        visitor.visitJumpInsn(Opcodes.IFEQ, falseLabel);
        visitor.visitLdcInsn(1.0d);
        visitor.visitJumpInsn(Opcodes.GOTO, endLabel);
        visitor.visitLabel(falseLabel);
        visitor.visitLdcInsn(0.0d);
        visitor.visitLabel(endLabel);
    } else if (uncompiled.getType() == Type.DOUBLE) {
        uncompiled.compile(visitor);
    } else if (uncompiled.getType() == Type.INT) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateInt", "()I");
        visitor.visitInsn(Opcodes.I2D);
    } else if (uncompiled.getType() == Type.STRING) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateString",
                "()Ljava/lang/String;");
        visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Double", "parseDouble",
                "(Ljava/lang/String;)D");
    }

    visitor.visitInsn(Opcodes.DRETURN);
    visitor.visitMaxs(5, 5);
    visitor.visitEnd();

    // protected abstract String evaluateString();
    visitor = writer.visitMethod(Opcodes.ACC_PROTECTED, "evaluateString", "()Ljava/lang/String;", null, null);

    if (uncompiled.getType() == Type.BOOLEAN) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateBoolean", "()Z");
        visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "toString", "(Z)Ljava/lang/String;");
    } else if (uncompiled.getType() == Type.DOUBLE) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateDouble", "()D");
        visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Double", "toString", "(D)Ljava/lang/String;");
    } else if (uncompiled.getType() == Type.INT) {
        visitor.visitVarInsn(Opcodes.ALOAD, 0); // this
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, classIdentifier, "evaluateInt", "()I");
        visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Integer", "toString", "(I)Ljava/lang/String;");
    } else if (uncompiled.getType() == Type.STRING) {
        uncompiled.compile(visitor);
    }

    visitor.visitInsn(Opcodes.ARETURN);
    visitor.visitMaxs(6, 6);
    visitor.visitEnd();

    // public abstract Type getType();        
    visitor = writer.visitMethod(Opcodes.ACC_PUBLIC, "getType", "()Lcom/nginious/http/xsp/expr/Type;", null,
            null);

    if (uncompiled.getType() == Type.BOOLEAN) {
        visitor.visitFieldInsn(Opcodes.GETSTATIC, "com/nginious/http/xsp/expr/Type", "BOOLEAN",
                "Lcom/nginious/http/xsp/expr/Type;");
        visitor.visitInsn(Opcodes.ARETURN);
    } else if (uncompiled.getType() == Type.DOUBLE) {
        visitor.visitFieldInsn(Opcodes.GETSTATIC, "com/nginious/http/xsp/expr/Type", "DOUBLE",
                "Lcom/nginious/http/xsp/expr/Type;");
        visitor.visitInsn(Opcodes.ARETURN);
    } else if (uncompiled.getType() == Type.INT) {
        visitor.visitFieldInsn(Opcodes.GETSTATIC, "com/nginious/http/xsp/expr/Type", "INT",
                "Lcom/nginious/http/xsp/expr/Type;");
        visitor.visitInsn(Opcodes.ARETURN);
    } else if (uncompiled.getType() == Type.STRING) {
        visitor.visitFieldInsn(Opcodes.GETSTATIC, "com/nginious/http/xsp/expr/Type", "STRING",
                "Lcom/nginious/http/xsp/expr/Type;");
        visitor.visitInsn(Opcodes.ARETURN);
    }

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

    try {
        writer.visitEnd();
        byte[] clazzBytes = writer.toByteArray();
        Class<?> clazz = loadClass(className, clazzBytes);
        return (Expression) clazz.newInstance();
    } catch (Exception e) {
        throw new ExpressionException("Can't instantiate compiled expression", e);
    }
}

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

License:Apache License

/**
 * Creates bytecode in a separate method for evaluating this for each tag part.
 * /*w ww  .  j  a v a  2 s  .co 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 {
    String[] exceptions = { "com/nginious/http/xsp/XspException" };
    MethodVisitor visitor = writer.visitMethod(Opcodes.ACC_PRIVATE, this.methodName,
            "(Lcom/nginious/http/HttpRequest;Lcom/nginious/http/HttpResponse;Ljava/lang/StringBuffer;)V", null,
            exceptions);
    visitor.visitCode();

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

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

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

        if (expr.getType() != Type.ANY) {
            throw new XspException("Expression in attribute set in tag " + getName()
                    + " is not an attribute or bean property " + " at line " + getLocationDescriptor());
        }

        expr.compile(visitor, Type.ANY);
        visitor.visitTypeInsn(Opcodes.CHECKCAST, "java/util/Collection");
        visitor.visitVarInsn(Opcodes.ASTORE, 4);
    } catch (ExpressionException e) {
        throw new XspException("Invalid expression in attribute set in tag " + getName() + " at line "
                + getLocationDescriptor(), e);
    }

    Label labelOut = new Label();
    visitor.visitVarInsn(Opcodes.ALOAD, 4);
    visitor.visitJumpInsn(Opcodes.IFNULL, labelOut);

    // Start
    if (this.start != null) {
        start.compile(visitor, Type.INT);
    } else {
        visitor.visitLdcInsn((int) 0);
    }

    visitor.visitVarInsn(Opcodes.ISTORE, 5);

    // End
    if (this.end != null) {
        end.compile(visitor, Type.INT);
    } else {
        visitor.visitVarInsn(Opcodes.ALOAD, 4);
        visitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Collection", "size", "()I");
    }

    visitor.visitVarInsn(Opcodes.ISTORE, 6);

    // Step
    if (this.step != null) {
        step.compile(visitor, Type.INT);
    } else {
        visitor.visitLdcInsn((int) 1);
    }

    visitor.visitVarInsn(Opcodes.ISTORE, 7);

    // Current pos
    visitor.visitLdcInsn(0);
    visitor.visitVarInsn(Opcodes.ISTORE, 8);

    visitor.visitVarInsn(Opcodes.ALOAD, 4);
    visitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Collection", "iterator",
            "()Ljava/util/Iterator;");
    visitor.visitVarInsn(Opcodes.ASTORE, 9);

    Label labelStart = new Label();

    // Start of loop
    visitor.visitLabel(labelStart);

    // iterator.hasNext();
    visitor.visitVarInsn(Opcodes.ALOAD, 9);
    visitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Iterator", "hasNext", "()Z");
    visitor.visitJumpInsn(Opcodes.IFEQ, labelOut);

    // iterator.next();
    visitor.visitVarInsn(Opcodes.ALOAD, 9);
    visitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/Iterator", "next", "()Ljava/lang/Object;");
    visitor.visitVarInsn(Opcodes.ASTORE, 10);

    // pos >= start && pos <= end && (pos - start) % step == 0
    Label labelIncr = new Label();

    visitor.visitVarInsn(Opcodes.ILOAD, 8);
    visitor.visitVarInsn(Opcodes.ILOAD, 5);
    visitor.visitJumpInsn(Opcodes.IF_ICMPLT, labelIncr);

    visitor.visitVarInsn(Opcodes.ILOAD, 8);
    visitor.visitVarInsn(Opcodes.ILOAD, 6);
    visitor.visitJumpInsn(Opcodes.IF_ICMPGT, labelIncr);

    visitor.visitVarInsn(Opcodes.ILOAD, 8);
    visitor.visitVarInsn(Opcodes.ILOAD, 5);
    visitor.visitInsn(Opcodes.ISUB);
    visitor.visitVarInsn(Opcodes.ILOAD, 7);
    visitor.visitInsn(Opcodes.IREM);
    visitor.visitJumpInsn(Opcodes.IFNE, labelIncr);

    visitor.visitVarInsn(Opcodes.ALOAD, 1);
    varName.compile(visitor, Type.STRING);
    visitor.visitVarInsn(Opcodes.ALOAD, 10);
    visitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "com/nginious/http/HttpRequest", "setAttribute",
            "(Ljava/lang/String;Ljava/lang/Object;)V");

    // Call sub parts
    for (XspPart part : this.contentParts) {
        part.compile(intClassName, writer, visitor);
    }

    // pos++
    visitor.visitLabel(labelIncr);
    visitor.visitIincInsn(8, 1);
    visitor.visitJumpInsn(Opcodes.GOTO, labelStart);

    visitor.visitLabel(labelOut);
    visitor.visitInsn(Opcodes.RETURN);

    visitor.visitLabel(startCatchLabel);

    visitor.visitVarInsn(Opcodes.ASTORE, 3);
    visitor.visitTypeInsn(Opcodes.NEW, "com/nginious/http/xsp/XspException");
    visitor.visitInsn(Opcodes.DUP);
    visitor.visitLdcInsn("Attribute set contains an invalid collection for tag " + getName() + " at "
            + getLocationDescriptor());
    visitor.visitVarInsn(Opcodes.ALOAD, 3);
    visitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "com/nginious/http/xsp/XspException", "<init>",
            "(Ljava/lang/String;Ljava/lang/Throwable;)V");
    visitor.visitInsn(Opcodes.ATHROW);

    visitor.visitMaxs(11, 11);
    visitor.visitEnd();
}

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

License:Apache License

/**
 * Creates bytecode in a separate method for evaluating this format date tag part.
 * //www  . j  a va 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 {
    String[] exceptions = { "com/nginious/http/xsp/XspException" };
    MethodVisitor visitor = writer.visitMethod(Opcodes.ACC_PRIVATE, this.methodName,
            "(Lcom/nginious/http/HttpRequest;Lcom/nginious/http/HttpResponse;Ljava/lang/StringBuffer;)V", null,
            exceptions);
    visitor.visitCode();

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

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

    visitor.visitLabel(tryLabel);

    visitor.visitTypeInsn(Opcodes.NEW, "java/text/SimpleDateFormat");
    visitor.visitInsn(Opcodes.DUP);
    pattern.compile(visitor, Type.STRING);
    visitor.visitVarInsn(Opcodes.ALOAD, 2);
    visitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "com/nginious/http/HttpResponse", "getLocale",
            "()Ljava/util/Locale;");
    visitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/text/SimpleDateFormat", "<init>",
            "(Ljava/lang/String;Ljava/util/Locale;)V");
    visitor.visitVarInsn(Opcodes.ASTORE, 4);

    if (this.timeZone != null) {
        visitor.visitVarInsn(Opcodes.ALOAD, 4);
        String timeZoneDesc = timeZone.getStringContent();
        visitor.visitLdcInsn(timeZoneDesc);
        visitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/TimeZone", "getTimeZone",
                "(Ljava/lang/String;)Ljava/util/TimeZone;");
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/text/SimpleDateFormat", "setTimeZone",
                "(Ljava/util/TimeZone;)V");
    }

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

        if (expr.getType() != Type.ANY) {
            throw new XspException("Expression in attribute value in tag " + getName()
                    + " is not an attribute or bean property " + " at line " + getLocationDescriptor());
        }

        expr.compile(visitor, Type.ANY);
        visitor.visitTypeInsn(Opcodes.CHECKCAST, "java/util/Date");
        visitor.visitVarInsn(Opcodes.ASTORE, 5);
    } catch (ExpressionException e) {
        throw new XspException("Invalid expression in attribute value in tag " + getName() + " at line "
                + getLocationDescriptor(), e);
    }

    Label nullLabel = new Label();
    visitor.visitVarInsn(Opcodes.ALOAD, 5);
    visitor.visitJumpInsn(Opcodes.IFNULL, nullLabel);

    visitor.visitVarInsn(Opcodes.ALOAD, 4);
    visitor.visitVarInsn(Opcodes.ALOAD, 5);
    visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/text/SimpleDateFormat", "format",
            "(Ljava/util/Date;)Ljava/lang/String;");
    visitor.visitVarInsn(Opcodes.ASTORE, 5);

    if (this.var != null) {
        visitor.visitVarInsn(Opcodes.ALOAD, 1);
        var.compile(visitor, Type.STRING);
        visitor.visitVarInsn(Opcodes.ALOAD, 5);
        visitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "com/nginious/http/HttpRequest", "setAttribute",
                "(Ljava/lang/String;Ljava/lang/Object;)V");
    } else {
        visitor.visitVarInsn(Opcodes.ALOAD, 3);
        visitor.visitVarInsn(Opcodes.ALOAD, 5);
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuffer", "append",
                "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
        visitor.visitInsn(Opcodes.POP);
    }

    visitor.visitLabel(nullLabel);
    visitor.visitInsn(Opcodes.RETURN);

    visitor.visitLabel(startCatchLabel);

    visitor.visitVarInsn(Opcodes.ASTORE, 3);
    visitor.visitTypeInsn(Opcodes.NEW, "com/nginious/http/xsp/XspException");
    visitor.visitInsn(Opcodes.DUP);
    visitor.visitLdcInsn(
            "Attribute value contains an invalid date for tag " + getName() + " at " + getLocationDescriptor());
    visitor.visitVarInsn(Opcodes.ALOAD, 3);
    visitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "com/nginious/http/xsp/XspException", "<init>",
            "(Ljava/lang/String;Ljava/lang/Throwable;)V");
    visitor.visitInsn(Opcodes.ATHROW);

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

    super.compileMethod(intClassName, writer);
}

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

License:Apache License

/**
 * Creates bytecode in a separate method for evaluating this format number tag part.
 * //from w  w  w.  j  av a 2s.c  om
 * @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 {
    String[] exceptions = { "com/nginious/http/xsp/XspException" };
    MethodVisitor visitor = writer.visitMethod(Opcodes.ACC_PRIVATE, this.methodName,
            "(Lcom/nginious/http/HttpRequest;Lcom/nginious/http/HttpResponse;Ljava/lang/StringBuffer;)V", null,
            exceptions);
    visitor.visitCode();

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

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

    visitor.visitLabel(tryLabel);

    visitor.visitTypeInsn(Opcodes.NEW, "java/text/DecimalFormat");
    visitor.visitInsn(Opcodes.DUP);
    pattern.compile(visitor, Type.STRING);
    visitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/text/DecimalFormat", "<init>",
            "(Ljava/lang/String;)V");
    visitor.visitVarInsn(Opcodes.ASTORE, 4);

    ExpressionParser parser = null;
    TreeExpression expr = null;

    try {
        String expression = value.getExpressionContent();
        parser = new ExpressionParser();
        expr = parser.parse(expression);

        if (expr.getType() != Type.ANY) {
            throw new XspException("Expression in attribute value in tag " + getName()
                    + " is not an attribute or bean property " + " at line " + getLocationDescriptor());
        }
    } catch (ExpressionException e) {
        throw new XspException("Invalid expression in attribute value in tag " + getName() + " at line "
                + getLocationDescriptor(), e);
    }

    visitor.visitVarInsn(Opcodes.ALOAD, 4);
    expr.compile(visitor, Type.DOUBLE);
    visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/text/DecimalFormat", "format",
            "(D)Ljava/lang/String;");
    visitor.visitVarInsn(Opcodes.ASTORE, 5);

    if (this.var != null) {
        visitor.visitVarInsn(Opcodes.ALOAD, 1);
        var.compile(visitor, Type.STRING);
        visitor.visitVarInsn(Opcodes.ALOAD, 5);
        visitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, "com/nginious/http/HttpRequest", "setAttribute",
                "(Ljava/lang/String;Ljava/lang/Object;)V");
    } else {
        visitor.visitVarInsn(Opcodes.ALOAD, 3);
        visitor.visitVarInsn(Opcodes.ALOAD, 5);
        visitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuffer", "append",
                "(Ljava/lang/String;)Ljava/lang/StringBuffer;");
        visitor.visitInsn(Opcodes.POP);
    }

    visitor.visitInsn(Opcodes.RETURN);

    visitor.visitLabel(startCatchLabel);

    visitor.visitVarInsn(Opcodes.ASTORE, 4);
    visitor.visitTypeInsn(Opcodes.NEW, "com/nginious/http/xsp/XspException");
    visitor.visitInsn(Opcodes.DUP);
    visitor.visitLdcInsn("Attribute value contains an invalid number for tag " + getName() + " at "
            + getLocationDescriptor());
    visitor.visitVarInsn(Opcodes.ALOAD, 4);
    visitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "com/nginious/http/xsp/XspException", "<init>",
            "(Ljava/lang/String;Ljava/lang/Throwable;)V");
    visitor.visitInsn(Opcodes.ATHROW);

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

    super.compileMethod(intClassName, writer);
}