Example usage for org.objectweb.asm Opcodes V1_6

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

Introduction

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

Prototype

int V1_6

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

Click Source Link

Usage

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.
 * /* w w  w. jav a 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> 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.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  w w.  j  a v  a 2 s . c om
 * @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.XspCompiler.java

License:Apache License

/**
 * Creates subclass of {@link XspService} for the XSP file represented by the specified document
 * tree node structure./*from   ww w.  j  a  va  2s  .c  o  m*/
 * 
 * @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.sixrr.metrics.profile.instanceHolder.MetricInstanceHolder.java

License:Apache License

private void loadMetricsFromProviders() {
    for (MetricProvider provider : MetricProvider.EXTENSION_POINT_NAME.getExtensions()) {
        final List<Class<? extends Metric>> classesForProvider = provider.getMetricClasses();

        for (Class<? extends Metric> aClass : classesForProvider) {
            try {
                myMetricInstances.put(aClass.getName(), aClass.newInstance());
            } catch (InstantiationException e) {
                MetricInstanceHolder.LOGGER.error(e);
            } catch (IllegalAccessException e) {
                MetricInstanceHolder.LOGGER.error(e);
            }/* w w w. j  a v a 2 s .c o  m*/
        }
    }

    for (Metric metric : Metric.EP_NAME.getExtensions()) {
        myMetricInstances.put(metric.getClass().getName(), metric);
    }

    // add some magic
    // in Profiles it stored by ClassName. Line Of code is can be handle without new metrics, need only extends  LinesOfCodeProjectMetric with
    // new name
    for (LineOfCodeFileTypeProviderEP ep : LineOfCodeFileTypeProviderEP.EP_NAME.getExtensions()) {
        FileType fileTypeByFileName = FileTypeRegistry.getInstance().findFileTypeByName(ep.fileType);

        if (fileTypeByFileName == null) {
            LOGGER.error("File type is unknown: " + ep.fileType);
            fileTypeByFileName = PlainTextFileType.INSTANCE;
        }
        String lineOfCodeClass = Type.getInternalName(LinesOfCodeProjectMetric.class);
        String className = lineOfCodeClass + "$" + ep.fileType;

        ClassWriter writer = new ClassWriter(Opcodes.F_FULL);
        writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, className, null, lineOfCodeClass, null);

        String desc = Type.getConstructorDescriptor(LinesOfCodeProjectMetric.class.getConstructors()[0]);
        MethodVisitor methodVisitor = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", desc, null, null);

        methodVisitor.visitMaxs(2, 2);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, lineOfCodeClass, "<init>", desc);
        methodVisitor.visitInsn(Opcodes.RETURN);
        methodVisitor.visitEnd();
        writer.visitEnd();

        Class<?> aClass = defineClass(className.replace("/", "."), writer.toByteArray());

        try {
            myMetricInstances.put(aClass.getName(),
                    (Metric) aClass.getConstructors()[0].newInstance(fileTypeByFileName));
        } catch (InstantiationException e) {
            LOGGER.error(e);
        } catch (IllegalAccessException e) {
            LOGGER.error(e);
        } catch (InvocationTargetException e) {
            LOGGER.error(e);
        }
    }
}

From source file:dodola.anole.lib.InstantRunTransform.java

License:Apache License

/**
 * Use asm to generate a concrete subclass of the AppPathLoaderImpl class.
 * It only implements one method ://from   w  ww.  ja v a  2  s  .  c o m
 * String[] getPatchedClasses();
 * <p>
 * The method is supposed to return the list of classes that were patched in this iteration.
 * This will be used by the InstantRun runtime to load all patched classes and register them
 * as overrides on the original classes.2 class files.
 *
 * @param patchFileContents list of patched class names.
 * @param outputDir         output directory where to generate the .class file in.
 * @return the generated .class files
 */
