/***
 * ASM: a very small and fast Java bytecode manipulation framework
 * Copyright (c) 2000-2011 INRIA, France Telecom
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the copyright holders nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.nutz.repo.org.objectweb.asm;

/**
 * A {@link ClassVisitor} that generates classes in bytecode form. More
 * precisely this visitor generates a byte array conforming to the Java class
 * file format. It can be used alone, to generate a Java class "from scratch",
 * or with one or more {@link ClassReader ClassReader} and adapter class visitor
 * to generate a modified class from one or more existing Java classes.
 *
 * @author Eric Bruneton
 */
public class ClassWriter extends ClassVisitor {

    /**
     * Flag to automatically compute the maximum stack size and the maximum
     * number of local variables of methods. If this flag is set, then the
     * arguments of the {@link MethodVisitor#visitMaxs visitMaxs} method of the
     * {@link MethodVisitor} returned by the {@link #visitMethod visitMethod}
     * method will be ignored, and computed automatically from the signature and
     * the bytecode of each method.
     *
     * @see #ClassWriter(int)
     */
    public static final int COMPUTE_MAXS = 1;

    /**
     * Flag to automatically compute the stack map frames of methods from
     * scratch. If this flag is set, then the calls to the
     * {@link MethodVisitor#visitFrame} method are ignored, and the stack map
     * frames are recomputed from the methods bytecode. The arguments of the
     * {@link MethodVisitor#visitMaxs visitMaxs} method are also ignored and
     * recomputed from the bytecode. In other words, COMPUTE_FRAMES implies
     * COMPUTE_MAXS.
     *
     * @see #ClassWriter(int)
     */
    public static final int COMPUTE_FRAMES = 2;

    /**
     * Pseudo access flag to distinguish between the synthetic attribute and the
     * synthetic access flag.
     */
    static final int ACC_SYNTHETIC_ATTRIBUTE = 0x40000;

    /**
     * Factor to convert from ACC_SYNTHETIC_ATTRIBUTE to Opcode.ACC_SYNTHETIC.
     */
    static final int TO_ACC_SYNTHETIC = ACC_SYNTHETIC_ATTRIBUTE
            / Opcodes.ACC_SYNTHETIC;

    /**
     * The type of instructions without any argument.
     */
    static final int NOARG_INSN = 0;

    /**
     * The type of instructions with an signed byte argument.
     */
    static final int SBYTE_INSN = 1;

    /**
     * The type of instructions with an signed short argument.
     */
    static final int SHORT_INSN = 2;

    /**
     * The type of instructions with a local variable index argument.
     */
    static final int VAR_INSN = 3;

    /**
     * The type of instructions with an implicit local variable index argument.
     */
    static final int IMPLVAR_INSN = 4;

    /**
     * The type of instructions with a type descriptor argument.
     */
    static final int TYPE_INSN = 5;

    /**
     * The type of field and method invocations instructions.
     */
    static final int FIELDORMETH_INSN = 6;

    /**
     * The type of the INVOKEINTERFACE/INVOKEDYNAMIC instruction.
     */
    static final int ITFMETH_INSN = 7;

    /**
     * The type of the INVOKEDYNAMIC instruction.
     */
    static final int INDYMETH_INSN = 8;

    /**
     * The type of instructions with a 2 bytes bytecode offset label.
     */
    static final int LABEL_INSN = 9;

    /**
     * The type of instructions with a 4 bytes bytecode offset label.
     */
    static final int LABELW_INSN = 10;

    /**
     * The type of the LDC instruction.
     */
    static final int LDC_INSN = 11;

    /**
     * The type of the LDC_W and LDC2_W instructions.
     */
    static final int LDCW_INSN = 12;

    /**
     * The type of the IINC instruction.
     */
    static final int IINC_INSN = 13;

    /**
     * The type of the TABLESWITCH instruction.
     */
    static final int TABL_INSN = 14;

    /**
     * The type of the LOOKUPSWITCH instruction.
     */
    static final int LOOK_INSN = 15;

    /**
     * The type of the MULTIANEWARRAY instruction.
     */
    static final int MANA_INSN = 16;

    /**
     * The type of the WIDE instruction.
     */
    static final int WIDE_INSN = 17;

    /**
     * The type of the ASM pseudo instructions with an unsigned 2 bytes offset
     * label (see Label#resolve).
     */
    static final int ASM_LABEL_INSN = 18;

    /**
     * Represents a frame inserted between already existing frames. This kind of
     * frame can only be used if the frame content can be computed from the
     * previous existing frame and from the instructions between this existing
     * frame and the inserted one, without any knowledge of the type hierarchy.
     * This kind of frame is only used when an unconditional jump is inserted in
     * a method while expanding an ASM pseudo instruction (see ClassReader).
     */
    static final int F_INSERT = 256;

    /**
     * The instruction types of all JVM opcodes.
     */
    static final byte[] TYPE;

    /**
     * The type of CONSTANT_Class constant pool items.
     */
    static final int CLASS = 7;

    /**
     * The type of CONSTANT_Fieldref constant pool items.
     */
    static final int FIELD = 9;

    /**
     * The type of CONSTANT_Methodref constant pool items.
     */
    static final int METH = 10;

    /**
     * The type of CONSTANT_InterfaceMethodref constant pool items.
     */
    static final int IMETH = 11;

    /**
     * The type of CONSTANT_String constant pool items.
     */
    static final int STR = 8;

    /**
     * The type of CONSTANT_Integer constant pool items.
     */
    static final int INT = 3;

    /**
     * The type of CONSTANT_Float constant pool items.
     */
    static final int FLOAT = 4;

    /**
     * The type of CONSTANT_Long constant pool items.
     */
    static final int LONG = 5;

    /**
     * The type of CONSTANT_Double constant pool items.
     */
    static final int DOUBLE = 6;

    /**
     * The type of CONSTANT_NameAndType constant pool items.
     */
    static final int NAME_TYPE = 12;

    /**
     * The type of CONSTANT_Utf8 constant pool items.
     */
    static final int UTF8 = 1;

    /**
     * The type of CONSTANT_MethodType constant pool items.
     */
    static final int MTYPE = 16;

    /**
     * The type of CONSTANT_MethodHandle constant pool items.
     */
    static final int HANDLE = 15;

    /**
     * The type of CONSTANT_InvokeDynamic constant pool items.
     */
    static final int INDY = 18;

    /**
     * The base value for all CONSTANT_MethodHandle constant pool items.
     * Internally, ASM store the 9 variations of CONSTANT_MethodHandle into 9
     * different items.
     */
    static final int HANDLE_BASE = 20;

    /**
     * Normal type Item stored in the ClassWriter {@link ClassWriter#typeTable},
     * instead of the constant pool, in order to avoid clashes with normal
     * constant pool items in the ClassWriter constant pool's hash table.
     */
    static final int TYPE_NORMAL = 30;

    /**
     * Uninitialized type Item stored in the ClassWriter
     * {@link ClassWriter#typeTable}, instead of the constant pool, in order to
     * avoid clashes with normal constant pool items in the ClassWriter constant
     * pool's hash table.
     */
    static final int TYPE_UNINIT = 31;

    /**
     * Merged type Item stored in the ClassWriter {@link ClassWriter#typeTable},
     * instead of the constant pool, in order to avoid clashes with normal
     * constant pool items in the ClassWriter constant pool's hash table.
     */
    static final int TYPE_MERGED = 32;

    /**
     * The type of BootstrapMethods items. These items are stored in a special
     * class attribute named BootstrapMethods and not in the constant pool.
     */
    static final int BSM = 33;

    /**
     * The class reader from which this class writer was constructed, if any.
     */
    ClassReader cr;

    /**
     * Minor and major version numbers of the class to be generated.
     */
    int version;

    /**
     * Index of the next item to be added in the constant pool.
     */
    int index;

    /**
     * The constant pool of this class.
     */
    final ByteVector pool;

    /**
     * The constant pool's hash table data.
     */
    Item[] items;

    /**
     * The threshold of the constant pool's hash table.
     */
    int threshold;

    /**
     * A reusable key used to look for items in the {@link #items} hash table.
     */
    final Item key;

    /**
     * A reusable key used to look for items in the {@link #items} hash table.
     */
    final Item key2;

    /**
     * A reusable key used to look for items in the {@link #items} hash table.
     */
    final Item key3;

    /**
     * A reusable key used to look for items in the {@link #items} hash table.
     */
    final Item key4;

    /**
     * A type table used to temporarily store internal names that will not
     * necessarily be stored in the constant pool. This type table is used by
     * the control flow and data flow analysis algorithm used to compute stack
     * map frames from scratch. This array associates to each index <tt>i</tt>
     * the Item whose index is <tt>i</tt>. All Item objects stored in this array
     * are also stored in the {@link #items} hash table. These two arrays allow
     * to retrieve an Item from its index or, conversely, to get the index of an
     * Item from its value. Each Item stores an internal name in its
     * {@link Item#strVal1} field.
     */
    Item[] typeTable;

    /**
     * Number of elements in the {@link #typeTable} array.
     */
    private short typeCount;

    /**
     * The access flags of this class.
     */
    private int access;

    /**
     * The constant pool item that contains the internal name of this class.
     */
    private int name;

    /**
     * The internal name of this class.
     */
    String thisName;

    /**
     * The constant pool item that contains the signature of this class.
     */
    private int signature;

    /**
     * The constant pool item that contains the internal name of the super class
     * of this class.
     */
    private int superName;

    /**
     * Number of interfaces implemented or extended by this class or interface.
     */
    private int interfaceCount;

    /**
     * The interfaces implemented or extended by this class or interface. More
     * precisely, this array contains the indexes of the constant pool items
     * that contain the internal names of these interfaces.
     */
    private int[] interfaces;

    /**
     * The index of the constant pool item that contains the name of the source
     * file from which this class was compiled.
     */
    private int sourceFile;

    /**
     * The SourceDebug attribute of this class.
     */
    private ByteVector sourceDebug;

    /**
     * The constant pool item that contains the name of the enclosing class of
     * this class.
     */
    private int enclosingMethodOwner;

    /**
     * The constant pool item that contains the name and descriptor of the
     * enclosing method of this class.
     */
    private int enclosingMethod;

    /**
     * The runtime visible annotations of this class.
     */
    private AnnotationWriter anns;

    /**
     * The runtime invisible annotations of this class.
     */
    private AnnotationWriter ianns;

    /**
     * The runtime visible type annotations of this class.
     */
    private AnnotationWriter tanns;

    /**
     * The runtime invisible type annotations of this class.
     */
    private AnnotationWriter itanns;

    /**
     * The non standard attributes of this class.
     */
    private Attribute attrs;

    /**
     * The number of entries in the InnerClasses attribute.
     */
    private int innerClassesCount;

    /**
     * The InnerClasses attribute.
     */
    private ByteVector innerClasses;

    /**
     * The number of entries in the BootstrapMethods attribute.
     */
    int bootstrapMethodsCount;

