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.google.code.jconts.instrument.gen.ContinuationClassGenerator.java

License:Apache License

public void accept(TransformationContext context) {
    ClassVisitor cv = context.writer();//from  w ww .  ja v a  2  s  .c o m

    cv.visit(Opcodes.V1_6, Opcodes.ACC_FINAL, info.continuationClassName, signature, OBJECT_NAME,
            new String[] { CONTINUATION_NAME });

    cv.visitSource(info.ownerSource, null);
    cv.visitInnerClass(info.stateClassName, info.owner, info.stateSimpleName, 0);
    cv.visitInnerClass(info.continuationClassName, info.owner, info.continuationSimpleName, 0);

    cv.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "state", stateDesc, null, null);

    cv.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "index", "I", null, null);

    generateConstructor(cv);
    generateExecute(cv, true);
    generateExecute(cv, false);

    cv.visitEnd();
}

From source file:com.google.code.jconts.instrument.gen.StateClassGenerator.java

License:Apache License

public void accept(TransformationContext context) {
    ClassVisitor cv = context.writer();/*from  w  ww  .j ava 2 s . c  om*/

    final String name = info.stateClassName;

    cv.visit(Opcodes.V1_6, Opcodes.ACC_FINAL /*| Opcodes.ACC_SYNTHETIC*/, name, null, OBJECT_NAME, null);

    cv.visitSource(info.ownerSource, null);
    cv.visitOuterClass(info.owner, null, null);

    cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, CONTINUATION_FIELD, CONTINUATION_DESC,
            'L' + CONTINUATION_NAME + '<' + info.valueSignature + ">;", null);

    // Local variables state
    List<String> names = info.tracker.getFieldNames();
    List<Type> types = info.tracker.getFieldTypes();
    for (int i = 0; i < names.size(); ++i) {
        cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, names.get(i), types.get(i).getDescriptor(), null, null);
    }

    // Return value variable
    cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, "result", OBJECT_DESC, null, null);
    cv.visitField(0/*Opcodes.ACC_SYNTHETIC*/, "exception", THROWABLE_DESC, null, null);

    // Generate constructor
    MethodVisitor mv = cv.visitMethod(0, CTOR_NAME, DEFAULT_CTOR_DESC, null, null);
    mv.visitCode();
    Label start = new Label();
    Label end = new Label();
    mv.visitLabel(start);
    mv.visitLineNumber(0, start);

    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, OBJECT_NAME, CTOR_NAME, DEFAULT_CTOR_DESC);
    mv.visitInsn(Opcodes.RETURN);
    mv.visitLabel(end);

    mv.visitLocalVariable("this", 'L' + name + ';', null, start, end, 0);

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

    cv.visitEnd();
}

From source file:com.googlecode.dex2jar.v3.V3ClassAdapter.java

License:Apache License

protected void build() {
    if (!build) {
        String signature = null;/*from w w  w.  j ava  2s. c o m*/
        for (Iterator<AnnotationNode> it = anns.iterator(); it.hasNext();) {
            AnnotationNode ann = it.next();
            if ("Ldalvik/annotation/Signature;".equals(ann.type)) {
                it.remove();
                signature = buildSignature(ann);
            }
        }

        Clz clz = this.clz;

        int access = clz.access;
        boolean isInnerClass = clz.enclosingClass != null || clz.enclosingMethod != null;
        int accessInClass = clearClassAccess(isInnerClass, access);
        String[] nInterfaceNames = null;
        if (interfaceNames != null) {
            nInterfaceNames = new String[interfaceNames.length];
            for (int i = 0; i < interfaceNames.length; i++) {
                nInterfaceNames[i] = Type.getType(interfaceNames[i]).getInternalName();
            }
        }
        cv.visit(Opcodes.V1_6, accessInClass, Type.getType(className).getInternalName(), signature,
                superClass == null ? null : Type.getType(superClass).getInternalName(), nInterfaceNames);

        searchInnerClass(clz);
        if (isInnerClass) {
            // build Outer Clz
            if (clz.innerName == null) {// anonymous Innerclass
                Method enclosingMethod = clz.enclosingMethod;
                if (enclosingMethod != null) {
                    cv.visitOuterClass(Type.getType(enclosingMethod.getOwner()).getInternalName(),
                            enclosingMethod.getName(), enclosingMethod.getDesc());
                } else {
                    Clz enclosingClass = clz.enclosingClass;
                    cv.visitOuterClass(Type.getType(enclosingClass.name).getInternalName(), null, null);
                }
            }
            searchEnclosing(clz);
        }
        for (AnnotationNode ann : anns) {
            ann.accept(cv);
        }
        if (file != null) {
            cv.visitSource(file, null);
        }
        build = true;
    }
}