public static File writePatchFileContents(List<String> patchFileContents, File outputDir) {

    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;

    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, IncrementalVisitor.APP_PATCHES_LOADER_IMPL,
            null, IncrementalVisitor.ABSTRACT_PATCHES_LOADER_IMPL, null);

    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, IncrementalVisitor.ABSTRACT_PATCHES_LOADER_IMPL, "<init>",
                "()V", false);
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getPatchedClasses", "()[Ljava/lang/String;", null, null);
        mv.visitCode();
        mv.visitIntInsn(Opcodes.BIPUSH, patchFileContents.size());
        mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
        for (int index = 0; index < patchFileContents.size(); index++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.BIPUSH, index);
            mv.visitLdcInsn(patchFileContents.get(index));
            mv.visitInsn(Opcodes.AASTORE);
        }
        mv.visitInsn(Opcodes.ARETURN);
        mv.visitMaxs(4, 1);
        mv.visitEnd();
    }
    cw.visitEnd();

    byte[] classBytes = cw.toByteArray();
    File outputFile = new File(outputDir, IncrementalVisitor.APP_PATCHES_LOADER_IMPL + ".class");
    try {
        Files.createParentDirs(outputFile);
        Files.write(classBytes, outputFile);
        // add the files to the list of files to be processed by subsequent tasks.
        return outputFile;
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:fi.jumi.test.BuildTest.java

License:Open Source License

@Parameters(name = "{0}")
public static Collection<Object[]> data() {
    return asList(new Object[][] {
            { "jumi-actors", asList(Opcodes.V1_6), asList(),
                    asList(MANIFEST, POM_FILES, BASE_PACKAGE + "actors/"), new Deprecations() },

            { "thread-safety-agent", asList(Opcodes.V1_5, Opcodes.V1_6), asList(),
                    asList(MANIFEST, POM_FILES, BASE_PACKAGE + "threadsafetyagent/"), new Deprecations() }, });
}

From source file:jaspex.transactifier.Transactifier.java

License:Open Source License

private byte[] transactify() throws IOException {
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);

    // Copiar mtodos originais inalterados
    cr.accept(new ClassVisitor(Opcodes.ASM4) {
        @Override/*from  w w w. j  a va2  s .  c om*/
        public void visit(int version, int access, String name, String signature, String superName,
                String[] interfaces) {
            cw.visit(version, access, name, signature, superName, interfaces);
        }

        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            if (name.equals("<clinit>"))
                return new EmptyMethodVisitor();
            return cw.visitMethod(access, name, desc, signature, exceptions);
        }

        @Override
        public void visitEnd() {
            cw.visitEnd();
        }
    }, 0);

    // Varivel que contm o ltimo ClassVisitor da "chain" de classvisitors que servem de filtros ao
    // ficheiro original
    ClassVisitor cv = cw;

    // Mtodos alterados so marcados com $transactional no nome
    // Este marcador  temporrio, e ir ser substituido por $speculative mais  frente
    // Nota: Apenas os mtodos so renomeados, os seus INVOKE* ainda no apontam para os
    // $transactional; essa alterao  feita no SpeculativeTransformer
    cv = new ClassVisitor(Opcodes.ASM4, cv) {
        @Override
        public MethodVisitor visitMethod(int access, String name, String desc, String signature,
                String[] exceptions) {
            if (name.equals("<init>")) {
                desc = desc.replace(")", "Ljaspex/MARKER/Transactional;)");
            } else if (!name.equals("<clinit>")) {
                name += "$transactional";
            }
            return cv.visitMethod(access, name, desc, signature, exceptions);
        }
    };

    // Remover ACC_SYNCHRONIZED dos mtodos
    if (Options.REMOVESYNC || _JDKClass)
        cv = new RemoveSyncClassVisitor(cv);

    // Remover MONITORENTER/MONITOREXIT dos mtodos
    if (Options.REMOVEMONITORS)
        cv = new GenericMethodVisitorAdapter(cv, RemoveMonitorsClassVisitor.class);

    // Verificar se existem mtodos com ACC_SYNCHRONIZED ou opcodes MONITORENTER/MONITOREXIT
    if (!_JDKClass)
        cv = new CheckMonitorUsage(cv);

    // Corrigir chamadas a alguns mtodos de java.lang.Object
    cv = new GenericMethodVisitorAdapter(cv, ChangeObjectMethodsMethodVisitor.class, currentClass);

    // Adicionar overrides a alguns mtodos de java.lang.Object
    cv = new AddObjectMethodsClassVisitor(cv, currentClass);

    // Suporte para Arrays
    cv = new GenericMethodVisitorAdapter(cv, ChangeArrayAccessMethodVisitor.class, currentClass, _JDKClass);

    // Adicionar inicializao de offsets usados pela unsafetrans ao clinit da classe
    // Nota: Visitor tem que estar *depois* do FieldTransactifierClassVisitor
    if (!_JDKClass)
        cv = new GenericMethodVisitorAdapter(cv, ChangeClinitMethodVisitor.class, currentClass);

    // Visitor que cria os fields offset e o staticfieldbase
    if (!_JDKClass)
        cv = new FieldTransactifierClassVisitor(cv);

    // Alterar acessos a fields para passarem pela STM
    cv = new GenericMethodVisitorAdapter(cv, ChangeFieldAccessMethodVisitor.class, currentClass, _JDKClass);

    // Modificar string com filename da classe que aparece em excepes
    if (!_JDKClass)
        cv = new MarkAsTransactifiedClassVisitor(cv);

    // Verificar e fazer upgrade da verso da classe, se necessrio
    if (!_JDKClass)
        cv = new ClassVisitor(Opcodes.ASM4, cv) {
            @Override
            public void visit(int version, int access, String name, String signature, String superName,
                    String[] interfaces) {
                // Transactificao precisa de version >= 49, porque usa o MethodVisitor.visitLdcInsn(Type)
                // MethodVisitor.visitLdcInsn(Type), que s funciona a partir dessa verso dos classfiles.
                // http://asm.ow2.org/asm40/javadoc/user/org/objectweb/asm/MethodVisitor.html#visitLdcInsn(java.lang.Object)
                // http://stackoverflow.com/questions/2784791/
                // Caso especial: V1_1  196653, por alguma razo...
                if (version < Opcodes.V1_5 || version == Opcodes.V1_1) {
                    //Log.debug("Class " + name + " has version " + version + ", upgrading it to Java 5");
                    version = Opcodes.V1_5;
                }

                if (version > Opcodes.V1_6 && !name.startsWith("java/")) {
                    Log.warn("Class " + name + " is compiled for Java 7 or newer");
                }

                super.visit(version, access, name, signature, superName, interfaces);
            }
        };

    cr.accept(cv, ClassReader.EXPAND_FRAMES);

    return cw.toByteArray();
}