    /**
     * The BootstrapMethods attribute.
     */
    ByteVector bootstrapMethods;

    /**
     * The fields of this class. These fields are stored in a linked list of
     * {@link FieldWriter} objects, linked to each other by their
     * {@link FieldWriter#fv} field. This field stores the first element of this
     * list.
     */
    FieldWriter firstField;

    /**
     * The fields of this class. These fields are stored in a linked list of
     * {@link FieldWriter} objects, linked to each other by their
     * {@link FieldWriter#fv} field. This field stores the last element of this
     * list.
     */
    FieldWriter lastField;

    /**
     * The methods of this class. These methods are stored in a linked list of
     * {@link MethodWriter} objects, linked to each other by their
     * {@link MethodWriter#mv} field. This field stores the first element of
     * this list.
     */
    MethodWriter firstMethod;

    /**
     * The methods of this class. These methods are stored in a linked list of
     * {@link MethodWriter} objects, linked to each other by their
     * {@link MethodWriter#mv} field. This field stores the last element of this
     * list.
     */
    MethodWriter lastMethod;

    /**
     * Indicates what must be automatically computed.
     *
     * @see MethodWriter#compute
     */
    private int compute;

    /**
     * <tt>true</tt> if some methods have wide forward jumps using ASM pseudo
     * instructions, which need to be expanded into sequences of standard
     * bytecode instructions. In this case the class is re-read and re-written
     * with a ClassReader -> ClassWriter chain to perform this transformation.
     */
    boolean hasAsmInsns;

    // ------------------------------------------------------------------------
    // Static initializer
    // ------------------------------------------------------------------------

    /**
     * Computes the instruction types of JVM opcodes.
     */
    static {
        int i;
        byte[] b = new byte[220];
        String s = "AAAAAAAAAAAAAAAABCLMMDDDDDEEEEEEEEEEEEEEEEEEEEAAAAAAAADD"
                + "DDDEEEEEEEEEEEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                + "AAAAAAAAAAAAAAAAANAAAAAAAAAAAAAAAAAAAAJJJJJJJJJJJJJJJJDOPAA"
                + "AAAAGGGGGGGHIFBFAAFFAARQJJKKSSSSSSSSSSSSSSSSSS";
        for (i = 0; i < b.length; ++i) {
            b[i] = (byte) (s.charAt(i) - 'A');
        }
        TYPE = b;

        // code to generate the above string
        //
        // // SBYTE_INSN instructions
        // b[Constants.NEWARRAY] = SBYTE_INSN;
        // b[Constants.BIPUSH] = SBYTE_INSN;
        //
        // // SHORT_INSN instructions
        // b[Constants.SIPUSH] = SHORT_INSN;
        //
        // // (IMPL)VAR_INSN instructions
        // b[Constants.RET] = VAR_INSN;
        // for (i = Constants.ILOAD; i <= Constants.ALOAD; ++i) {
        // b[i] = VAR_INSN;
        // }
        // for (i = Constants.ISTORE; i <= Constants.ASTORE; ++i) {
        // b[i] = VAR_INSN;
        // }
        // for (i = 26; i <= 45; ++i) { // ILOAD_0 to ALOAD_3
        // b[i] = IMPLVAR_INSN;
        // }
        // for (i = 59; i <= 78; ++i) { // ISTORE_0 to ASTORE_3
        // b[i] = IMPLVAR_INSN;
        // }
        //
        // // TYPE_INSN instructions
        // b[Constants.NEW] = TYPE_INSN;
        // b[Constants.ANEWARRAY] = TYPE_INSN;
        // b[Constants.CHECKCAST] = TYPE_INSN;
        // b[Constants.INSTANCEOF] = TYPE_INSN;
        //
        // // (Set)FIELDORMETH_INSN instructions
        // for (i = Constants.GETSTATIC; i <= Constants.INVOKESTATIC; ++i) {
        // b[i] = FIELDORMETH_INSN;
        // }
        // b[Constants.INVOKEINTERFACE] = ITFMETH_INSN;
        // b[Constants.INVOKEDYNAMIC] = INDYMETH_INSN;
        //
        // // LABEL(W)_INSN instructions
        // for (i = Constants.IFEQ; i <= Constants.JSR; ++i) {
        // b[i] = LABEL_INSN;
        // }
        // b[Constants.IFNULL] = LABEL_INSN;
        // b[Constants.IFNONNULL] = LABEL_INSN;
        // b[200] = LABELW_INSN; // GOTO_W
        // b[201] = LABELW_INSN; // JSR_W
        // // temporary opcodes used internally by ASM - see Label and
        // MethodWriter
        // for (i = 202; i < 220; ++i) {
        // b[i] = ASM_LABEL_INSN;
        // }
        //
        // // LDC(_W) instructions
        // b[Constants.LDC] = LDC_INSN;
        // b[19] = LDCW_INSN; // LDC_W
        // b[20] = LDCW_INSN; // LDC2_W
        //
        // // special instructions
        // b[Constants.IINC] = IINC_INSN;
        // b[Constants.TABLESWITCH] = TABL_INSN;
        // b[Constants.LOOKUPSWITCH] = LOOK_INSN;
        // b[Constants.MULTIANEWARRAY] = MANA_INSN;
        // b[196] = WIDE_INSN; // WIDE
        //
        // for (i = 0; i < b.length; ++i) {
        // System.err.print((char)('A' + b[i]));
        // }
        // System.err.println();
    }

    // ------------------------------------------------------------------------
    // Constructor
    // ------------------------------------------------------------------------

    /**
     * Constructs a new {@link ClassWriter} object.
     *
     * @param flags
     *            option flags that can be used to modify the default behavior
     *            of this class. See {@link #COMPUTE_MAXS},
     *            {@link #COMPUTE_FRAMES}.
     */
    public ClassWriter(final int flags) {
        super(Opcodes.ASM5);
        index = 1;
        pool = new ByteVector();
        items = new Item[256];
        threshold = (int) (0.75d * items.length);
        key = new Item();
        key2 = new Item();
        key3 = new Item();
        key4 = new Item();
        this.compute = (flags & COMPUTE_FRAMES) != 0 ? MethodWriter.FRAMES
                : ((flags & COMPUTE_MAXS) != 0 ? MethodWriter.MAXS
                        : MethodWriter.NOTHING);
    }

    /**
     * Constructs a new {@link ClassWriter} object and enables optimizations for
     * "mostly add" bytecode transformations. These optimizations are the
     * following:
     *
     *

     *
The constant pool from the original class is copied as is in the new
     * class, which saves time. New constant pool entries will be added at the
     * end if necessary, but unused constant pool entries won't be
     * removed.

     *
Methods that are not transformed are copied as is in the new class,
     * directly from the original class bytecode (i.e. without emitting visit
     * events for all the method instructions), which saves a lot of
     * time. Untransformed methods are detected by the fact that the
     * {@link ClassReader} receives {@link MethodVisitor} objects that come from
     * a {@link ClassWriter} (and not from any other {@link ClassVisitor}
     * instance).

     *

     *
     * @param classReader
     *            the {@link ClassReader} used to read the original class. It
     *            will be used to copy the entire constant pool from the
     *            original class and also to copy other fragments of original
     *            bytecode where applicable.
     * @param flags
     *            option flags that can be used to modify the default behavior
     *            of this class. These option flags do not affect methods
     *            that are copied as is in the new class. This means that
     *            neither the maximum stack size nor the stack frames will be
     *            computed for these methods. See {@link #COMPUTE_MAXS},
     *            {@link #COMPUTE_FRAMES}.
     */
    public ClassWriter(final ClassReader classReader, final int flags) {
        this(flags);
        classReader.copyPool(this);
        this.cr = classReader;
    }

    // ------------------------------------------------------------------------
    // Implementation of the ClassVisitor abstract class
    // ------------------------------------------------------------------------

    @Override
    public final void visit(final int version, final int access,
            final String name, final String signature, final String superName,
            final String[] interfaces) {
        this.version = version;
        this.access = access;
        this.name = newClass(name);
        thisName = name;
        if (ClassReader.SIGNATURES && signature != null) {
            this.signature = newUTF8(signature);
        }
        this.superName = superName == null ? 0 : newClass(superName);
        if (interfaces != null && interfaces.length > 0) {
            interfaceCount = interfaces.length;
            this.interfaces = new int[interfaceCount];
            for (int i = 0; i < interfaceCount; ++i) {
                this.interfaces[i] = newClass(interfaces[i]);
            }
        }
    }

    @Override
    public final void visitSource(final String file, final String debug) {
        if (file != null) {
            sourceFile = newUTF8(file);
        }
        if (debug != null) {
            sourceDebug = new ByteVector().encodeUTF8(debug, 0,
                    Integer.MAX_VALUE);
        }
    }

    @Override
    public final void visitOuterClass(final String owner, final String name,
            final String desc) {
        enclosingMethodOwner = newClass(owner);
        if (name != null && desc != null) {
            enclosingMethod = newNameType(name, desc);
        }
    }

    @Override
    public final AnnotationVisitor visitAnnotation(final String desc,
            final boolean visible) {
        if (!ClassReader.ANNOTATIONS) {
            return null;
        }
        ByteVector bv = new ByteVector();
        // write type, and reserve space for values count
        bv.putShort(newUTF8(desc)).putShort(0);
        AnnotationWriter aw = new AnnotationWriter(this, true, bv, bv, 2);
        if (visible) {
            aw.next = anns;
            anns = aw;
        } else {
            aw.next = ianns;
            ianns = aw;
        }
        return aw;
    }

    @Override
    public final AnnotationVisitor visitTypeAnnotation(int typeRef,
            TypePath typePath, final String desc, final boolean visible) {
        if (!ClassReader.ANNOTATIONS) {
            return null;
        }
        ByteVector bv = new ByteVector();
        // write target_type and target_info
        AnnotationWriter.putTarget(typeRef, typePath, bv);
        // write type, and reserve space for values count
        bv.putShort(newUTF8(desc)).putShort(0);
        AnnotationWriter aw = new AnnotationWriter(this, true, bv, bv,
                bv.length - 2);
        if (visible) {
            aw.next = tanns;
            tanns = aw;
        } else {
            aw.next = itanns;
            itanns = aw;
        }
        return aw;
    }

    @Override
    public final void visitAttribute(final Attribute attr) {
        attr.next = attrs;
        attrs = attr;
    }