From source file:com.googlecode.gwt.test.internal.rewrite.ForceClassVersion15.java

License:Apache License

@Override
public void visit(final int version, final int access, final String name, final String signature,
        final String superName, final String[] interfaces) {
    assert version >= Opcodes.V1_5 && version <= Opcodes.V1_6;
    super.visit(Opcodes.V1_5, access, name, signature, superName, interfaces);
}

From source file:com.khubla.jvmbasic.jvmbasicc.JVMBasicCompiler.java

License:Open Source License

/**
 * compile. This method generates the class definition
 *//* ww w  .  j  ava 2  s  .  c o  m*/
public byte[] compile(InputStream inputStream, String classname, boolean verboseOutput) throws Exception {
    try {
        /*
         * a message
         */
        logger.info("Parsing input for classname: '" + classname + "'");
        /*
         * get tree
         */
        final ProgContext progContext = parse(inputStream);
        /*
         * print tree
         */
        final TreePrinter treePrinter = new TreePrinter();
        treePrinter.printTree(progContext);
        /*
         * a message
         */
        logger.info("Generating Bytecode for class '" + classname + "'");
        /*
         * class
         */
        final ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
        classWriter.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, classname, null, "java/lang/Object", null);
        /*
         * the execution context
         */
        FieldVisitor fieldVistor = classWriter.visitField(Opcodes.ACC_PUBLIC, RTLHelper.EXECUTIONCONTEXT_NAME,
                RTLHelper.JASIC_RUNTIME_EXECUTIONCONTEXT_TYPE, null, null);
        fieldVistor.visitEnd();
        /*
         * input stream
         */
        fieldVistor = classWriter.visitField(Opcodes.ACC_PUBLIC, "inputStream", "Ljava/io/InputStream;", null,
                null);
        fieldVistor.visitEnd();
        /*
         * output stream
         */
        fieldVistor = classWriter.visitField(Opcodes.ACC_PUBLIC, "outputStream", "Ljava/io/PrintStream;", null,
                null);
        fieldVistor.visitEnd();
        /*
         * init method
         */
        generateInit(classname, classWriter);
        /*
         * main()
         */
        generateMain(classname, classWriter);
        /*
         * program
         */
        generateProgram(classname, classWriter, progContext);
        /*
         * generate the class
         */
        classWriter.visitEnd();
        return classWriter.toByteArray();
    } catch (final Exception e) {
        throw new Exception("Exception in compile", e);
    }
}

From source file:com.mogujie.instantrun.IncrementalTool.java

License:Apache License

public static byte[] getPatchFileContents(ImmutableList<String> patchFileContents,
        ImmutableList<Integer> patchIndexContents) {
    if (patchFileContents.size() != patchIndexContents.size()) {
        throw new GradleException("patchFileContents's size is " + patchFileContents.size()
                + ", but patchIndexContents's size is " + patchIndexContents.size()
                + ", please check the changed classes.");
    }/*from  w ww .  ja  v a2s. com*/
    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.SIPUSH, patchFileContents.size());
        mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
        for (int index = 0; index < patchFileContents.size(); index++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.SIPUSH, index);
            mv.visitLdcInsn(patchFileContents.get(index));
            mv.visitInsn(Opcodes.AASTORE);
        }
        mv.visitInsn(Opcodes.ARETURN);
        mv.visitMaxs(4, 1);
        mv.visitEnd();
    }
    {
        mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getPatchedClassIndexes", "()[I", null, null);
        mv.visitCode();

        mv.visitIntInsn(Opcodes.SIPUSH, patchIndexContents.size());
        mv.visitIntInsn(Opcodes.NEWARRAY, Opcodes.T_INT);
        for (int index = 0; index < patchIndexContents.size(); index++) {
            mv.visitInsn(Opcodes.DUP);
            mv.visitIntInsn(Opcodes.SIPUSH, index);
            mv.visitLdcInsn(patchIndexContents.get(index));
            mv.visitInsn(Opcodes.IASTORE);
        }
        mv.visitInsn(Opcodes.ARETURN);
        mv.visitMaxs(4, 1);
        mv.visitEnd();
    }
    cw.visitEnd();

    return cw.toByteArray();

}

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

License:Apache License

/**
 * Creates a JSON deserializer for the specified bean class unless a deserializer has already
 * been created. Created deserializers are cached and returned on subsequent calls to this method.
 * /*from ww w.  j ava 2  s  .  c o m*/
 * @param <T> class type for bean
 * @param beanClazz bean class for which a deserializer should be created
 * @return the created deserializer
 * @throws SerializerFactoryException if unable to create deserializer or class is not a bean
 */