From source file:jpcsp.Allegrex.compiler.CodeBlock.java

License:Open Source License

private Class<IExecutable> interpret(CompilerContext context) {
    Class<IExecutable> compiledClass = null;

    context.setCodeBlock(this);
    String className = getInternalClassName();
    if (log.isInfoEnabled()) {
        log.info("Compiling for Interpreter " + className);
    }//  w  w w . j  av  a2 s  .c  om

    int computeFlag = ClassWriter.COMPUTE_FRAMES;
    if (context.isAutomaticMaxLocals() || context.isAutomaticMaxStack()) {
        computeFlag |= ClassWriter.COMPUTE_MAXS;
    }
    ClassWriter cw = new ClassWriter(computeFlag);
    ClassVisitor cv = cw;
    if (log.isDebugEnabled()) {
        cv = new CheckClassAdapter(cv);
    }

    StringWriter debugOutput = null;
    if (log.isDebugEnabled()) {
        debugOutput = new StringWriter();
        PrintWriter debugPrintWriter = new PrintWriter(debugOutput);
        cv = new TraceClassVisitor(cv, debugPrintWriter);
    }
    cv.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, className, null, objectInternalName,
            interfacesForExecutable);
    context.startClass(cv);

    addConstructor(cv);
    addNonStaticMethods(context, cv);

    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
            context.getStaticExecMethodName(), context.getStaticExecMethodDesc(), null, exceptions);
    mv.visitCode();
    context.setMethodVisitor(mv);
    context.startMethod();

    context.compileExecuteInterpreter(getStartAddress());

    mv.visitMaxs(context.getMaxStack(), context.getMaxLocals());
    mv.visitEnd();

    cv.visitEnd();

    if (debugOutput != null) {
        log.debug(debugOutput.toString());
    }

    compiledClass = loadExecutable(context, className, cw.toByteArray());

    return compiledClass;
}