    @Override
    public final void visitInnerClass(final String name,
            final String outerName, final String innerName, final int access) {
        if (innerClasses == null) {
            innerClasses = new ByteVector();
        }
        // Sec. 4.7.6 of the JVMS states "Every CONSTANT_Class_info entry in the
        // constant_pool table which represents a class or interface C that is
        // not a package member must have exactly one corresponding entry in the
        // classes array". To avoid duplicates we keep track in the intVal field
        // of the Item of each CONSTANT_Class_info entry C whether an inner
        // class entry has already been added for C (this field is unused for
        // class entries, and changing its value does not change the hashcode
        // and equality tests). If so we store the index of this inner class
        // entry (plus one) in intVal. This hack allows duplicate detection in
        // O(1) time.
        Item nameItem = newClassItem(name);
        if (nameItem.intVal == 0) {
            ++innerClassesCount;
            innerClasses.putShort(nameItem.index);
            innerClasses.putShort(outerName == null ? 0 : newClass(outerName));
            innerClasses.putShort(innerName == null ? 0 : newUTF8(innerName));
            innerClasses.putShort(access);
            nameItem.intVal = innerClassesCount;
        } else {
            // Compare the inner classes entry nameItem.intVal - 1 with the
            // arguments of this method and throw an exception if there is a
            // difference?
        }
    }

    @Override
    public final FieldVisitor visitField(final int access, final String name,
            final String desc, final String signature, final Object value) {
        return new FieldWriter(this, access, name, desc, signature, value);
    }

    @Override
    public final MethodVisitor visitMethod(final int access, final String name,
            final String desc, final String signature, final String[] exceptions) {
        return new MethodWriter(this, access, name, desc, signature,
                exceptions, compute);
    }

    @Override
    public final void visitEnd() {
    }

    // ------------------------------------------------------------------------
    // Other public methods
    // ------------------------------------------------------------------------