@SuppressWarnings("unchecked")
protected <T> JsonDeserializer<T> create(Class<T> beanClazz) throws SerializerFactoryException {
    JsonDeserializer<T> deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz);

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

    try {
        synchronized (this) {
            deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz);

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

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

            String intDeserializerClazzName = new StringBuffer(intBeanClazzName).append("JsonDeserializer")
                    .toString();

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

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

            // Create deserialize method
            MethodVisitor visitor = createDeserializeMethod(writer, intBeanClazzName);

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

                if (canDeserialize && method.getName().startsWith("set")
                        && method.getReturnType().equals(void.class)
                        && method.getParameterTypes().length == 1) {
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    Class<?> parameterType = parameterTypes[0];

                    if (parameterType.isArray()) {
                        Class<?> arrayType = parameterType.getComponentType();

                        if (arrayType.equals(boolean.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeBooleanArray", "[Z", "[Z", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(double.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeDoubleArray", "[D", "[D", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(float.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeFloatArray", "[F", "[F", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(int.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeIntArray", "[I", "[I", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(long.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeLongArray", "[J", "[J", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(short.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeShortArray", "[S", "[S", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(String.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeStringArray", "[Ljava/lang/String;", "[Ljava/lang/String;",
                                    intBeanClazzName, method.getName());
                        }
                    } else if (parameterType.isPrimitive()) {
                        if (parameterType.equals(boolean.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeBoolean", "Z", "Z", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(double.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeDouble", "D", "D", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(float.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeFloat", "F", "F", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(int.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeInt", "I", "I", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(long.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeLong", "J", "J", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(short.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeShort", "S", "S", intBeanClazzName, method.getName());
                        }
                    } else if (parameterType.equals(Calendar.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                "deserializeCalendar", "Ljava/util/Calendar;", "Ljava/util/Calendar;",
                                intBeanClazzName, method.getName());
                    } else if (parameterType.equals(Date.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDate",
                                "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName());
                    } else if (parameterType.equals(String.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                "deserializeString", "Ljava/lang/String;", "Ljava/lang/String;",
                                intBeanClazzName, method.getName());
                    }
                }
            }

            visitor.visitVarInsn(Opcodes.ALOAD, 3);
            visitor.visitInsn(Opcodes.ARETURN);
            visitor.visitMaxs(5, 4);
            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,
                    intDeserializerClazzName.replace('/', '.'), clazzBytes);
            deserializer = (JsonDeserializer<T>) clazz.newInstance();
            deserializers.put(beanClazz, deserializer);
            return deserializer;
        }
    } catch (IllegalAccessException e) {
        throw new SerializerFactoryException(e);
    } catch (InstantiationException e) {
        throw new SerializerFactoryException(e);
    }
}

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  w w .  j av a2 s. com
 * @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.QueryDeserializerCreator.java

License:Apache License

/**
 * Creates a query deserializer for the specified bean class unless a deserializer has already
 * been created. Created deserializers are cached and returned on subsequent calls to this method.
 * //from ww w  . j  ava 2s .co m
 * @param <T> class type for bean
 * @param beanClazz bean class for which a deserializer should be created
 * @return the created deserializer
 * @throws SerializerFactoryException if unable to create deserializer or class is not a bean
 */
@SuppressWarnings("unchecked")
protected <T> QueryDeserializer<T> create(Class<T> beanClazz) throws SerializerFactoryException {
    QueryDeserializer<T> deserializer = (QueryDeserializer<T>) deserializers.get(beanClazz);

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

    try {
        synchronized (this) {
            deserializer = (QueryDeserializer<T>) deserializers.get(beanClazz);

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

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

            String intDeserializerClazzName = new StringBuffer(intBeanClazzName).append("QueryDeserializer")
                    .toString();

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

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

            // Create deserialize method
            MethodVisitor visitor = createDeserializeMethod(writer, intBeanClazzName);

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

                if (canDeserialize && method.getName().startsWith("set")
                        && method.getReturnType().equals(void.class)
                        && method.getParameterTypes().length == 1) {
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    Class<?> parameterType = parameterTypes[0];

                    if (parameterType.isArray()) {
                        Class<?> arrayType = parameterType.getComponentType();

                        if (arrayType.equals(boolean.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeBooleanArray", "[Z", "[Z", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(double.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeDoubleArray", "[D", "[D", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(float.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeFloatArray", "[F", "[F", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(int.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeIntArray", "[I", "[I", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(long.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeLongArray", "[J", "[J", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(short.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeShortArray", "[S", "[S", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(String.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeStringArray", "[Ljava/lang/String;", "[Ljava/lang/String;",
                                    intBeanClazzName, method.getName());
                        }
                    } else if (parameterType.isPrimitive()) {
                        if (parameterType.equals(boolean.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeBoolean", "Z", "Z", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(double.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeDouble", "D", "D", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(float.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeFloat", "F", "F", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(int.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeInt", "I", "I", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(long.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeLong", "J", "J", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(short.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeShort", "S", "S", intBeanClazzName, method.getName());
                        }
                    } else if (parameterType.equals(Calendar.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                "deserializeCalendar", "Ljava/util/Calendar;", "Ljava/util/Calendar;",
                                intBeanClazzName, method.getName());
                    } else if (parameterType.equals(Date.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDate",
                                "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName());
                    } else if (parameterType.equals(String.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                "deserializeString", "Ljava/lang/String;", "Ljava/lang/String;",
                                intBeanClazzName, method.getName());
                    }
                }
            }

            visitor.visitVarInsn(Opcodes.ALOAD, 3);
            visitor.visitInsn(Opcodes.ARETURN);
            visitor.visitMaxs(5, 4);
            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,
                    intDeserializerClazzName.replace('/', '.'), clazzBytes);
            deserializer = (QueryDeserializer<T>) clazz.newInstance();
            deserializers.put(beanClazz, deserializer);
            return deserializer;
        }
    } catch (IllegalAccessException e) {
        throw new SerializerFactoryException(e);
    } catch (InstantiationException e) {
        throw new SerializerFactoryException(e);
    }
}

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

License:Apache License

/**
 * Creates a XML deserializer for the specified bean class unless a deserializer has already
 * been created. Created deserializers are cached and returned on subsequent calls to this method.
 * //from www  .j av a2s .  c om
 * @param <T> class type for bean
 * @param beanClazz bean class for which a deserializer should be created
 * @return the created deserializer
 * @throws SerializerFactoryException if unable to create deserializer or class is not a bean
 */
@SuppressWarnings("unchecked")
protected <T> XmlDeserializer<T> create(Class<T> beanClazz) throws SerializerFactoryException {
    XmlDeserializer<T> deserializer = (XmlDeserializer<T>) deserializers.get(beanClazz);

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

    try {
        synchronized (this) {
            deserializer = (XmlDeserializer<T>) deserializers.get(beanClazz);

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

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

            String intDeserializerClazzName = new StringBuffer(intBeanClazzName).append("XmlDeserializer")
                    .toString();

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

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

            // Create deserialize method
            MethodVisitor visitor = createDeserializeMethod(writer, intBeanClazzName);

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

                if (canDeserialize && method.getName().startsWith("set")
                        && method.getReturnType().equals(void.class)
                        && method.getParameterTypes().length == 1) {
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    Class<?> parameterType = parameterTypes[0];

                    if (parameterType.isArray()) {
                        Class<?> arrayType = parameterType.getComponentType();

                        if (arrayType.equals(boolean.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeBooleanArray", "[Z", "[Z", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(double.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeDoubleArray", "[D", "[D", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(float.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeFloatArray", "[F", "[F", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(int.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeIntArray", "[I", "[I", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(long.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeLongArray", "[J", "[J", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(short.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeShortArray", "[S", "[S", intBeanClazzName, method.getName());
                        } else if (arrayType.equals(String.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeStringArray", "[Ljava/lang/String;", "[Ljava/lang/String;",
                                    intBeanClazzName, method.getName());
                        }
                    } else if (parameterType.isPrimitive()) {
                        if (parameterType.equals(boolean.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeBoolean", "Z", "Z", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(double.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeDouble", "D", "D", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(float.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeFloat", "F", "F", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(int.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeInt", "I", "I", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(long.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeLong", "J", "J", intBeanClazzName, method.getName());
                        } else if (parameterType.equals(short.class)) {
                            createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                    "deserializeShort", "S", "S", intBeanClazzName, method.getName());
                        }
                    } else if (parameterType.equals(Calendar.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                "deserializeCalendar", "Ljava/util/Calendar;", "Ljava/util/Calendar;",
                                intBeanClazzName, method.getName());
                    } else if (parameterType.equals(Date.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDate",
                                "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName());
                    } else if (parameterType.equals(String.class)) {
                        createPropertyDeserializationCode(visitor, intDeserializerClazzName,
                                "deserializeString", "Ljava/lang/String;", "Ljava/lang/String;",
                                intBeanClazzName, method.getName());
                    }
                }
            }

            visitor.visitVarInsn(Opcodes.ALOAD, 3);
            visitor.visitInsn(Opcodes.ARETURN);
            visitor.visitMaxs(5, 4);
            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,
                    intDeserializerClazzName.replace('/', '.'), clazzBytes);
            deserializer = (XmlDeserializer<T>) clazz.newInstance();
            deserializers.put(beanClazz, deserializer);
            return deserializer;
        }
    } catch (IllegalAccessException e) {
        throw new SerializerFactoryException(e);
    } catch (InstantiationException e) {
        throw new SerializerFactoryException(e);
    }
}