From source file:jpcsp.Allegrex.compiler.CodeBlock.java

License:Open Source License

private Class<IExecutable> compile(CompilerContext context) throws ClassFormatError {
    Class<IExecutable> compiledClass = null;

    context.setCodeBlock(this);
    String className = getInternalClassName();
    if (log.isDebugEnabled()) {
        String functionName = Utilities.getFunctionNameByAddress(getStartAddress());

        if (functionName != null) {
            log.debug(String.format("Compiling %s (%s)", className, functionName));
        } else {//  ww  w.  j a v a2s .co  m
            log.debug(String.format("Compiling %s", className));
        }
    }

    prepare(context, context.getMethodMaxInstructions());

    currentSequence = null;
    int computeFlag = ClassWriter.COMPUTE_FRAMES;
    if (context.isAutomaticMaxLocals() || context.isAutomaticMaxStack()) {
        computeFlag |= ClassWriter.COMPUTE_MAXS;
    }
    ClassWriter cw = new ClassWriter(computeFlag);
    ClassVisitor cv = cw;
    if (log.isDebugEnabled()) {
        cv = new CheckClassAdapter(cv);
    }
    StringWriter debugOutput = null;
    if (log.isTraceEnabled()) {
        debugOutput = new StringWriter();
        PrintWriter debugPrintWriter = new PrintWriter(debugOutput);
        cv = new TraceClassVisitor(cv, debugPrintWriter);
    }
    cv.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER, className, null, objectInternalName,
            interfacesForExecutable);
    context.startClass(cv);

    addConstructor(cv);
    addNonStaticMethods(context, cv);

    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
            context.getStaticExecMethodName(), context.getStaticExecMethodDesc(), null, exceptions);
    mv.visitCode();
    context.setMethodVisitor(mv);
    context.startMethod();

    // Jump to the block start if other instructions have been inserted in front
    if (!codeInstructions.isEmpty() && codeInstructions.getFirst().getAddress() != getStartAddress()) {
        mv.visitJumpInsn(Opcodes.GOTO, getCodeInstruction(getStartAddress()).getLabel());
    }

    compile(context, mv, codeInstructions);
    mv.visitMaxs(context.getMaxStack(), context.getMaxLocals());
    mv.visitEnd();

    for (SequenceCodeInstruction sequenceCodeInstruction : sequenceCodeInstructions) {
        if (log.isDebugEnabled()) {
            log.debug("Compiling Sequence " + sequenceCodeInstruction.getMethodName(context));
        }
        currentSequence = sequenceCodeInstruction;
        mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
                sequenceCodeInstruction.getMethodName(context), "()V", null, exceptions);
        mv.visitCode();
        context.setMethodVisitor(mv);
        context.startSequenceMethod();

        compile(context, mv, sequenceCodeInstruction.getCodeSequence().getInstructions());

        context.endSequenceMethod();
        mv.visitMaxs(context.getMaxStack(), context.getMaxLocals());
        mv.visitEnd();
    }
    currentSequence = null;

    cv.visitEnd();

    if (debugOutput != null) {
        log.trace(debugOutput.toString());
    }

    try {
        compiledClass = loadExecutable(context, className, cw.toByteArray());
    } catch (NullPointerException e) {
        log.error("Error while compiling " + className + ": " + e);
    }

    return compiledClass;
}

From source file:lucee.runtime.type.util.ComponentUtil.java

License:Open Source License