    /**
     * Returns the bytecode of the class that was build with this class writer.
     *
     * @return the bytecode of the class that was build with this class writer.
     */
    public byte[] toByteArray() {
        if (index > 0xFFFF) {
            throw new RuntimeException("Class file too large!");
        }
        // computes the real size of the bytecode of this class
        int size = 24 + 2 * interfaceCount;
        int nbFields = 0;
        FieldWriter fb = firstField;
        while (fb != null) {
            ++nbFields;
            size += fb.getSize();
            fb = (FieldWriter) fb.fv;
        }
        int nbMethods = 0;
        MethodWriter mb = firstMethod;
        while (mb != null) {
            ++nbMethods;
            size += mb.getSize();
            mb = (MethodWriter) mb.mv;
        }
        int attributeCount = 0;
        if (bootstrapMethods != null) {
            // we put it as first attribute in order to improve a bit
            // ClassReader.copyBootstrapMethods
            ++attributeCount;
            size += 8 + bootstrapMethods.length;
            newUTF8("BootstrapMethods");
        }
        if (ClassReader.SIGNATURES && signature != 0) {
            ++attributeCount;
            size += 8;
            newUTF8("Signature");
        }
        if (sourceFile != 0) {
            ++attributeCount;
            size += 8;
            newUTF8("SourceFile");
        }
        if (sourceDebug != null) {
            ++attributeCount;
            size += sourceDebug.length + 6;
            newUTF8("SourceDebugExtension");
        }
        if (enclosingMethodOwner != 0) {
            ++attributeCount;
            size += 10;
            newUTF8("EnclosingMethod");
        }
        if ((access & Opcodes.ACC_DEPRECATED) != 0) {
            ++attributeCount;
            size += 6;
            newUTF8("Deprecated");
        }
        if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
            if ((version & 0xFFFF) < Opcodes.V1_5
                    || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0) {
                ++attributeCount;
                size += 6;
                newUTF8("Synthetic");
            }
        }
        if (innerClasses != null) {
            ++attributeCount;
            size += 8 + innerClasses.length;
            newUTF8("InnerClasses");
        }
        if (ClassReader.ANNOTATIONS && anns != null) {
            ++attributeCount;
            size += 8 + anns.getSize();
            newUTF8("RuntimeVisibleAnnotations");
        }
        if (ClassReader.ANNOTATIONS && ianns != null) {
            ++attributeCount;
            size += 8 + ianns.getSize();
            newUTF8("RuntimeInvisibleAnnotations");
        }
        if (ClassReader.ANNOTATIONS && tanns != null) {
            ++attributeCount;
            size += 8 + tanns.getSize();
            newUTF8("RuntimeVisibleTypeAnnotations");
        }
        if (ClassReader.ANNOTATIONS && itanns != null) {
            ++attributeCount;
            size += 8 + itanns.getSize();
            newUTF8("RuntimeInvisibleTypeAnnotations");
        }
        if (attrs != null) {
            attributeCount += attrs.getCount();
            size += attrs.getSize(this, null, 0, -1, -1);
        }
        size += pool.length;
        // allocates a byte vector of this size, in order to avoid unnecessary
        // arraycopy operations in the ByteVector.enlarge() method
        ByteVector out = new ByteVector(size);
        out.putInt(0xCAFEBABE).putInt(version);
        out.putShort(index).putByteArray(pool.data, 0, pool.length);
        int mask = Opcodes.ACC_DEPRECATED | ACC_SYNTHETIC_ATTRIBUTE
                | ((access & ACC_SYNTHETIC_ATTRIBUTE) / TO_ACC_SYNTHETIC);
        out.putShort(access & ~mask).putShort(name).putShort(superName);
        out.putShort(interfaceCount);
        for (int i = 0; i < interfaceCount; ++i) {
            out.putShort(interfaces[i]);
        }
        out.putShort(nbFields);
        fb = firstField;
        while (fb != null) {
            fb.put(out);
            fb = (FieldWriter) fb.fv;
        }
        out.putShort(nbMethods);
        mb = firstMethod;
        while (mb != null) {
            mb.put(out);
            mb = (MethodWriter) mb.mv;
        }
        out.putShort(attributeCount);
        if (bootstrapMethods != null) {
            out.putShort(newUTF8("BootstrapMethods"));
            out.putInt(bootstrapMethods.length + 2).putShort(
                    bootstrapMethodsCount);
            out.putByteArray(bootstrapMethods.data, 0, bootstrapMethods.length);
        }
        if (ClassReader.SIGNATURES && signature != 0) {
            out.putShort(newUTF8("Signature")).putInt(2).putShort(signature);
        }
        if (sourceFile != 0) {
            out.putShort(newUTF8("SourceFile")).putInt(2).putShort(sourceFile);
        }
        if (sourceDebug != null) {
            int len = sourceDebug.length;
            out.putShort(newUTF8("SourceDebugExtension")).putInt(len);
            out.putByteArray(sourceDebug.data, 0, len);
        }
        if (enclosingMethodOwner != 0) {
            out.putShort(newUTF8("EnclosingMethod")).putInt(4);
            out.putShort(enclosingMethodOwner).putShort(enclosingMethod);
        }
        if ((access & Opcodes.ACC_DEPRECATED) != 0) {
            out.putShort(newUTF8("Deprecated")).putInt(0);
        }
        if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
            if ((version & 0xFFFF) < Opcodes.V1_5
                    || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0) {
                out.putShort(newUTF8("Synthetic")).putInt(0);
            }
        }
        if (innerClasses != null) {
            out.putShort(newUTF8("InnerClasses"));
            out.putInt(innerClasses.length + 2).putShort(innerClassesCount);
            out.putByteArray(innerClasses.data, 0, innerClasses.length);
        }
        if (ClassReader.ANNOTATIONS && anns != null) {
            out.putShort(newUTF8("RuntimeVisibleAnnotations"));
            anns.put(out);
        }
        if (ClassReader.ANNOTATIONS && ianns != null) {
            out.putShort(newUTF8("RuntimeInvisibleAnnotations"));
            ianns.put(out);
        }
        if (ClassReader.ANNOTATIONS && tanns != null) {
            out.putShort(newUTF8("RuntimeVisibleTypeAnnotations"));
            tanns.put(out);
        }
        if (ClassReader.ANNOTATIONS && itanns != null) {
            out.putShort(newUTF8("RuntimeInvisibleTypeAnnotations"));
            itanns.put(out);
        }
        if (attrs != null) {
            attrs.put(this, null, 0, -1, -1, out);
        }
        if (hasAsmInsns) {
            anns = null;
            ianns = null;
            attrs = null;
            innerClassesCount = 0;
            innerClasses = null;
            firstField = null;
            lastField = null;
            firstMethod = null;
            lastMethod = null;
            compute = MethodWriter.INSERTED_FRAMES;
            hasAsmInsns = false;
            new ClassReader(out.data).accept(this, ClassReader.EXPAND_FRAMES
                    | ClassReader.EXPAND_ASM_INSNS);
            return toByteArray();
        }
        return out.data;
    }

    // ------------------------------------------------------------------------
    // Utility methods: constant pool management
    // ------------------------------------------------------------------------

    /**
     * Adds a number or string constant to the constant pool of the class being
     * build. Does nothing if the constant pool already contains a similar item.
     *
     * @param cst
     *            the value of the constant to be added to the constant pool.
     *            This parameter must be an {@link Integer}, a {@link Float}, a
     *            {@link Long}, a {@link Double}, a {@link String} or a
     *            {@link Type}.
     * @return a new or already existing constant item with the given value.
     */
    Item newConstItem(final Object cst) {
        if (cst instanceof Integer) {
            int val = ((Integer) cst).intValue();
            return newInteger(val);
        } else if (cst instanceof Byte) {
            int val = ((Byte) cst).intValue();
            return newInteger(val);
        } else if (cst instanceof Character) {
            int val = ((Character) cst).charValue();
            return newInteger(val);
        } else if (cst instanceof Short) {
            int val = ((Short) cst).intValue();
            return newInteger(val);
        } else if (cst instanceof Boolean) {
            int val = ((Boolean) cst).booleanValue() ? 1 : 0;
            return newInteger(val);
        } else if (cst instanceof Float) {
            float val = ((Float) cst).floatValue();
            return newFloat(val);
        } else if (cst instanceof Long) {
            long val = ((Long) cst).longValue();
            return newLong(val);
        } else if (cst instanceof Double) {
            double val = ((Double) cst).doubleValue();
            return newDouble(val);
        } else if (cst instanceof String) {
            return newString((String) cst);
        } else if (cst instanceof Type) {
            Type t = (Type) cst;
            int s = t.getSort();
            if (s == Type.OBJECT) {
                return newClassItem(t.getInternalName());
            } else if (s == Type.METHOD) {
                return newMethodTypeItem(t.getDescriptor());
            } else { // s == primitive type or array
                return newClassItem(t.getDescriptor());
            }
        } else if (cst instanceof Handle) {
            Handle h = (Handle) cst;
            return newHandleItem(h.tag, h.owner, h.name, h.desc, h.itf);
        } else {
            throw new IllegalArgumentException("value " + cst);
        }
    }

    /**
     * Adds a number or string constant to the constant pool of the class being
     * build. Does nothing if the constant pool already contains a similar item.
     * This method is intended for {@link Attribute} sub classes, and is
     * normally not needed by class generators or adapters.
     *
     * @param cst
     *            the value of the constant to be added to the constant pool.
     *            This parameter must be an {@link Integer}, a {@link Float}, a
     *            {@link Long}, a {@link Double} or a {@link String}.
     * @return the index of a new or already existing constant item with the
     *         given value.
     */
    public int newConst(final Object cst) {
        return newConstItem(cst).index;
    }

    /**
     * Adds an UTF8 string to the constant pool of the class being build. Does
     * nothing if the constant pool already contains a similar item. This
     * method is intended for {@link Attribute} sub classes, and is normally not
     * needed by class generators or adapters.
     *
     * @param value
     *            the String value.
     * @return the index of a new or already existing UTF8 item.
     */
    public int newUTF8(final String value) {
        key.set(UTF8, value, null, null);
        Item result = get(key);
        if (result == null) {
            pool.putByte(UTF8).putUTF8(value);
            result = new Item(index++, key);
            put(result);
        }
        return result.index;
    }

    /**
     * Adds a class reference to the constant pool of the class being build.
     * Does nothing if the constant pool already contains a similar item.
     * This method is intended for {@link Attribute} sub classes, and is
     * normally not needed by class generators or adapters.
     *
     * @param value
     *            the internal name of the class.
     * @return a new or already existing class reference item.
     */
    Item newClassItem(final String value) {
        key2.set(CLASS, value, null, null);
        Item result = get(key2);
        if (result == null) {
            pool.put12(CLASS, newUTF8(value));
            result = new Item(index++, key2);
            put(result);
        }
        return result;
    }

    /**
     * Adds a class reference to the constant pool of the class being build.
     * Does nothing if the constant pool already contains a similar item.
     * This method is intended for {@link Attribute} sub classes, and is
     * normally not needed by class generators or adapters.
     *
     * @param value
     *            the internal name of the class.
     * @return the index of a new or already existing class reference item.
     */
    public int newClass(final String value) {
        return newClassItem(value).index;
    }

    /**
     * Adds a method type reference to the constant pool of the class being
     * build. Does nothing if the constant pool already contains a similar item.
     * This method is intended for {@link Attribute} sub classes, and is
     * normally not needed by class generators or adapters.
     *
     * @param methodDesc
     *            method descriptor of the method type.
     * @return a new or already existing method type reference item.
     */
    Item newMethodTypeItem(final String methodDesc) {
        key2.set(MTYPE, methodDesc, null, null);
        Item result = get(key2);
        if (result == null) {
            pool.put12(MTYPE, newUTF8(methodDesc));
            result = new Item(index++, key2);
            put(result);
        }
        return result;
    }

    /**
     * Adds a method type reference to the constant pool of the class being
     * build. Does nothing if the constant pool already contains a similar item.
     * This method is intended for {@link Attribute} sub classes, and is
     * normally not needed by class generators or adapters.
     *
     * @param methodDesc
     *            method descriptor of the method type.
     * @return the index of a new or already existing method type reference
     *         item.
     */
    public int newMethodType(final String methodDesc) {
        return newMethodTypeItem(methodDesc).index;
    }

    /**
     * Adds a handle to the constant pool of the class being build. Does nothing
     * if the constant pool already contains a similar item. This method is
     * intended for {@link Attribute} sub classes, and is normally not needed by
     * class generators or adapters.
     *
     * @param tag
     *            the kind of this handle. Must be {@link Opcodes#H_GETFIELD},
     *            {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD},
     *            {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL},
     *            {@link Opcodes#H_INVOKESTATIC},
     *            {@link Opcodes#H_INVOKESPECIAL},
     *            {@link Opcodes#H_NEWINVOKESPECIAL} or
     *            {@link Opcodes#H_INVOKEINTERFACE}.
     * @param owner
     *            the internal name of the field or method owner class.
     * @param name
     *            the name of the field or method.
     * @param desc
     *            the descriptor of the field or method.
     * @param itf
     *            true if the owner is an interface.
     * @return a new or an already existing method type reference item.
     */
    Item newHandleItem(final int tag, final String owner, final String name,
            final String desc, final boolean itf) {
        key4.set(HANDLE_BASE + tag, owner, name, desc);
        Item result = get(key4);
        if (result == null) {
            if (tag <= Opcodes.H_PUTSTATIC) {
                put112(HANDLE, tag, newField(owner, name, desc));
            } else {
                put112(HANDLE,
                        tag,
                        newMethod(owner, name, desc, itf));
            }
            result = new Item(index++, key4);
            put(result);
        }
        return result;
    }

    /**
     * Adds a handle to the constant pool of the class being build. Does nothing
     * if the constant pool already contains a similar item. This method is
     * intended for {@link Attribute} sub classes, and is normally not needed by
     * class generators or adapters.
     *
     * @param tag
     *            the kind of this handle. Must be {@link Opcodes#H_GETFIELD},
     *            {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD},
     *            {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL},
     *            {@link Opcodes#H_INVOKESTATIC},
     *            {@link Opcodes#H_INVOKESPECIAL},
     *            {@link Opcodes#H_NEWINVOKESPECIAL} or
     *            {@link Opcodes#H_INVOKEINTERFACE}.
     * @param owner
     *            the internal name of the field or method owner class.
     * @param name
     *            the name of the field or method.
     * @param desc
     *            the descriptor of the field or method.
     * @return the index of a new or already existing method type reference
     *         item.
     *
     * @deprecated this method is superseded by
     *             {@link #newHandle(int, String, String, String, boolean)}.
     */
    @Deprecated
    public int newHandle(final int tag, final String owner, final String name,
            final String desc) {
        return newHandle(tag, owner, name, desc, tag == Opcodes.H_INVOKEINTERFACE);
    }

    /**
     * Adds a handle to the constant pool of the class being build. Does nothing
     * if the constant pool already contains a similar item. This method is
     * intended for {@link Attribute} sub classes, and is normally not needed by
     * class generators or adapters.
     *
     * @param tag
     *            the kind of this handle. Must be {@link Opcodes#H_GETFIELD},
     *            {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD},
     *            {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL},
     *            {@link Opcodes#H_INVOKESTATIC},
     *            {@link Opcodes#H_INVOKESPECIAL},
     *            {@link Opcodes#H_NEWINVOKESPECIAL} or
     *            {@link Opcodes#H_INVOKEINTERFACE}.
     * @param owner
     *            the internal name of the field or method owner class.
     * @param name
     *            the name of the field or method.
     * @param desc
     *            the descriptor of the field or method.
     * @param itf
     *            true if the owner is an interface.
     * @return the index of a new or already existing method type reference
     *         item.
     */
    public int newHandle(final int tag, final String owner, final String name,
            final String desc, final boolean itf) {
        return newHandleItem(tag, owner, name, desc, itf).index;
    }

    /**
     * Adds an invokedynamic reference to the constant pool of the class being
     * build. Does nothing if the constant pool already contains a similar item.
     * This method is intended for {@link Attribute} sub classes, and is
     * normally not needed by class generators or adapters.
     *
     * @param name
     *            name of the invoked method.
     * @param desc
     *            descriptor of the invoke method.
     * @param bsm
     *            the bootstrap method.
     * @param bsmArgs
     *            the bootstrap method constant arguments.
     *
     * @return a new or an already existing invokedynamic type reference item.
     */
    Item newInvokeDynamicItem(final String name, final String desc,
            final Handle bsm, final Object... bsmArgs) {
        // cache for performance
        ByteVector bootstrapMethods = this.bootstrapMethods;
        if (bootstrapMethods == null) {
            bootstrapMethods = this.bootstrapMethods = new ByteVector();
        }

        int position = bootstrapMethods.length; // record current position

        int hashCode = bsm.hashCode();
        bootstrapMethods.putShort(newHandle(bsm.tag, bsm.owner, bsm.name,
                bsm.desc, bsm.isInterface()));

        int argsLength = bsmArgs.length;
        bootstrapMethods.putShort(argsLength);

        for (int i = 0; i < argsLength; i++) {
            Object bsmArg = bsmArgs[i];
            hashCode ^= bsmArg.hashCode();
            bootstrapMethods.putShort(newConst(bsmArg));
        }

        byte[] data = bootstrapMethods.data;
        int length = (1 + 1 + argsLength) << 1; // (bsm + argCount + arguments)
        hashCode &= 0x7FFFFFFF;
        Item result = items[hashCode % items.length];
        loop: while (result != null) {
            if (result.type != BSM || result.hashCode != hashCode) {
                result = result.next;
                continue;
            }

            // because the data encode the size of the argument
            // we don't need to test if these size are equals
            int resultPosition = result.intVal;
            for (int p = 0; p < length; p++) {
                if (data[position + p] != data[resultPosition + p]) {
                    result = result.next;
                    continue loop;
                }
            }
            break;
        }

        int bootstrapMethodIndex;
        if (result != null) {
            bootstrapMethodIndex = result.index;
            bootstrapMethods.length = position; // revert to old position
        } else {
            bootstrapMethodIndex = bootstrapMethodsCount++;
            result = new Item(bootstrapMethodIndex);
            result.set(position, hashCode);
            put(result);
        }

        // now, create the InvokeDynamic constant
        key3.set(name, desc, bootstrapMethodIndex);
        result = get(key3);
        if (result == null) {
            put122(INDY, bootstrapMethodIndex, newNameType(name, desc));
            result = new Item(index++, key3);
            put(result);
        }
        return result;
    }

    /**
     * Adds an invokedynamic reference to the constant pool of the class being
     * build. Does nothing if the constant pool already contains a similar item.
     * This method is intended for {@link Attribute} sub classes, and is
     * normally not needed by class generators or adapters.
     *
     * @param name
     *            name of the invoked method.
     * @param desc
     *            descriptor of the invoke method.
     * @param bsm
     *            the bootstrap method.
     * @param bsmArgs
     *            the bootstrap method constant arguments.
     *
     * @return the index of a new or already existing invokedynamic reference
     *         item.
     */
    public int newInvokeDynamic(final String name, final String desc,
            final Handle bsm, final Object... bsmArgs) {
        return newInvokeDynamicItem(name, desc, bsm, bsmArgs).index;
    }

    /**
     * Adds a field reference to the constant pool of the class being build.
     * Does nothing if the constant pool already contains a similar item.
     *
     * @param owner
     *            the internal name of the field's owner class.
     * @param name
     *            the field's name.
     * @param desc
     *            the field's descriptor.
     * @return a new or already existing field reference item.
     */
    Item newFieldItem(final String owner, final String name, final String desc) {
        key3.set(FIELD, owner, name, desc);
        Item result = get(key3);
        if (result == null) {
            put122(FIELD, newClass(owner), newNameType(name, desc));
            result = new Item(index++, key3);
            put(result);
        }
        return result;
    }

    /**
     * Adds a field reference to the constant pool of the class being build.
     * Does nothing if the constant pool already contains a similar item.
     * This method is intended for {@link Attribute} sub classes, and is
     * normally not needed by class generators or adapters.
     *
     * @param owner
     *            the internal name of the field's owner class.
     * @param name
     *            the field's name.
     * @param desc
     *            the field's descriptor.
     * @return the index of a new or already existing field reference item.
     */
    public int newField(final String owner, final String name, final String desc) {
        return newFieldItem(owner, name, desc).index;
    }

    /**
     * Adds a method reference to the constant pool of the class being build.
     * Does nothing if the constant pool already contains a similar item.
     *
     * @param owner
     *            the internal name of the method's owner class.
     * @param name
     *            the method's name.
     * @param desc
     *            the method's descriptor.
     * @param itf
     *            <tt>true</tt> if <tt>owner</tt> is an interface.
     * @return a new or already existing method reference item.
     */
    Item newMethodItem(final String owner, final String name,
            final String desc, final boolean itf) {
        int type = itf ? IMETH : METH;
        key3.set(type, owner, name, desc);
        Item result = get(key3);
        if (result == null) {
            put122(type, newClass(owner), newNameType(name, desc));
            result = new Item(index++, key3);
            put(result);
        }
        return result;
    }

    /**
     * Adds a method reference to the constant pool of the class being build.
     * Does nothing if the constant pool already contains a similar item.
     * This method is intended for {@link Attribute} sub classes, and is
     * normally not needed by class generators or adapters.
     *
     * @param owner
     *            the internal name of the method's owner class.
     * @param name
     *            the method's name.
     * @param desc
     *            the method's descriptor.
     * @param itf
     *            <tt>true</tt> if <tt>owner</tt> is an interface.
     * @return the index of a new or already existing method reference item.
     */
    public int newMethod(final String owner, final String name,
            final String desc, final boolean itf) {
        return newMethodItem(owner, name, desc, itf).index;
    }

    /**
     * Adds an integer to the constant pool of the class being build. Does
     * nothing if the constant pool already contains a similar item.
     *
     * @param value
     *            the int value.
     * @return a new or already existing int item.
     */
    Item newInteger(final int value) {
        key.set(value);
        Item result = get(key);
        if (result == null) {
            pool.putByte(INT).putInt(value);
            result = new Item(index++, key);
            put(result);
        }
        return result;
    }

    /**
     * Adds a float to the constant pool of the class being build. Does nothing
     * if the constant pool already contains a similar item.
     *
     * @param value
     *            the float value.
     * @return a new or already existing float item.
     */
    Item newFloat(final float value) {
        key.set(value);
        Item result = get(key);
        if (result == null) {
            pool.putByte(FLOAT).putInt(key.intVal);
            result = new Item(index++, key);
            put(result);
        }
        return result;
    }

    /**
     * Adds a long to the constant pool of the class being build. Does nothing
     * if the constant pool already contains a similar item.
     *
     * @param value
     *            the long value.
     * @return a new or already existing long item.
     */
    Item newLong(final long value) {
        key.set(value);
        Item result = get(key);
        if (result == null) {
            pool.putByte(LONG).putLong(value);
            result = new Item(index, key);
            index += 2;
            put(result);
        }
        return result;
    }

    /**
     * Adds a double to the constant pool of the class being build. Does nothing
     * if the constant pool already contains a similar item.
     *
     * @param value
     *            the double value.
     * @return a new or already existing double item.
     */
    Item newDouble(final double value) {
        key.set(value);
        Item result = get(key);
        if (result == null) {
            pool.putByte(DOUBLE).putLong(key.longVal);
            result = new Item(index, key);
            index += 2;
            put(result);
        }
        return result;
    }

    /**
     * Adds a string to the constant pool of the class being build. Does nothing
     * if the constant pool already contains a similar item.
     *
     * @param value
     *            the String value.
     * @return a new or already existing string item.
     */
    private Item newString(final String value) {
        key2.set(STR, value, null, null);
        Item result = get(key2);
        if (result == null) {
            pool.put12(STR, newUTF8(value));
            result = new Item(index++, key2);
            put(result);
        }
        return result;
    }

    /**
     * Adds a name and type to the constant pool of the class being build. Does
     * nothing if the constant pool already contains a similar item. This
     * method is intended for {@link Attribute} sub classes, and is normally not
     * needed by class generators or adapters.
     *
     * @param name
     *            a name.
     * @param desc
     *            a type descriptor.
     * @return the index of a new or already existing name and type item.
     */
    public int newNameType(final String name, final String desc) {
        return newNameTypeItem(name, desc).index;
    }

    /**
     * Adds a name and type to the constant pool of the class being build. Does
     * nothing if the constant pool already contains a similar item.
     *
     * @param name
     *            a name.
     * @param desc
     *            a type descriptor.
     * @return a new or already existing name and type item.
     */
    Item newNameTypeItem(final String name, final String desc) {
        key2.set(NAME_TYPE, name, desc, null);
        Item result = get(key2);
        if (result == null) {
            put122(NAME_TYPE, newUTF8(name), newUTF8(desc));
            result = new Item(index++, key2);
            put(result);
        }
        return result;
    }

    /**
     * Adds the given internal name to {@link #typeTable} and returns its index.
     * Does nothing if the type table already contains this internal name.
     *
     * @param type
     *            the internal name to be added to the type table.
     * @return the index of this internal name in the type table.
     */
    int addType(final String type) {
        key.set(TYPE_NORMAL, type, null, null);
        Item result = get(key);
        if (result == null) {
            result = addType(key);
        }
        return result.index;
    }

    /**
     * Adds the given "uninitialized" type to {@link #typeTable} and returns its
     * index. This method is used for UNINITIALIZED types, made of an internal
     * name and a bytecode offset.
     *
     * @param type
     *            the internal name to be added to the type table.
     * @param offset
     *            the bytecode offset of the NEW instruction that created this
     *            UNINITIALIZED type value.
     * @return the index of this internal name in the type table.
     */
    int addUninitializedType(final String type, final int offset) {
        key.type = TYPE_UNINIT;
        key.intVal = offset;
        key.strVal1 = type;
        key.hashCode = 0x7FFFFFFF & (TYPE_UNINIT + type.hashCode() + offset);
        Item result = get(key);
        if (result == null) {
            result = addType(key);
        }
        return result.index;
    }

    /**
     * Adds the given Item to {@link #typeTable}.
     *
     * @param item
     *            the value to be added to the type table.
     * @return the added Item, which a new Item instance with the same value as
     *         the given Item.
     */
    private Item addType(final Item item) {
        ++typeCount;
        Item result = new Item(typeCount, key);
        put(result);
        if (typeTable == null) {
            typeTable = new Item[16];
        }
        if (typeCount == typeTable.length) {
            Item[] newTable = new Item[2 * typeTable.length];
            System.arraycopy(typeTable, 0, newTable, 0, typeTable.length);
            typeTable = newTable;
        }
        typeTable[typeCount] = result;
        return result;
    }

    /**
     * Returns the index of the common super type of the two given types. This
     * method calls {@link #getCommonSuperClass} and caches the result in the
     * {@link #items} hash table to speedup future calls with the same
     * parameters.
     *
     * @param type1
     *            index of an internal name in {@link #typeTable}.
     * @param type2
     *            index of an internal name in {@link #typeTable}.
     * @return the index of the common super type of the two given types.
     */
    int getMergedType(final int type1, final int type2) {
        key2.type = TYPE_MERGED;
        key2.longVal = type1 | (((long) type2) << 32);
        key2.hashCode = 0x7FFFFFFF & (TYPE_MERGED + type1 + type2);
        Item result = get(key2);
        if (result == null) {
            String t = typeTable[type1].strVal1;
            String u = typeTable[type2].strVal1;
            key2.intVal = addType(getCommonSuperClass(t, u));
            result = new Item((short) 0, key2);
            put(result);
        }
        return result.intVal;
    }

    /**
     * Returns the common super type of the two given types. The default
     * implementation of this method loads the two given classes and uses
     * the java.lang.Class methods to find the common super class. It can be
     * overridden to compute this common super type in other ways, in particular
     * without actually loading any class, or to take into account the class
     * that is currently being generated by this ClassWriter, which can of
     * course not be loaded since it is under construction.
     *
     * @param type1
     *            the internal name of a class.
     * @param type2
     *            the internal name of another class.
     * @return the internal name of the common super class of the two given
     *         classes.
     */
    protected String getCommonSuperClass(final String type1, final String type2) {
        Class<?> c, d;
        ClassLoader classLoader = getClass().getClassLoader();
        try {
            c = Class.forName(type1.replace('/', '.'), false, classLoader);
            d = Class.forName(type2.replace('/', '.'), false, classLoader);
        } catch (Exception e) {
            throw new RuntimeException(e.toString());
        }
        if (c.isAssignableFrom(d)) {
            return type1;
        }
        if (d.isAssignableFrom(c)) {
            return type2;
        }
        if (c.isInterface() || d.isInterface()) {
            return "java/lang/Object";
        } else {
            do {
                c = c.getSuperclass();
            } while (!c.isAssignableFrom(d));
            return c.getName().replace('.', '/');
        }
    }

    /**
     * Returns the constant pool's hash table item which is equal to the given
     * item.
     *
     * @param key
     *            a constant pool item.
     * @return the constant pool's hash table item which is equal to the given
     *         item, or <tt>null</tt> if there is no such item.
     */
    private Item get(final Item key) {
        Item i = items[key.hashCode % items.length];
        while (i != null && (i.type != key.type || !key.isEqualTo(i))) {
            i = i.next;
        }
        return i;
    }

    /**
     * Puts the given item in the constant pool's hash table. The hash table
     * must not already contains this item.
     *
     * @param i
     *            the item to be added to the constant pool's hash table.
     */
    private void put(final Item i) {
        if (index + typeCount > threshold) {
            int ll = items.length;
            int nl = ll * 2 + 1;
            Item[] newItems = new Item[nl];
            for (int l = ll - 1; l >= 0; --l) {
                Item j = items[l];
                while (j != null) {
                    int index = j.hashCode % newItems.length;
                    Item k = j.next;
                    j.next = newItems[index];
                    newItems[index] = j;
                    j = k;
                }
            }
            items = newItems;
            threshold = (int) (nl * 0.75);
        }
        int index = i.hashCode % items.length;
        i.next = items[index];
        items[index] = i;
    }

    /**
     * Puts one byte and two shorts into the constant pool.
     *
     * @param b
     *            a byte.
     * @param s1
     *            a short.
     * @param s2
     *            another short.
     */
    private void put122(final int b, final int s1, final int s2) {
        pool.put12(b, s1).putShort(s2);
    }

    /**
     * Puts two bytes and one short into the constant pool.
     *
     * @param b1
     *            a byte.
     * @param b2
     *            another byte.
     * @param s
     *            a short.
     */
    private void put112(final int b1, final int b2, final int s) {
        pool.put11(b1, b2).putShort(s);
    }
}


package org.nutz.dao.impl;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;

import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.EntityMaker;
import org.nutz.dao.impl.entity.MapEntityMaker;
import org.nutz.dao.jdbc.JdbcExpert;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Lang;

/**
 * 封装一些获取实体对象的帮助函数
 *
 * @author zozoh(zozohtnt@gmail.com)
 */
public class EntityHolder {

    // DaoSupport 会设置这个值
    public EntityMaker maker;

    protected JdbcExpert expert;

    private Map<Class<?>, Entity<?>> map;

    protected DataSource dataSource;

    protected MapEntityMaker mapEntityMaker;

    public EntityHolder(JdbcExpert expert, DataSource dataSource) {
        this.expert = expert;
        this.dataSource = dataSource;
        this.map = new ConcurrentHashMap<Class<?>, Entity<?>>();
        mapEntityMaker = new MapEntityMaker();
        mapEntityMaker.init(dataSource, expert, this);
    }

    public void set(Entity<?> en) {
        synchronized (map) {
            this.map.put(en.getType(), en);
        }
    }

    public void remove(Entity<?> en) {
        if (en == null || en.getType() == null)
            return;
        synchronized (map) {
            this.map.remove(en.getType());
        }
    }

    /**
     * 根据类型获取实体
     *
     * @param classOfT
     *            实体类型
     * @return 实体
     */
    @SuppressWarnings("unchecked")
    public <T> Entity<T> getEntity(Class<T> classOfT) {
        Entity<?> re = map.get(classOfT);
        if (null == re || !re.isComplete()) {
            synchronized (map) {
                re = map.get(classOfT);
                if (null == re) {
                    re = maker.make(classOfT);
                }
            }
        }
        return (Entity<T>) re;
    }