/**
 * generate a ComponentJavaAccess (CJA) class from a component
 * a CJA is a dynamic genarted java class that has all method defined inside a component as java methods.
* 
* This is used to generated server side Webservices.
* @param component//from   w  w  w  .  j av a 2 s. c  o m
 * @param isNew 
 * @return
 * @throws PageException
 */
public static Class getComponentJavaAccess(PageContext pc, Component component, RefBoolean isNew,
        boolean create, boolean writeLog, boolean suppressWSbeforeArg, boolean output) throws PageException {
    isNew.setValue(false);
    String classNameOriginal = component.getPageSource().getFullClassName();
    String className = getClassname(component, null).concat("_wrap");
    String real = className.replace('.', '/');
    String realOriginal = classNameOriginal.replace('.', '/');
    Mapping mapping = component.getPageSource().getMapping();
    PhysicalClassLoader cl = null;
    try {
        cl = (PhysicalClassLoader) ((PageContextImpl) pc).getRPCClassLoader(false);
    } catch (IOException e) {
        throw Caster.toPageException(e);
    }
    Resource classFile = cl.getDirectory().getRealResource(real.concat(".class"));
    Resource classFileOriginal = mapping.getClassRootDirectory().getRealResource(realOriginal.concat(".class"));

    // LOAD CLASS
    //print.out(className);
    // check last Mod
    if (classFile.lastModified() >= classFileOriginal.lastModified()) {
        try {
            Class clazz = cl.loadClass(className);
            if (clazz != null && !hasChangesOfChildren(classFile.lastModified(), clazz))
                return registerTypeMapping(clazz);
        } catch (Throwable t) {
        }
    }
    if (!create)
        return null;
    isNew.setValue(true);
    //print.out("new");
    // CREATE CLASS   
    ClassWriter cw = ASMUtil.getClassWriter();
    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, real, null, "java/lang/Object", null);

    //GeneratorAdapter ga = new GeneratorAdapter(Opcodes.ACC_PUBLIC,Page.STATIC_CONSTRUCTOR,null,null,cw);
    BytecodeContext statConstr = null;//new BytecodeContext(null,null,null,cw,real,ga,Page.STATIC_CONSTRUCTOR);

    ///ga = new GeneratorAdapter(Opcodes.ACC_PUBLIC,Page.CONSTRUCTOR,null,null,cw);
    BytecodeContext constr = null;//new BytecodeContext(null,null,null,cw,real,ga,Page.CONSTRUCTOR);

    // field component
    //FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE, "c", "Llucee/runtime/ComponentImpl;", null, null);
    //fv.visitEnd();

    java.util.List<LitString> _keys = new ArrayList<LitString>();

    // remote methods
    Collection.Key[] keys = ComponentProUtil.keys(component, Component.ACCESS_REMOTE);
    int max;
    for (int i = 0; i < keys.length; i++) {
        max = -1;
        while ((max = createMethod(statConstr, constr, _keys, cw, real, component.get(keys[i]), max, writeLog,
                suppressWSbeforeArg, output)) != -1) {
            break;// for overload remove this
        }
    }

    // Constructor
    GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ACC_PUBLIC, CONSTRUCTOR_OBJECT, null, null, cw);
    adapter.loadThis();
    adapter.invokeConstructor(Types.OBJECT, CONSTRUCTOR_OBJECT);
    lucee.transformer.bytecode.Page
            .registerFields(new BytecodeContext(null, statConstr, constr, getPage(statConstr, constr), _keys,
                    cw, real, adapter, CONSTRUCTOR_OBJECT, writeLog, suppressWSbeforeArg, output), _keys);
    adapter.returnValue();
    adapter.endMethod();

    cw.visitEnd();
    byte[] barr = cw.toByteArray();

    try {
        ResourceUtil.touch(classFile);
        IOUtil.copy(new ByteArrayInputStream(barr), classFile, true);

        cl = (PhysicalClassLoader) ((PageContextImpl) pc).getRPCClassLoader(true);

        return registerTypeMapping(cl.loadClass(className, barr));
    } catch (Throwable t) {
        throw Caster.toPageException(t);
    }
}