    public <T extends Map<String, ?>> Entity<T> makeEntity(String tableName, T map) {
        return mapEntityMaker.make(tableName, map);
    }

    /**
     * 根据一个对象获取实体
     * <p>
     * 对象如果是集合或者数组，则取其第一个元素进行判断
     *
     * @param obj
     *            对象
     * @return 实体
     */
    @SuppressWarnings("unchecked")
    public Entity<?> getEntityBy(Object obj) {
        // 正常的构建一个 Entity
        Object first = Lang.first(obj);
        // 对象为空，不能构建实体
        if (first == null)
            return null;

        // 这是一个 Map,试图构建一个 entity
        if (first instanceof Map<?, ?>) {
            Object tableName = ((Map<String, ?>) first).get(".table");
            if (null == tableName)
                throw Lang.makeThrow("Can not insert map without key '.table' : \n%s",
                                     Json.toJson(first, JsonFormat.forLook()));
            return makeEntity(tableName.toString(), (Map<String, ?>) first);
        }
        // 作为 POJO 构建
        return getEntity(first.getClass());
    }

    public boolean hasType(Class<?> typeName) {
        synchronized (map) {
            return map.containsKey(typeName);
        }
    }

    public void clear() {
        map.clear();
    }

    public void remove(String className) {
        Set<Class<?>> keys = new HashSet<Class<?>>(map.keySet());
        for (Class<?> klass : keys) {
            if (klass.getName().equals(className))
                map.remove(klass);
        }
    }
}


package org.nutz.log;

import org.nutz.lang.Lang;
import org.nutz.log.impl.Log4jLogAdapter;
import org.nutz.log.impl.NopLog;
import org.nutz.log.impl.SystemLogAdapter;
import org.nutz.plugin.SimplePluginManager;

/**
 * 获取 Log 的静态工厂方法
 * @author Young(sunonfire@gmail.com)
 * @author zozoh(zozohtnt@gmail.com)
 * @author Wendal(wendal1985@gmail.com)
 */
public final class Logs {

    private static LogAdapter adapter;

    static {
        init();
    }

    /**
     * Get a Log by Class
     *
     * @param clazz
     *            your class
     * @return Log
     */
    public static Log getLog(Class<?> clazz) {
        return getLog(clazz.getName());
    }

    /**
     * Get a Log by name
     *
     * @param className
     *            the name of Log
     * @return Log
     */
    public static Log getLog(String className) {
        return adapter.getLogger(className);
    }

    /**
     * 返回以调用者的类命名的Log,是获取Log对象最简单的方法!
     */
    public static Log get() {
    	StackTraceElement[] sts = Thread.currentThread().getStackTrace();
    	if (Lang.isAndroid) {
    		for (int i = 0; i < sts.length; i++) {
				if (sts[i].getClassName().equals(Logs.class.getName())) {
					return adapter.getLogger(sts[i+1].getClassName());
				}
			}
    	}
    	return adapter.getLogger(sts[2].getClassName());
    }

    /**
     * 初始化NutLog,检查全部Log的可用性,选择可用的Log适配器
     *

     * 加载本类时,该方法已经在静态构造函数中调用,用户无需主动调用.
     *

     * 除非迫不得已,请不要调用本方法
     *

     */
    public static void init() {
        try {
            String packageName = Logs.class.getPackage().getName() + ".impl.";
            adapter = new SimplePluginManager<LogAdapter>(
                    packageName + "CustomLogAdapter",
                    packageName + "Slf4jLogAdapter",
                    packageName + "Log4jLogAdapter",
                    packageName + "SystemLogAdapter").get();
        }
        catch (Throwable e) {
            try {
                Log4jLogAdapter tmp = new Log4jLogAdapter();
                if (tmp.canWork())
                    adapter = tmp;
                else
                    adapter = new SystemLogAdapter();
            } catch (Throwable _e) {
                adapter = new SystemLogAdapter();
            }
        }
    }

    /**
     * 开放自定义设置LogAdapter,注意,不能设置为null!! 如果你打算完全禁用Nutz的log,可以设置为NOP_ADAPTER
     * @param adapter 你所偏好的LogAdapter
     */
    public static void setAdapter(LogAdapter adapter) {
		Logs.adapter = adapter;
	}

    /**
     * 什么都不做的适配器,无任何输出,某些人就想完全禁用掉NutzLog,就可以用上它了
     */
    public static LogAdapter NOP_ADAPTER = NopLog.NOP;
}


package org.nutz.mvc.upload.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.nutz.lang.Encoding;
import org.nutz.lang.Lang;
import org.nutz.lang.Streams;
import org.nutz.lang.stream.StringOutputStream;

/**
 * 分页缓冲 - 专为高效的成块的解析 HTTP Multipart 输入流而设计
 *

 * 总体的想法是，在内存中构建一个数组环，每个节点是固定宽度的数组（默认8192）。

 * 每次翻页 都相当于将当前环节点的下一个节点读满
 *

 * 每个环节点都有指针指向其下一个节点

 * 每个节点都有一个有效结尾位置以及本节点是否为一个输入流的最末节点
 *

 * 支持一个便利的标记方法（不支持回溯，标记的开始和结束只能在一个节点内不能跨节点）

 * 支持成块写到输出流

 *
 *

 * 考虑到效率问题，BufferRing 有一些基本假设：
 *

 *

 *
环节点最少为 3 个
 *
每个节点的长度，至少要比即将给定的 boundary 要长
 *

 * 如果违背了上述假设， BufferRing 将发生不可预知的异常
 *
 *
 * @author zozoh(zozohtnt@gmail.com)
 */
public class BufferRing {

    private static void assertRingLength(int len) {
        if (len < 2)
            throw Lang.makeThrow("BufferRing length can not less than 2");
    }

    private InputStream ins;
    RingItem item;
    long readed;

    public BufferRing(InputStream ins, int len, int width) {
        assertRingLength(len);
        this.ins = ins;
        /*
         * Make ring
         */
        item = new RingItem(width);
        for (int i = 1; i < len; i++) {
            item = item.createNext();
        }
    }

    public MarkMode mark(RemountBytes rb) throws IOException {
        return mark(rb.bytes, rb.fails);
    }

    /**
     * 根据给定的字节数组，在环中作标记，以便 dump
     *
     * @param bs
     *            数组
     * @return 标记模式
     * @throws IOException
     */
    private MarkMode mark(byte[] bs, int[] fails) throws IOException {
        RingItem ri = item;
        int re;
        while ((re = ri.mark(bs, fails)) >= 0 && ri.isDone4Mark()) {
            // 结尾匹配 bs 的开始，看不出这是否是一个结束，所以暂时当作
            // 结束标记，并看看下一个节点。如果不是结束，则需要将 r 置到 max
            if (re > 0) {
                // 下一个节点没有加载，加载一下
                if (!ri.next.isLoaded) {
                    ri.next.load(ins);
                    readed += ri.next.max;
                }
                // 如果当前的环节点的 next指向最初节点，说明整个当前的环已经被读满了，
                // 因此所以不能判断这个位置是不是边界
                // 因此做一下记录，下次加载时，本节点应该为头部
                else if (ri.next == this.item) {
                    ri.nextmark = ri.r;
                    return MarkMode.NOT_FOUND;
                }
                // 匹配头部
                if (ri.next.matchHeadingWithRemain(bs, re)) {
                    return MarkMode.FOUND;
                }
                // 没有匹配上，重置当前节点
                else {
                    ri.r = ri.max;
                    ri.nextmark = ri.max;
                }
            }
            if (ri.isStreamEnd)
                break;
            // 指向下一个节点
            ri = ri.next;
            // 保证该节点已经加载了
            if (!ri.isLoaded) {
                ri.load(ins);
                readed += ri.max;
            }
            // 如果已经循环了一圈，退出
            if (ri == item)
                break;
        }
        if (re == -1)
            return MarkMode.FOUND;

        return ri.isStreamEnd ? MarkMode.STREAM_END : MarkMode.NOT_FOUND;
    }

    /**
     * 被 Dump 的节点将会通过标志表示可以再次加载
     *
     * @param ops
     *            输出流，如果为 null，则不会输出，直接改变标志
     * @throws IOException
     */
    public void dump(OutputStream ops) throws IOException {
        while (item.isLoaded) {
            item.dump(ops);
            // All content had been dumped, move to next
            if (!item.isLoaded)
                item = item.next;
            // Else break the loop and waiting for next 'mark'
            else
                break;
        }
        ops.flush();
    }

    /**
     * 将标记的内容 Dump 成一个字符串,使用默认字符集
     *
     * @return 字符串
     *
     * @throws IOException
     */
    String dumpAsString() throws IOException {
        StringBuilder sb = new StringBuilder();
        OutputStream ops = new StringOutputStream(sb, Encoding.defaultEncoding());
        dump(ops);
        return sb.toString();
    }

    /**
     * 将标记的内容 Dump 成一个字符串
     *
     * @return 字符串
     *
     * @throws IOException
     */
    public String dumpAsString(String charset) throws IOException {
        StringBuilder sb = new StringBuilder();
        OutputStream ops = new StringOutputStream(sb, charset);
        dump(ops);
        return sb.toString();
    }

    /**
     * 不输出，直接跳过 Mark，相当于将当前的 Mark dump 到一个空的输出流
     *
     * @throws IOException
     */
    public void skipMark() throws IOException {
        dump(new OutputStream() {
            public void write(int b) throws IOException {}

            public void close() throws IOException {}

            public void flush() throws IOException {}

            public void write(byte[] b, int off, int len) throws IOException {}

            public void write(byte[] b) throws IOException {}

        });
    }

    /**
     * 从当前节点的 next 开始，依次将所有可用的节点全部加载满
     *
     * @return 一共读去的字节数
     *
     * @throws IOException
     */
    public long load() throws IOException {
        if (item.isStreamEnd)
            return readed;
        RingItem ri = item;
        while (!ri.isLoaded) {
            ri.load(ins);
            if (ri.max > 0)
                readed += ri.max;
            ri = ri.next;
        }
        return readed;
    }

    /**
     * @return 已经读了多少字节
     */
    public long readed() {
        return readed;
    }

    /**
     * 安全关闭输入流
     */
    public void close() {
        Streams.safeClose(ins);
    }

}


package org.nutz.dao;

import java.util.Map;

import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.lang.segment.Segment;
import org.nutz.lang.util.Context;
import org.nutz.log.Log;
import org.nutz.log.Logs;

/**
 * 将一个参考对象存入 ThreadLocal
 * <p>
 * Nutz.Dao 将在构造 SQL 时，参考这个对象。如何参考，请参看 '@Table' 关于 “动态表名的赋值规则” 的描述
 *
 * @author zozoh(zozohtnt@gmail.com)
 */
public class TableName {

    private static final Log log = Logs.get();

    private static final ThreadLocal<Object> object = new ThreadLocal<Object>();

    /**
     * 代码模板，这个模板保证了，在 atom 中运行的 POJO 的动态表名，都会被参考对象所影响
     *
     * @param refer
     *            参考对象
     * @param atom
     *            你的业务逻辑
     */
    public static void run(Object refer, Runnable atom) {
        if (null != atom) {
            if (log.isTraceEnabled())
                log.tracef("TableName.run: [%s]->[%s]", object, object.get());

            Object old = get();
            set(refer);
            try {
                atom.run();
            }
            catch (Exception e) {
                throw Lang.wrapThrow(e);
            }
            finally {
                set(old);
                if (log.isTraceEnabled())
                    log.tracef("TableName.finally: [%s]->[%s]", object, object.get());
            }
        }
    }

    /**
     * @return 当前线程中的动态表名参考对象
     */
    public static Object get() {
        return object.get();
    }

    /**
     * 为当前线程设置动态表名参考对象
     *
     * @param obj
     *            参考对象
     * @return 旧的动态表名参考对象
     */
    public static Object set(Object obj) {
        Object re = get();
        object.set(obj);
        return re;
    }

    /**
     * 清除当前线程的动态表名参考对象
     */
    public static void clear() {
        set(null);
    }

    /**
     * 根据当前线程的参考对象，渲染一个动态表名
     *
     * @param tableName
     *            动态表名
     * @return 渲染后的表名
     */
    public static String render(Segment tableName) {
        Object obj = get();
        if (null == obj || !tableName.hasKey())
            return tableName.toString();

        Context context = Lang.context();
        if (isPrimitive(obj)) {
            for (String key : tableName.keys())
                context.set(key, obj);
        } else if (obj instanceof Context) {
            for (String key : tableName.keys())
                context.set(key, ((Context) obj).get(key));
        } else if (obj instanceof Map<?, ?>) {
            for (String key : tableName.keys())
                context.set(key, ((Map<?, ?>) obj).get(key));
        } else {
            Mirror<?> mirror = Mirror.me(obj);
            for (String key : tableName.keys())
                context.set(key, mirror.getValue(obj, key));
        }
        return tableName.render(context).toString();
    }

    public static boolean isPrimitive(Object obj) {
        return obj instanceof CharSequence || obj instanceof Number || obj.getClass().isPrimitive();
    }
}


package org.nutz.mapl;

import java.io.Reader;
import java.lang.reflect.Type;
import java.util.List;

import org.nutz.mapl.impl.MaplMerge;
import org.nutz.mapl.impl.MaplRebuild;
import org.nutz.mapl.impl.compile.ObjCompileImpl;
import org.nutz.mapl.impl.convert.FilterConvertImpl;
import org.nutz.mapl.impl.convert.ObjConvertImpl;
import org.nutz.mapl.impl.convert.StructureConvert;

/**
 * 集合了对象转换合并等高级操作
 *
 * @author juqkai(juqkai@gmail.com)
 *
 */
public class Mapl {
    /**
     * 这个实现, 主要将 List, Map 的对象结构转换成真实的对象.
     *

     * 规则:
     *

     *
对象以Map存储, key为属性名, value为属性值
     *
数组以List存储
     *
Map直接存储为Map
     *
List直接存储为List
     *
只要不是List, Map 存储的, 都认为是可以直接写入对象的. TODO 这点可以调整一下.
     *

     */
    public static Object maplistToObj(Object maplist, Type type) {
        return new ObjConvertImpl(type).convert(maplist);
    }

    /**
     * 与maplistToObj实现一样, 少了一步强制转换而已
     *
     */
    @SuppressWarnings("unchecked")
    public static <T> T maplistToT(Object maplist, Class<T> clz) {
        return (T) new ObjConvertImpl(clz).convert(maplist);
    }

    // ------------------------------------------------------------------
    /**
     * 访问MAP, List结构的数据, 通过 uers[2].name 这种形式.
     *
     * @param maplist
     * @param path
     *            路径
     */
    public static Object cell(Object maplist, String path) {
        MaplRebuild mr = new MaplRebuild(maplist);
        return mr.cell(path);
    }

    // ------------------------------------------------------------------

    /**
     * 转换器中间对象合并器

     * 合并 {@link Mapl} 中定义的中间结构.

     * 规则:

     *

     *
普通对象, 保存为List, 但是要去掉重复.
     *
合并 map , 如果 key 值相同, 那么后一个值覆盖前面的值.递归合并
     *
list不做递归合并, 只做简单的合并, 清除重复的操作.
     *

     */
    public static Object merge(Object... maplists) {
        return MaplMerge.merge(maplists);
    }

    // ------------------------------------------------------------------
    /**
     * 包含MapList过滤器, 详情参见: {@link FilterConvertImpl}
     *
     * @param maplist
     *            maplist结构的对象
     * @param paths
     *            过滤列表
     */
    public static Object includeFilter(Object maplist, List<String> paths) {
        FilterConvertImpl filter = new FilterConvertImpl(paths);
        filter.useIncludeModel();
        return filter.convert(maplist);
    }

    /**
     * 排除MapList过滤器, 详情参见: {@link FilterConvertImpl}
     *
     * @param maplist
     *            maplist结构的对象
     * @param paths
     *            过滤列表
     */
    public static Object excludeFilter(Object maplist, List<String> paths) {
        FilterConvertImpl filter = new FilterConvertImpl(paths);
        filter.useExcludeModel();
        return filter.convert(maplist);
    }

    // ------------------------------------------------------------------

    /**
     * 结构转换, 详情参见: {@link StructureConvert}
     *
     * @param maplist
     *            maplist结构的对象
     * @param model
     *            转换模板, 一个JSON格式的reader
     */
    public static Object convert(Object maplist, Reader model) {
        StructureConvert convert = new StructureConvert(model);
        return convert.convert(maplist);
    }

    /**
     * 结构转换, 详情参见: {@link StructureConvert}
     *
     * @param maplist
     *            maplist结构的对象
     * @param model
     *            转换模板, 也是一个规定格式的maplist结构
     */
    public static Object convert(Object maplist, Object model) {
        StructureConvert convert = new StructureConvert(model);
        return convert.convert(maplist);
    }

    // ------------------------------------------------------------------
    /**
     * 将对象转换成Maplist结构
     *
     * @param obj
     *            待转换的对象
     */
    public static Object toMaplist(Object obj) {
        ObjCompileImpl convert = new ObjCompileImpl();
        return convert.parse(obj);
    }

    /**
     * 添加新的结点
     *
     * @param obj
     *            原始的MapList
     * @param path
     *            路径
     * @param val
     *            值
     */
    public static void put(Object obj, String path, Object val) {
        Object mapList = Mapl.toMaplist(val);
        MaplRebuild rebuild = new MaplRebuild(obj);
        rebuild.put(path, mapList);
    }

    /**
     * 删除一个结点
     *
     * @param obj
     *            原始的Maplist
     * @param path
     *            路径
     */
    public static void del(Object obj, String path) {
        MaplRebuild rebuild = new MaplRebuild(obj);
        rebuild.remove(path);
    }

    /**
     * 更新
     *
     * @param obj
     *            原始的Maplist
     * @param path
     *            路径
     * @param val
     *            新的值
     */
    public static void update(Object obj, String path, Object val) {
        put(obj, path, val);
    }
}


/***
 * ASM: a very small and fast Java bytecode manipulation framework
 * Copyright (c) 2000-2011 INRIA, France Telecom
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the copyright holders nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.nutz.repo.org.objectweb.asm;

/**
 * A visitor to visit a Java annotation. The methods of this class must be
 * called in the following order: ( <tt>visit</tt> | <tt>visitEnum</tt> |
 * <tt>visitAnnotation</tt> | <tt>visitArray</tt> )* <tt>visitEnd</tt>.
 *
 * @author Eric Bruneton
 * @author Eugene Kuleshov
 */
public abstract class AnnotationVisitor {

    /**
     * The ASM API version implemented by this visitor. The value of this field
     * must be one of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
     */
    protected final int api;

    /**
     * The annotation visitor to which this visitor must delegate method calls.
     * May be null.
     */
    protected AnnotationVisitor av;

    /**
     * Constructs a new {@link AnnotationVisitor}.
     *
     * @param api
     *            the ASM API version implemented by this visitor. Must be one
     *            of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
     */
    public AnnotationVisitor(final int api) {
        this(api, null);
    }

    /**
     * Constructs a new {@link AnnotationVisitor}.
     *
     * @param api
     *            the ASM API version implemented by this visitor. Must be one
     *            of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}.
     * @param av
     *            the annotation visitor to which this visitor must delegate
     *            method calls. May be null.
     */
    public AnnotationVisitor(final int api, final AnnotationVisitor av) {
        if (api != Opcodes.ASM4 && api != Opcodes.ASM5) {
            throw new IllegalArgumentException();
        }
        this.api = api;
        this.av = av;
    }

    /**
     * Visits a primitive value of the annotation.
     *
     * @param name
     *            the value name.
     * @param value
     *            the actual value, whose type must be {@link Byte},
     *            {@link Boolean}, {@link Character}, {@link Short},
     *            {@link Integer} , {@link Long}, {@link Float}, {@link Double},
     *            {@link String} or {@link Type} of OBJECT or ARRAY sort. This
     *            value can also be an array of byte, boolean, short, char, int,
     *            long, float or double values (this is equivalent to using
     *            {@link #visitArray visitArray} and visiting each array element
     *            in turn, but is more convenient).
     */
    public void visit(String name, Object value) {
        if (av != null) {
            av.visit(name, value);
        }
    }

    /**
     * Visits an enumeration value of the annotation.
     *
     * @param name
     *            the value name.
     * @param desc
     *            the class descriptor of the enumeration class.
     * @param value
     *            the actual enumeration value.
     */
    public void visitEnum(String name, String desc, String value) {
        if (av != null) {
            av.visitEnum(name, desc, value);
        }
    }

    /**
     * Visits a nested annotation value of the annotation.
     *
     * @param name
     *            the value name.
     * @param desc
     *            the class descriptor of the nested annotation class.
     * @return a visitor to visit the actual nested annotation value, or
     *         <tt>null</tt> if this visitor is not interested in visiting this
     *         nested annotation. The nested annotation value must be fully
     *         visited before calling other methods on this annotation
     *         visitor.
     */
    public AnnotationVisitor visitAnnotation(String name, String desc) {
        if (av != null) {
            return av.visitAnnotation(name, desc);
        }
        return null;
    }

    /**
     * Visits an array value of the annotation. Note that arrays of primitive
     * types (such as byte, boolean, short, char, int, long, float or double)
     * can be passed as value to {@link #visit visit}. This is what
     * {@link ClassReader} does.
     *
     * @param name
     *            the value name.
     * @return a visitor to visit the actual array value elements, or
     *         <tt>null</tt> if this visitor is not interested in visiting these
     *         values. The 'name' parameters passed to the methods of this
     *         visitor are ignored. All the array values must be visited
     *         before calling other methods on this annotation visitor.
     */
    public AnnotationVisitor visitArray(String name) {
        if (av != null) {
            return av.visitArray(name);
        }
        return null;
    }

    /**
     * Visits the end of the annotation.
     */
    public void visitEnd() {
        if (av != null) {
            av.visitEnd();
        }
    }
}


package org.nutz.service;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.EntityField;

/**
 * 针对仅标注了@Id的实体的Service
 * @author wendal(wendal1985@gmail.com)
 *
 * @param <T> 实体的类型
 */
public abstract class IdEntityService<T> extends EntityService<T> {

    /**
     * @see EntityService
     */
    public IdEntityService() {
        super();
    }

    /**
     * @see EntityService
     */
    public IdEntityService(Dao dao) {
        super(dao);
    }

    /**
     * @see EntityService
     */
    public IdEntityService(Dao dao, Class<T> entityType) {
        super(dao, entityType);
    }

    /**
     * 根据@Id所在的属性的值获取一个实体对象
     * @param id 属性的值
     * @return 实体对象,如不存在则返回null
     */
    public T fetch(long id) {
        return dao().fetch(getEntityClass(), id);
    }

    /**
     * 根据@Id所在的属性的值删除一个实体对象
     * @param id 属性的值
     * @return 删除的记录数, 通常是0或者1
     */
    public int delete(long id) {
        return dao().delete(getEntityClass(), id);
    }

    /**
     * 根据@Id所在的属性在数据库中的最大值
     * @return 最大值,若数据库中没有数据,会抛出空指针异常
     */
    public int getMaxId() {
        return dao().getMaxId(getEntityClass());
    }

    /**
     * 是否存在@Id所在属性的值为指定值的记录
     * @param id 属性的值
     * @return true,如果存在的话
     */
    public boolean exists(long id) {
        EntityField ef = getEntity().getIdField();
        if (null == ef)
            return false;
        return dao().count(getEntityClass(), Cnd.where(ef.getName(), "=", id)) > 0;
    }

}


package org.nutz.lang.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;

/**
 * 解析命令参数
 *
 * @author zozoh(zozohtnt@gmail.com)
 * @author wendal(wendal1985@gmail.com)
 */
public class CmdParams {

    private static final Pattern PARAM_KEY = Pattern.compile("^-([a-zA-Z_].*)$");

    public String[] vals;

    NutMap map;

    /**
     * @see #parse(String[], String, String)
     */
    public static CmdParams parse(String[] args, String bools) {
        if (null == bools)
            return parse(args, null, null);

        if (bools.startsWith("^"))
            return parse(args, null, bools);

        return parse(args, bools, null);
    }

    /**
     * 解析传入的参数表
     *
     *

     * 如果参数以 "-" 开头，则所谓名值对的键。
     * 如果后面接着一个 "-" 开头的参数，则认为当前项目是布尔
     * 当然，如果给入的参数 boolChars 或者 boolRegex 匹配上了这个参数，也认为是布尔
     *

     *
     * @param args
     *            参数表
     *
     * @param boolChars
     *            指明一个键的哪个字符是布尔值。 一个键如果全部内容都是布尔值，则分别记录。否则认为是一个普通键

     *            你可以直接给一个正则表达式来匹配 boolChar，但是你的正则表达式必须得有 group(1) 表示内容
     *
     * @param boolRegex
     *            用一个正则表达式来描述哪些键（参数的整体）为布尔值
     *
     * @return 参数表
     */
    public static CmdParams parse(String[] args, String boolChars, String boolRegex) {
        CmdParams params = new CmdParams();
        List<String> list = new ArrayList<String>(args.length);
        params.map = new NutMap();
        if (args.length > 0) {

            // 预编译 boolRegex
            Pattern bool_key = null;
            if (!Strings.isBlank(boolRegex)) {
                bool_key = Pattern.compile(boolRegex);
            }

            // 预编译 boolChars，如果匹配这个正则表达式的参数，将被认为是一个布尔参数
            // 支持 -bish 这样的组合形式
            Pattern bool_char = null;
            if (!Strings.isBlank(boolChars)) {
                bool_char = Pattern.compile("^-([" + boolChars + "]+)$");
            }

            // 参数表 ...
            int i = 0;
            Matcher m;
            for (; i < args.length; i++) {
                String s = args[i];
                // boolChars
                // 是否是布尔值表
                if (null != bool_char) {
                    m = bool_char.matcher(s);
                    if (m.find()) {
                        char[] cs = m.group(m.groupCount()).toCharArray();
                        for (char c : cs) {
                            params.map.put("" + c, true);
                        }
                        continue;
                    }
                }

                // 键值
                m = PARAM_KEY.matcher(s);
                if (m.find()) {
                    String key = m.group(m.groupCount());
                    // 键就是布尔值
                    if (null != bool_key && bool_key.matcher(key).matches()) {
                        params.map.put(key, true);
                    }
                    // 木有后面的值了，那么作为 boolean
                    else if (i >= args.length - 1) {
                        params.map.put(key, true);
                        break;
                    }
                    // 如果有值 ...
                    else {
                        s = args[i + 1];
                        if (s.matches("^-[a-zA-Z_].*$")) {
                            params.map.put(key, true);
                            continue;
                        }
                        params.map.put(key, s);
                        // 跳过下一个值
                        i++;
                    }
                }
                // 嗯，是普通值 ...
                else {
                    list.add(s);
                }
            }
        }
        params.vals = list.toArray(new String[list.size()]);
        return params;
    }

    protected CmdParams() {}

    public String val(int index) {
        int i = index >= 0 ? index : vals.length + index;
        if (i < 0 || i >= vals.length)
            return null;
        return this.vals[i];
    }

    public String val_check(int index) {
        String v = val(index);
        if (null == v) {
            throw Er.create("e.cmd.lack.param.vals", index);
        }
        return v;
    }

    public boolean is(String key) {
        return map.getBoolean(key, false);
    }

    public boolean is(String key, boolean dft) {
        return map.getBoolean(key, dft);
    }

    public void setv(String key, Object val) {
        map.setv(key, val);
    }

    public boolean has(String key) {
        return map.has(key);
    }

    public boolean hasString(String key) {
        String val = this.get(key);
        return !Strings.isBlank(val) && !"true".equals(val);
    }

    public float getFloat(String key) {
        return map.getFloat(key, Float.NaN);
    }

    public float getFloat(String key, float dft) {
        return map.getFloat(key, dft);
    }

    public int getInt(String key) {
        return map.getInt(key, -1);
    }

    public int getInt(String key, int dft) {
        return map.getInt(key, dft);
    }

    public long getLong(String key) {
        return map.getLong(key, -1);
    }

    public long getLong(String key, long dft) {
        return map.getLong(key, dft);
    }

    public double getDouble(String key) {
        return map.getDouble(key, Double.NaN);
    }

    public double getDouble(String key, double dft) {
        return map.getDouble(key, dft);
    }

    public String get(String key) {
        return map.getString(key);
    }

    public String get(String key, String dft) {
        return map.getString(key, dft);
    }

    public String getString(String key) {
        return this.getString(key, "");
    }

    public String getString(String key, String dft) {
        Object val = map.get(key);
        if (null == val || val instanceof Boolean)
            return dft;
        return val.toString();
    }

    public String wrap(String key, String fmt) {
        return wrap(key, fmt, "");
    }

    public String wrap(String key, String fmt, String dft) {
        String val = this.get(key);
        if (Strings.isBlank(val)) {
            return dft;
        }
        return String.format(fmt, val);
    }

    public <T extends Enum<T>> T getEnum(String key, Class<T> classOfEnum) {
        return map.getEnum(key, classOfEnum);
    }

    public <T> T getAs(String key, Class<T> classOfT) {
        return map.getAs(key, classOfT);
    }

    public <T> T getAs(String key, Class<T> classOfT, T dft) {
        return map.getAs(key, classOfT, dft);
    }

    public NutMap getMap(String key) {
        return getMap(key, null);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public NutMap getMap(String key, NutMap dft) {
        Object val = map.get(key);
        if (null == val)
            return null;

        if (val instanceof Map)
            return NutMap.WRAP((Map) val);

        return Lang.map(val.toString());
    }

    public <T> List<T> getList(String key, Class<T> eleType) {
        return map.getList(key, eleType);
    }

    public String check(String key) {
        String v = get(key);
        if (Strings.isBlank(v)) {
            throw Er.create("e.cmd.lack.param", key);
        }
        return v;
    }

    public int checkInt(String key) {
        String v = get(key);
        if (Strings.isBlank(v)) {
            throw Er.create("e.cmd.lack.param.int", key);
        }
        return Integer.valueOf(v);
    }

    public long checkLong(String key) {
        String v = get(key);
        if (Strings.isBlank(v)) {
            throw Er.create("e.cmd.lack.param.long", key);
        }
        return Long.valueOf(v);
    }

    public float checkFloat(String key) {
        String v = get(key);
        if (Strings.isBlank(v)) {
            throw Er.create("e.cmd.lack.param.float", key);
        }
        return Float.valueOf(v);
    }

    public double checkDouble(String key) {
        String v = get(key);
        if (Strings.isBlank(v)) {
            throw Er.create("e.cmd.lack.param.double", key);
        }
        return Double.valueOf(key);
    }

    public NutMap map() {
        return map;
    }

    static class Er {
        public static RuntimeException create(String msg, Object key) {
            return new RuntimeException(String.format("%s : key=%s", msg, key));
        }
    }
}