private byte[] transformThreadPool(ThreadPoolCfg md, byte[] classfileBuffer) { ClassWriter w = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); ClassVisitor a = new PoolClassAdapter(w, md); ClassReader r = new ClassReader(classfileBuffer); r.accept(a, ClassReader.EXPAND_FRAMES); return w.toByteArray(); }
/** * Replaces the given type with the appropriate type if it is one of the types on which a * constructor is invoked in the basic block. * * @param cw the ClassWriter to which this label belongs. * @param t a type * @return t or, if t is one of the types on which a constructor is invoked in the basic block, * the type corresponding to this constructor. */ private int init(final ClassWriter cw, final int t) { int s; if (t == UNINITIALIZED_THIS) { s = OBJECT | cw.addType(cw.thisName); } else if ((t & (DIM | BASE_KIND)) == UNINITIALIZED) { String type = cw.typeTable[t & BASE_VALUE].strVal1; s = OBJECT | cw.addType(type); } else { return t; } for (int j = 0; j < initializationCount; ++j) { int u = initializations[j]; int dim = u & DIM; int kind = u & KIND; if (kind == LOCAL) { u = dim + inputLocals[u & VALUE]; } else if (kind == STACK) { u = dim + inputStack[inputStack.length - (u & VALUE)]; } if (t == u) { return s; } } return t; }
/** * Constructs a new {@link FieldWriter}. * * @param cw the class writer to which this field must be added. * @param access the field's access flags (see {@link Opcodes}). * @param name the field's name. * @param desc the field's descriptor (see {@link Type}). * @param signature the field's signature. May be <tt>null</tt>. * @param value the field's constant value. May be <tt>null</tt>. */ FieldWriter( final ClassWriter cw, final int access, final String name, final String desc, final String signature, final Object value) { super(Opcodes.ASM4); if (cw.firstField == null) { cw.firstField = this; } else { cw.lastField.fv = this; } cw.lastField = this; this.cw = cw; this.access = access; this.name = cw.newUTF8(name); this.desc = cw.newUTF8(desc); if (ClassReader.SIGNATURES && signature != null) { this.signature = cw.newUTF8(signature); } if (value != null) { this.value = cw.newConstItem(value).index; } }
public void visitEnum(final String name, final String desc, final String value) { ++size; if (named) { bv.putShort(cw.newUTF8(name)); } bv.put12('e', cw.newUTF8(desc)).putShort(cw.newUTF8(value)); }
public AnnotationVisitor visitAnnotation(final String name, final String desc) { ++size; if (named) { bv.putShort(cw.newUTF8(name)); } // write tag and type, and reserve space for values count bv.put12('@', cw.newUTF8(desc)).putShort(0); return new AnnotationWriter(cw, true, bv, bv, bv.length - 2); }
/** * Merges the type at the given index in the given type array with the given type. Returns * <tt>true</tt> if the type array has been modified by this operation. * * @param cw the ClassWriter to which this label belongs. * @param t the type with which the type array element must be merged. * @param types an array of types. * @param index the index of the type that must be merged in 'types'. * @return <tt>true</tt> if the type array has been modified by this operation. */ private static boolean merge(final ClassWriter cw, int t, final int[] types, final int index) { int u = types[index]; if (u == t) { // if the types are equal, merge(u,t)=u, so there is no change return false; } if ((t & ~DIM) == NULL) { if (u == NULL) { return false; } t = NULL; } if (u == 0) { // if types[index] has never been assigned, merge(u,t)=t types[index] = t; return true; } int v; if ((u & BASE_KIND) == OBJECT || (u & DIM) != 0) { // if u is a reference type of any dimension if (t == NULL) { // if t is the NULL type, merge(u,t)=u, so there is no change return false; } else if ((t & (DIM | BASE_KIND)) == (u & (DIM | BASE_KIND))) { if ((u & BASE_KIND) == OBJECT) { // if t is also a reference type, and if u and t have the // same dimension merge(u,t) = dim(t) | common parent of the // element types of u and t v = (t & DIM) | OBJECT | cw.getMergedType(t & BASE_VALUE, u & BASE_VALUE); } else { // if u and t are array types, but not with the same element // type, merge(u,t)=java/lang/Object v = OBJECT | cw.addType("java/lang/Object"); } } else if ((t & BASE_KIND) == OBJECT || (t & DIM) != 0) { // if t is any other reference or array type, // merge(u,t)=java/lang/Object v = OBJECT | cw.addType("java/lang/Object"); } else { // if t is any other type, merge(u,t)=TOP v = TOP; } } else if (u == NULL) { // if u is the NULL type, merge(u,t)=t, // or TOP if t is not a reference type v = (t & BASE_KIND) == OBJECT || (t & DIM) != 0 ? t : TOP; } else { // if u is any other type, merge(u,t)=TOP whatever t v = TOP; } if (u != v) { types[index] = v; return true; } return false; }
private void generatePushCommands() throws Exception { if (domain.getService() != null) { for (final Pushmethod method : domain.getService().getPushmethod()) { final ClassWriter classWriter = generatePushCommandX(method, method.getType()); classWriter.addExtend( "com.ponysdk.core.command.AbstractPushCommand<" + method.getType() + ">"); classWriter.generateContentAndStore(); } } }
protected Class findClass(String className) throws ClassNotFoundException { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); InstanceKlass klass = SystemDictionaryHelper.findInstanceKlass(className); ClassWriter cw = new ClassWriter(klass, bos); cw.write(); byte[] buf = bos.toByteArray(); return defineClass(className, buf, 0, buf.length); } catch (Exception e) { throw (ClassNotFoundException) new ClassNotFoundException().initCause(e); } }
private ClassWriter generatePushCommandX(final Pushmethod method, final String type) throws Exception { final String className = method.getName().substring(0, 1).toUpperCase() + method.getName().substring(1) + "Command"; final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getCommandPackage(domain), className); final Parameter pushListener = new Parameter(); pushListener.setName("listener"); pushListener.setClazz("com.ponysdk.core.command.PushListener<" + type + ">"); final List<Parameter> parameters = method.getParameter(); final List<Parameter> clonedParameters = new ArrayList<Parameter>(parameters); clonedParameters.add(pushListener); final Constructor constructor = new Constructor(); constructor.setConstructorParameters(clonedParameters); constructor.setSuperConstructorParameters(Arrays.asList(pushListener)); classWriter.addConstructor(constructor); for (final Parameter param : parameters) { classWriter.addClassMembers(param); } classWriter.addConstants( "private static " + GeneratorHelper.getServiceFullClassName(domain) + " service;"); final StringBuilder template = new StringBuilder(); template.append("@Override\n"); template.append("public com.ponysdk.core.event.HandlerRegistration execute(){\n"); template.append(" if (service == null) {\n"); template.append( " service = com.ponysdk.core.service.PonyServiceRegistry.getPonyService(" + GeneratorHelper.getServiceFullClassName(domain) + ".class);"); template.append(" }\n"); if (method.getParameter().isEmpty()) template.append(" return service.%1$sRegistration(this);\n"); else template.append(" return service.%1$sRegistration(%2$s,this);\n"); template.append("}\n"); classWriter.addMethod( template.toString(), method.getName(), GeneratorHelper.getParameterNamesToString(method.getParameter())); return classWriter; }
/** * Returns the size of this field. * * @return the size of this field. */ int getSize() { int size = 8; if (value != 0) { cw.newUTF8("ConstantValue"); size += 8; } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && (cw.version & 0xffff) < Opcodes.V1_5) { cw.newUTF8("Synthetic"); size += 6; } if ((access & Opcodes.ACC_DEPRECATED) != 0) { cw.newUTF8("Deprecated"); size += 6; } if (cw.version == Opcodes.V1_4 && (access & Opcodes.ACC_ENUM) != 0) { cw.newUTF8("Enum"); size += 6; } if (signature != 0) { cw.newUTF8("Signature"); size += 8; } if (anns != null) { cw.newUTF8("RuntimeVisibleAnnotations"); size += 8 + anns.getSize(); } if (ianns != null) { cw.newUTF8("RuntimeInvisibleAnnotations"); size += 8 + ianns.getSize(); } if (attrs != null) { size += attrs.getSize(cw, null, 0, -1, -1); } return size; }
private void generateCommands() throws Exception { if (domain.getService() != null) { for (final Method method : domain.getService().getMethod()) { final String returnClass = GeneratorHelper.getClassName(method.getReturn()); final ClassWriter classWriter = generateCommandX(method, returnClass); if (returnClass.equals("void") && method.getReturn().getValue() == null) { classWriter.addExtend( "com.ponysdk.core.command.AbstractServiceCommand<java.lang.Object>"); } else { classWriter.addExtend( "com.ponysdk.core.command.AbstractServiceCommand<" + returnClass + ">"); } classWriter.generateContentAndStore(); } } }
public AnnotationVisitor visitArray(final String name) { ++size; if (named) { bv.putShort(cw.newUTF8(name)); } // write tag, and reserve space for array size bv.put12('[', 0); return new AnnotationWriter(cw, false, bv, bv, bv.length - 2); }
/** * Puts the content of this field into the given byte vector. * * @param out where the content of this field must be put. */ void put(final ByteVector out) { out.putShort(access).putShort(name).putShort(desc); int attributeCount = 0; if (value != 0) { ++attributeCount; } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && (cw.version & 0xffff) < Opcodes.V1_5) { ++attributeCount; } if ((access & Opcodes.ACC_DEPRECATED) != 0) { ++attributeCount; } if (cw.version == Opcodes.V1_4 && (access & Opcodes.ACC_ENUM) != 0) { ++attributeCount; } if (signature != 0) { ++attributeCount; } if (anns != null) { ++attributeCount; } if (ianns != null) { ++attributeCount; } if (attrs != null) { attributeCount += attrs.getCount(); } out.putShort(attributeCount); if (value != 0) { out.putShort(cw.newUTF8("ConstantValue")); out.putInt(2).putShort(value); } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && (cw.version & 0xffff) < Opcodes.V1_5) { out.putShort(cw.newUTF8("Synthetic")).putInt(0); } if ((access & Opcodes.ACC_DEPRECATED) != 0) { out.putShort(cw.newUTF8("Deprecated")).putInt(0); } if (cw.version == Opcodes.V1_4 && (access & Opcodes.ACC_ENUM) != 0) { out.putShort(cw.newUTF8("Enum")).putInt(0); } if (signature != 0) { out.putShort(cw.newUTF8("Signature")); out.putInt(2).putShort(signature); } if (anns != null) { out.putShort(cw.newUTF8("RuntimeVisibleAnnotations")); anns.put(out); } if (ianns != null) { out.putShort(cw.newUTF8("RuntimeInvisibleAnnotations")); ianns.put(out); } if (attrs != null) { attrs.put(cw, null, 0, -1, -1, out); } }
private void generateHandler(final Event event) throws Exception { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getEventPackage(domain), GeneratorHelper.getHandlerClassName(event)); classWriter.setInterface(true); classWriter.addExtend("com.ponysdk.core.event.EventHandler"); // Build event method classWriter.addLine( "public void on" + event.getName() + "(" + GeneratorHelper.getEventClassName(event) + " event);"); classWriter.generateContentAndStore(); }
private void generateEventsHandler() throws Exception { if (domain.getCrudevent() != null || (domain.getEvent() != null && !domain.getEvent().isEmpty())) { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getEventPackage(domain), GeneratorHelper.getMasterHandlerClassName(domain)); classWriter.setInterface(true); if (domain.getCrudevent() != null) { for (final String before : GeneratorHelper.getBeforeEventName()) { classWriter.addExtend(before + domain.getName() + "Handler"); } for (final String after : GeneratorHelper.getAfterEventName()) { classWriter.addExtend(domain.getName() + after + "Handler"); } } if (domain.getEvent() != null) { for (final Event event : domain.getEvent()) { classWriter.addExtend(GeneratorHelper.getHandlerClassName(event)); } } classWriter.generateContentAndStore(); } }
/** * Returns the size of this field. * * @return the size of this field. */ int getSize() { int size = 8; if (value != 0) { cw.newUTF8("ConstantValue"); size += 8; } if ((access & Opcodes.ACC_SYNTHETIC) != 0) { if ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0) { cw.newUTF8("Synthetic"); size += 6; } } if ((access & Opcodes.ACC_DEPRECATED) != 0) { cw.newUTF8("Deprecated"); size += 6; } if (ClassReader.SIGNATURES && signature != 0) { cw.newUTF8("Signature"); size += 8; } if (ClassReader.ANNOTATIONS && anns != null) { cw.newUTF8("RuntimeVisibleAnnotations"); size += 8 + anns.getSize(); } if (ClassReader.ANNOTATIONS && ianns != null) { cw.newUTF8("RuntimeInvisibleAnnotations"); size += 8 + ianns.getSize(); } if (attrs != null) { size += attrs.getSize(cw, null, 0, -1, -1); } return size; }
/** * Puts the content of this field into the given byte vector. * * @param out where the content of this field must be put. */ void put(final ByteVector out) { int mask = Opcodes.ACC_DEPRECATED | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE | ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC)); out.putShort(access & ~mask).putShort(name).putShort(desc); int attributeCount = 0; if (value != 0) { ++attributeCount; } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0)) { ++attributeCount; } if ((access & Opcodes.ACC_DEPRECATED) != 0) { ++attributeCount; } if (ClassReader.SIGNATURES && signature != 0) { ++attributeCount; } if (ClassReader.ANNOTATIONS && anns != null) { ++attributeCount; } if (ClassReader.ANNOTATIONS && ianns != null) { ++attributeCount; } if (attrs != null) { attributeCount += attrs.getCount(); } out.putShort(attributeCount); if (value != 0) { out.putShort(cw.newUTF8("ConstantValue")); out.putInt(2).putShort(value); } if ((access & Opcodes.ACC_SYNTHETIC) != 0 && ((cw.version & 0xFFFF) < Opcodes.V1_5 || (access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) != 0)) { out.putShort(cw.newUTF8("Synthetic")).putInt(0); } if ((access & Opcodes.ACC_DEPRECATED) != 0) { out.putShort(cw.newUTF8("Deprecated")).putInt(0); } if (ClassReader.SIGNATURES && signature != 0) { out.putShort(cw.newUTF8("Signature")); out.putInt(2).putShort(signature); } if (ClassReader.ANNOTATIONS && anns != null) { out.putShort(cw.newUTF8("RuntimeVisibleAnnotations")); anns.put(out); } if (ClassReader.ANNOTATIONS && ianns != null) { out.putShort(cw.newUTF8("RuntimeInvisibleAnnotations")); ianns.put(out); } if (attrs != null) { attrs.put(cw, null, 0, -1, -1, out); } }
public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { ByteVector bv = new ByteVector(); // write type, and reserve space for values count bv.putShort(cw.newUTF8(desc)).putShort(0); AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, 2); if (visible) { aw.next = anns; anns = aw; } else { aw.next = ianns; ianns = aw; } return aw; }
/** * Constructs a new {@link FieldWriter}. * * @param cw the class writer to which this field must be added. * @param access the field's access flags (see {@link Opcodes}). * @param name the field's name. * @param desc the field's descriptor (see {@link Type}). * @param signature the field's signature. May be <tt>null</tt>. * @param value the field's constant value. May be <tt>null</tt>. */ protected FieldWriter( final ClassWriter cw, final int access, final String name, final String desc, final String signature, final Object value) { if (cw.firstField == null) { cw.firstField = this; } else { cw.lastField.next = this; } cw.lastField = this; this.cw = cw; this.access = access; this.name = cw.newUTF8(name); this.desc = cw.newUTF8(desc); if (signature != null) { this.signature = cw.newUTF8(signature); } if (value != null) { this.value = cw.newConstItem(value).index; } }
/** * Initializes the input frame of the first basic block from the method descriptor. * * @param cw the ClassWriter to which this label belongs. * @param access the access flags of the method to which this label belongs. * @param args the formal parameter types of this method. * @param maxLocals the maximum number of local variables of this method. */ void initInputFrame( final ClassWriter cw, final int access, final Type[] args, final int maxLocals) { inputLocals = new int[maxLocals]; inputStack = new int[0]; int i = 0; if ((access & Opcodes.ACC_STATIC) == 0) { if ((access & MethodWriter.ACC_CONSTRUCTOR) == 0) { inputLocals[i++] = OBJECT | cw.addType(cw.thisName); } else { inputLocals[i++] = UNINITIALIZED_THIS; } } for (int j = 0; j < args.length; ++j) { int t = type(cw, args[j].getDescriptor()); inputLocals[i++] = t; if (t == LONG || t == DOUBLE) { inputLocals[i++] = TOP; } } while (i < maxLocals) { inputLocals[i++] = TOP; } }
/** * Simulates the action of the given instruction on the output stack frame. * * @param opcode the opcode of the instruction. * @param arg the operand of the instruction, if any. * @param cw the class writer to which this label belongs. * @param item the operand of the instructions, if any. */ void execute(final int opcode, final int arg, final ClassWriter cw, final Item item) { int t1, t2, t3, t4; switch (opcode) { case Opcodes.NOP: case Opcodes.INEG: case Opcodes.LNEG: case Opcodes.FNEG: case Opcodes.DNEG: case Opcodes.I2B: case Opcodes.I2C: case Opcodes.I2S: case Opcodes.GOTO: case Opcodes.RETURN: break; case Opcodes.ACONST_NULL: push(NULL); break; case Opcodes.ICONST_M1: case Opcodes.ICONST_0: case Opcodes.ICONST_1: case Opcodes.ICONST_2: case Opcodes.ICONST_3: case Opcodes.ICONST_4: case Opcodes.ICONST_5: case Opcodes.BIPUSH: case Opcodes.SIPUSH: case Opcodes.ILOAD: push(INTEGER); break; case Opcodes.LCONST_0: case Opcodes.LCONST_1: case Opcodes.LLOAD: push(LONG); push(TOP); break; case Opcodes.FCONST_0: case Opcodes.FCONST_1: case Opcodes.FCONST_2: case Opcodes.FLOAD: push(FLOAT); break; case Opcodes.DCONST_0: case Opcodes.DCONST_1: case Opcodes.DLOAD: push(DOUBLE); push(TOP); break; case Opcodes.LDC: switch (item.type) { case ClassWriter.INT: push(INTEGER); break; case ClassWriter.LONG: push(LONG); push(TOP); break; case ClassWriter.FLOAT: push(FLOAT); break; case ClassWriter.DOUBLE: push(DOUBLE); push(TOP); break; case ClassWriter.CLASS: push(OBJECT | cw.addType("java/lang/Class")); break; // case ClassWriter.STR: default: push(OBJECT | cw.addType("java/lang/String")); } break; case Opcodes.ALOAD: push(get(arg)); break; case Opcodes.IALOAD: case Opcodes.BALOAD: case Opcodes.CALOAD: case Opcodes.SALOAD: pop(2); push(INTEGER); break; case Opcodes.LALOAD: case Opcodes.D2L: pop(2); push(LONG); push(TOP); break; case Opcodes.FALOAD: pop(2); push(FLOAT); break; case Opcodes.DALOAD: case Opcodes.L2D: pop(2); push(DOUBLE); push(TOP); break; case Opcodes.AALOAD: pop(1); t1 = pop(); push(ELEMENT_OF + t1); break; case Opcodes.ISTORE: case Opcodes.FSTORE: case Opcodes.ASTORE: t1 = pop(); set(arg, t1); if (arg > 0) { t2 = get(arg - 1); // if t2 is of kind STACK or LOCAL we cannot know its size! if (t2 == LONG || t2 == DOUBLE) { set(arg - 1, TOP); } else if ((t2 & KIND) != BASE) { set(arg - 1, t2 | TOP_IF_LONG_OR_DOUBLE); } } break; case Opcodes.LSTORE: case Opcodes.DSTORE: pop(1); t1 = pop(); set(arg, t1); set(arg + 1, TOP); if (arg > 0) { t2 = get(arg - 1); // if t2 is of kind STACK or LOCAL we cannot know its size! if (t2 == LONG || t2 == DOUBLE) { set(arg - 1, TOP); } else if ((t2 & KIND) != BASE) { set(arg - 1, t2 | TOP_IF_LONG_OR_DOUBLE); } } break; case Opcodes.IASTORE: case Opcodes.BASTORE: case Opcodes.CASTORE: case Opcodes.SASTORE: case Opcodes.FASTORE: case Opcodes.AASTORE: pop(3); break; case Opcodes.LASTORE: case Opcodes.DASTORE: pop(4); break; case Opcodes.POP: case Opcodes.IFEQ: case Opcodes.IFNE: case Opcodes.IFLT: case Opcodes.IFGE: case Opcodes.IFGT: case Opcodes.IFLE: case Opcodes.IRETURN: case Opcodes.FRETURN: case Opcodes.ARETURN: case Opcodes.TABLESWITCH: case Opcodes.LOOKUPSWITCH: case Opcodes.ATHROW: case Opcodes.MONITORENTER: case Opcodes.MONITOREXIT: case Opcodes.IFNULL: case Opcodes.IFNONNULL: pop(1); break; case Opcodes.POP2: case Opcodes.IF_ICMPEQ: case Opcodes.IF_ICMPNE: case Opcodes.IF_ICMPLT: case Opcodes.IF_ICMPGE: case Opcodes.IF_ICMPGT: case Opcodes.IF_ICMPLE: case Opcodes.IF_ACMPEQ: case Opcodes.IF_ACMPNE: case Opcodes.LRETURN: case Opcodes.DRETURN: pop(2); break; case Opcodes.DUP: t1 = pop(); push(t1); push(t1); break; case Opcodes.DUP_X1: t1 = pop(); t2 = pop(); push(t1); push(t2); push(t1); break; case Opcodes.DUP_X2: t1 = pop(); t2 = pop(); t3 = pop(); push(t1); push(t3); push(t2); push(t1); break; case Opcodes.DUP2: t1 = pop(); t2 = pop(); push(t2); push(t1); push(t2); push(t1); break; case Opcodes.DUP2_X1: t1 = pop(); t2 = pop(); t3 = pop(); push(t2); push(t1); push(t3); push(t2); push(t1); break; case Opcodes.DUP2_X2: t1 = pop(); t2 = pop(); t3 = pop(); t4 = pop(); push(t2); push(t1); push(t4); push(t3); push(t2); push(t1); break; case Opcodes.SWAP: t1 = pop(); t2 = pop(); push(t1); push(t2); break; case Opcodes.IADD: case Opcodes.ISUB: case Opcodes.IMUL: case Opcodes.IDIV: case Opcodes.IREM: case Opcodes.IAND: case Opcodes.IOR: case Opcodes.IXOR: case Opcodes.ISHL: case Opcodes.ISHR: case Opcodes.IUSHR: case Opcodes.L2I: case Opcodes.D2I: case Opcodes.FCMPL: case Opcodes.FCMPG: pop(2); push(INTEGER); break; case Opcodes.LADD: case Opcodes.LSUB: case Opcodes.LMUL: case Opcodes.LDIV: case Opcodes.LREM: case Opcodes.LAND: case Opcodes.LOR: case Opcodes.LXOR: pop(4); push(LONG); push(TOP); break; case Opcodes.FADD: case Opcodes.FSUB: case Opcodes.FMUL: case Opcodes.FDIV: case Opcodes.FREM: case Opcodes.L2F: case Opcodes.D2F: pop(2); push(FLOAT); break; case Opcodes.DADD: case Opcodes.DSUB: case Opcodes.DMUL: case Opcodes.DDIV: case Opcodes.DREM: pop(4); push(DOUBLE); push(TOP); break; case Opcodes.LSHL: case Opcodes.LSHR: case Opcodes.LUSHR: pop(3); push(LONG); push(TOP); break; case Opcodes.IINC: set(arg, INTEGER); break; case Opcodes.I2L: case Opcodes.F2L: pop(1); push(LONG); push(TOP); break; case Opcodes.I2F: pop(1); push(FLOAT); break; case Opcodes.I2D: case Opcodes.F2D: pop(1); push(DOUBLE); push(TOP); break; case Opcodes.F2I: case Opcodes.ARRAYLENGTH: case Opcodes.INSTANCEOF: pop(1); push(INTEGER); break; case Opcodes.LCMP: case Opcodes.DCMPL: case Opcodes.DCMPG: pop(4); push(INTEGER); break; case Opcodes.JSR: case Opcodes.RET: throw new RuntimeException("JSR/RET are not supported with computeFrames option"); case Opcodes.GETSTATIC: push(cw, item.strVal3); break; case Opcodes.PUTSTATIC: pop(item.strVal3); break; case Opcodes.GETFIELD: pop(1); push(cw, item.strVal3); break; case Opcodes.PUTFIELD: pop(item.strVal3); pop(); break; case Opcodes.INVOKEVIRTUAL: case Opcodes.INVOKESPECIAL: case Opcodes.INVOKESTATIC: case Opcodes.INVOKEINTERFACE: pop(item.strVal3); if (opcode != Opcodes.INVOKESTATIC) { t1 = pop(); if (opcode == Opcodes.INVOKESPECIAL && item.strVal2.charAt(0) == '<') { init(t1); } } push(cw, item.strVal3); break; case Opcodes.INVOKEDYNAMIC: pop(item.strVal2); push(cw, item.strVal2); break; case Opcodes.NEW: push(UNINITIALIZED | cw.addUninitializedType(item.strVal1, arg)); break; case Opcodes.NEWARRAY: pop(); switch (arg) { case Opcodes.T_BOOLEAN: push(ARRAY_OF | BOOLEAN); break; case Opcodes.T_CHAR: push(ARRAY_OF | CHAR); break; case Opcodes.T_BYTE: push(ARRAY_OF | BYTE); break; case Opcodes.T_SHORT: push(ARRAY_OF | SHORT); break; case Opcodes.T_INT: push(ARRAY_OF | INTEGER); break; case Opcodes.T_FLOAT: push(ARRAY_OF | FLOAT); break; case Opcodes.T_DOUBLE: push(ARRAY_OF | DOUBLE); break; // case Opcodes.T_LONG: default: push(ARRAY_OF | LONG); break; } break; case Opcodes.ANEWARRAY: String s = item.strVal1; pop(); if (s.charAt(0) == '[') { push(cw, '[' + s); } else { push(ARRAY_OF | OBJECT | cw.addType(s)); } break; case Opcodes.CHECKCAST: s = item.strVal1; pop(); if (s.charAt(0) == '[') { push(cw, s); } else { push(OBJECT | cw.addType(s)); } break; // case Opcodes.MULTIANEWARRAY: default: pop(arg); push(cw, item.strVal1); break; } }
private ClassWriter generateCommandX(final Method method, final String resultClass) throws Exception { final String className = method.getName().substring(0, 1).toUpperCase() + method.getName().substring(1) + "Command"; final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getCommandPackage(domain), className); final Constructor constructor = new Constructor(); final Parameter eventBusParameter = new Parameter(); eventBusParameter.setName("eventBus"); eventBusParameter.setClazz("com.ponysdk.core.event.EventBus"); final List<Parameter> parameters = method.getParameter(); final List<Parameter> clonedParameters = new ArrayList<Parameter>(); for (final Parameter parameter : parameters) { final Parameter clonedParameter = new Parameter(); clonedParameter.setClazz(parameter.getClazz()); clonedParameter.setName(parameter.getName()); clonedParameter.setCollection(parameter.getCollection()); clonedParameters.add(clonedParameter); } final Constructor constructor2 = new Constructor(); constructor2.setConstructorParameters(new ArrayList<Parameter>(clonedParameters)); clonedParameters.add(0, eventBusParameter); constructor.setConstructorParameters(clonedParameters); constructor.setSuperConstructorParameters(Arrays.asList(eventBusParameter)); classWriter.addConstructor(constructor); classWriter.addConstructor(constructor2); for (final Parameter param : parameters) { classWriter.addClassMembers(param); } classWriter.addConstants( "private static " + GeneratorHelper.getServiceFullClassName(domain) + " service;"); final StringBuilder template = new StringBuilder(); template.append("@Override\n"); if (resultClass.equals("void") && method.getReturn().getValue() == null) { template.append("protected java.lang.Void execute0() throws Exception {\n"); } else { template.append("protected " + resultClass + " execute0() throws Exception {\n"); } template.append(" if (service == null) {\n"); template.append( " service = com.ponysdk.core.service.PonyServiceRegistry.getPonyService(" + GeneratorHelper.getServiceFullClassName(domain) + ".class);"); template.append(" }\n"); if (resultClass.equals("void") && method.getReturn().getValue() == null) { template.append(" service.%1$s(%2$s);\n"); template.append(" return null;\n"); } else { template.append(" return service.%1$s(%2$s);\n"); } template.append("}\n"); classWriter.addMethod( template.toString(), method.getName(), GeneratorHelper.getParameterNamesToString(method.getParameter())); return classWriter; }
private void generateCRUDMethos() throws Exception { // Insert CRUD methods if (domain.getService() != null && domain.getService().getCrudmethod() != null) { // Return final Return crudReturn = new Return(); crudReturn.setClazz(domain.getService().getCrudmethod().getClazz()); // Parameters final Parameter crudParameter = new Parameter(); crudParameter.setClazz(domain.getService().getCrudmethod().getClazz()); crudParameter.setName(GeneratorHelper.getFirstCharToLower(domain.getName())); final Parameter crudIDParameter = new Parameter(); crudIDParameter.setClazz("long"); crudIDParameter.setName(GeneratorHelper.getFirstCharToLower(domain.getName()) + "ID"); // Add CRUD methods final Method createMethod = createCRUDMethod("create" + domain.getName(), crudParameter, crudReturn); final Method readMethod = createCRUDMethod("read" + domain.getName(), crudIDParameter, crudReturn); final Method updateMethod = createCRUDMethod("update" + domain.getName(), crudParameter, crudReturn); final Method deleteMethod = createCRUDMethod("delete" + domain.getName(), crudIDParameter, new Return()); // Create the implementation class of these CRUD methods if the HibernateDAO is set if (domain.getService().getDao() != null) { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getServerServicePackage(domain), GeneratorHelper.getServiceImplClassName(domain)); classWriter.addImplements(GeneratorHelper.getServiceClassName(domain)); classWriter.setGenerateGetter(true); classWriter.setGenerateSetter(true); // Add static logger classWriter.addConstants( "private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(" + GeneratorHelper.getServiceImplClassName(domain) + ".class);"); // Add service HibernateDAO object final Parameter daoParameter = new Parameter(); daoParameter.setClazz( GeneratorHelper.getDAOPackage(domain) + "." + GeneratorHelper.getDAOClassName(domain)); daoParameter.setName( GeneratorHelper.getFirstCharToLower(GeneratorHelper.getDAOClassName(domain))); classWriter.addClassMembers(daoParameter); for (final Method method : domain.getService().getMethod()) { final String resultClass = GeneratorHelper.getClassName(method.getReturn()); classWriter.addNewLine(); classWriter.addLine("@Override"); classWriter.addLine( "public " + resultClass + " " + method.getName() + "(" + GeneratorHelper.getParameterToString(method.getParameter()) + ") throws Exception {"); if (!"void".equals(resultClass)) { classWriter.addLine(" return null;"); } classWriter.addLine("}"); } final String domainClass = domain.getName(); final String domainDAOParameter = GeneratorHelper.getFirstCharToLower(GeneratorHelper.getDAOClassName(domain)); final String domainParameter = GeneratorHelper.getFirstCharToLower(domain.getName()); final String domainParameterID = domainParameter + "ID"; /* * CRUD method implementation */ // Create classWriter.addLine("@Override"); classWriter.addLine( "public " + GeneratorHelper.getClassName(createMethod.getReturn()) + " " + createMethod.getName() + " (" + GeneratorHelper.getParameterToString(createMethod.getParameter()) + ") throws Exception {"); classWriter.addLine(" " + domainDAOParameter + ".beginTransaction();"); classWriter.addLine(" try {"); classWriter.addLine(" " + domainDAOParameter + ".save(" + domainParameter + ");"); classWriter.addLine(" " + domainDAOParameter + ".commit();"); classWriter.addLine(" } catch (final Exception e) {"); classWriter.addLine( " log.error(\"final Cannot create " + domainClass + " in database\", e);"); classWriter.addLine(" " + domainDAOParameter + ".rollback();"); classWriter.addLine( " throw new Exception(\"Cannot create " + domainClass + " in database\", e);"); classWriter.addLine(" }"); classWriter.addLine(" return " + domainParameter + ";"); classWriter.addLine("}"); // Read classWriter.addLine("@Override"); classWriter.addLine( "public " + GeneratorHelper.getClassName(createMethod.getReturn()) + " " + readMethod.getName() + " (" + GeneratorHelper.getParameterToString(readMethod.getParameter()) + ") throws Exception {"); classWriter.addLine( " " + GeneratorHelper.getClassName(createMethod.getReturn()) + " " + domainParameter + " = null;"); classWriter.addLine(" " + domainDAOParameter + ".beginTransaction();"); classWriter.addLine(" try {"); classWriter.addLine( " " + domainParameter + " = " + domainDAOParameter + ".findById(" + domainParameterID + ");"); classWriter.addLine(" " + domainDAOParameter + ".commit();"); classWriter.addLine(" } catch (final Exception e) {"); classWriter.addLine( " log.error(\"final Cannot find " + domain.getName() + " in database\", e);"); classWriter.addLine(" " + domainDAOParameter + ".rollback();"); classWriter.addLine( " throw new Exception(\"Cannot find " + domain.getName() + " in database\", e);"); classWriter.addLine(" }"); classWriter.addLine(" return " + domainParameter + ";"); classWriter.addLine("}"); // Update classWriter.addLine("@Override"); classWriter.addLine( "public " + GeneratorHelper.getClassName(updateMethod.getReturn()) + " " + updateMethod.getName() + " (" + GeneratorHelper.getParameterToString(updateMethod.getParameter()) + ") throws Exception {"); classWriter.addLine(" " + domainDAOParameter + ".beginTransaction();"); classWriter.addLine(" try {"); classWriter.addLine( " " + domainDAOParameter + ".saveOrUpdate(" + domainParameter + ");"); classWriter.addLine(" " + domainDAOParameter + ".commit();"); classWriter.addLine(" } catch (final Exception e) {"); classWriter.addLine( " log.error(\"final Cannot update " + domainClass + " in database\", e);"); classWriter.addLine(" " + domainDAOParameter + ".rollback();"); classWriter.addLine( " throw new Exception(\"Cannot update " + domainClass + " in database\", e);"); classWriter.addLine(" }"); classWriter.addLine(" return " + domainParameter + ";"); classWriter.addLine("}"); // Delete classWriter.addLine("@Override"); classWriter.addLine( "public " + GeneratorHelper.getClassName(deleteMethod.getReturn()) + " " + deleteMethod.getName() + " (" + GeneratorHelper.getParameterToString(deleteMethod.getParameter()) + ") throws Exception {"); classWriter.addLine(" " + domainDAOParameter + ".beginTransaction();"); classWriter.addLine(" try {"); classWriter.addLine( " " + GeneratorHelper.getClassName(createMethod.getReturn()) + " " + domainParameter + " = " + domainDAOParameter + ".findById(" + domainParameterID + ");"); classWriter.addLine(" " + domainDAOParameter + ".delete(" + domainParameter + ");"); classWriter.addLine(" " + domainDAOParameter + ".commit();"); classWriter.addLine(" } catch (final Exception e) {"); classWriter.addLine( " log.error(\"final Cannot delete " + domain.getName() + " in database\", e);"); classWriter.addLine(" " + domainDAOParameter + ".rollback();"); classWriter.addLine( " throw new Exception(\"Cannot delete " + domain.getName() + " in database\", e);"); classWriter.addLine(" }"); classWriter.addLine("}"); classWriter.generateContentAndStore(); } domain.getService().getMethod().add(createMethod); domain.getService().getMethod().add(readMethod); domain.getService().getMethod().add(updateMethod); domain.getService().getMethod().add(deleteMethod); } }
private void generateEvent(final Event event) throws Exception { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getEventPackage(domain), GeneratorHelper.getEventClassName(event)); if (event.getParameter() != null) { for (final Parameter parameter : event.getParameter()) { classWriter.addClassMembers(parameter); } } classWriter.addExtend(GeneratorHelper.getBusinessEventExtends(event)); // Constant classWriter.addConstants( "public static final com.ponysdk.core.event.Event.Type<" + GeneratorHelper.getHandlerClassName(event) + "> TYPE = new com.ponysdk.core.event.Event.Type<" + GeneratorHelper.getHandlerClassName(event) + ">();"); // Build constructor final Parameter sourceComponentParameter = new Parameter(); sourceComponentParameter.setName("sourceComponent"); sourceComponentParameter.setClazz("java.lang.Object"); final List<Parameter> superConstructorParameters = new ArrayList<Parameter>(); superConstructorParameters.add(sourceComponentParameter); final List<Parameter> constructorParameters = new ArrayList<Parameter>(event.getParameter()); constructorParameters.add(0, sourceComponentParameter); final Constructor constructor = new Constructor(constructorParameters, superConstructorParameters); classWriter.addConstructor(constructor); // Build methods classWriter.addLine("@Override"); classWriter.addLine( "protected void dispatch(" + GeneratorHelper.getHandlerClassName(event) + " handler) {"); classWriter.addLine(" handler.on" + event.getName() + "(this);"); classWriter.addLine("}"); classWriter.addNewLine(); classWriter.addLine("@Override"); classWriter.addLine( "public com.ponysdk.core.event.Event.Type<" + GeneratorHelper.getHandlerClassName(event) + "> getAssociatedType() {"); classWriter.addLine(" return TYPE;"); classWriter.addLine("}"); // Adding classWriter.setGenerateGetter(true); classWriter.generateContentAndStore(); }
/** * Returns the int encoding of the given type. * * @param cw the ClassWriter to which this label belongs. * @param desc a type descriptor. * @return the int encoding of the given type. */ private static int type(final ClassWriter cw, final String desc) { String t; int index = desc.charAt(0) == '(' ? desc.indexOf(')') + 1 : 0; switch (desc.charAt(index)) { case 'V': return 0; case 'Z': case 'C': case 'B': case 'S': case 'I': return INTEGER; case 'F': return FLOAT; case 'J': return LONG; case 'D': return DOUBLE; case 'L': // stores the internal name, not the descriptor! t = desc.substring(index + 1, desc.length() - 1); return OBJECT | cw.addType(t); // case '[': default: // extracts the dimensions and the element type int data; int dims = index + 1; while (desc.charAt(dims) == '[') { ++dims; } switch (desc.charAt(dims)) { case 'Z': data = BOOLEAN; break; case 'C': data = CHAR; break; case 'B': data = BYTE; break; case 'S': data = SHORT; break; case 'I': data = INTEGER; break; case 'F': data = FLOAT; break; case 'J': data = LONG; break; case 'D': data = DOUBLE; break; // case 'L': default: // stores the internal name, not the descriptor t = desc.substring(dims + 1, desc.length() - 1); data = OBJECT | cw.addType(t); } return (dims - index) << 28 | data; } }
/** * 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() { // 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 = fb.next; } int nbMethods = 0; MethodWriter mb = firstMethod; while (mb != null) { ++nbMethods; size += mb.getSize(); mb = mb.next; } int attributeCount = 0; if (signature != 0) { ++attributeCount; size += 8; newUTF8("Signature"); } if (sourceFile != 0) { ++attributeCount; size += 8; newUTF8("SourceFile"); } if (sourceDebug != null) { ++attributeCount; size += sourceDebug.length + 4; 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 && (version & 0xffff) < Opcodes.V1_5) { ++attributeCount; size += 6; newUTF8("Synthetic"); } if (innerClasses != null) { ++attributeCount; size += 8 + innerClasses.length; newUTF8("InnerClasses"); } if (anns != null) { ++attributeCount; size += 8 + anns.getSize(); newUTF8("RuntimeVisibleAnnotations"); } if (ianns != null) { ++attributeCount; size += 8 + ianns.getSize(); newUTF8("RuntimeInvisibleAnnotations"); } 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); out.putShort(access).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 = fb.next; } out.putShort(nbMethods); mb = firstMethod; while (mb != null) { mb.put(out); mb = mb.next; } out.putShort(attributeCount); if (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 - 2; out.putShort(newUTF8("SourceDebugExtension")).putInt(len); out.putByteArray(sourceDebug.data, 2, 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 && (version & 0xffff) < Opcodes.V1_5) { 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 (anns != null) { out.putShort(newUTF8("RuntimeVisibleAnnotations")); anns.put(out); } if (ianns != null) { out.putShort(newUTF8("RuntimeInvisibleAnnotations")); ianns.put(out); } if (attrs != null) { attrs.put(this, null, 0, -1, -1, out); } if (invalidFrames) { ClassWriter cw = new ClassWriter(COMPUTE_FRAMES); new ClassReader(out.data).accept(cw, ClassReader.SKIP_FRAMES); return cw.toByteArray(); } return out.data; }
/* * Services : MongoDBDAO */ private void generateMongoDBDAO(final Dao dao) throws Exception { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getDAOPackage(domain), GeneratorHelper.getDAOClassName(domain)); classWriter.addImport("com.fasterxml.jackson.databind.ObjectMapper"); classWriter.addImport("com.mongodb.BasicDBObject"); classWriter.addImport("com.mongodb.DBCollection"); classWriter.addImport("com.mongodb.DBObject"); classWriter.addImport("com.mongodb.DBCursor"); classWriter.addImport("java.util.List"); classWriter.addImport("java.util.ArrayList"); classWriter.addExtend("com.ponysdk.mongodb.dao.MongoDAO"); // Add static logger classWriter.addConstants( "private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(" + GeneratorHelper.getDAOClassName(domain) + ".class);"); // Create constructor final List<Parameter> parameters = new ArrayList<Parameter>(); final Parameter sessionFactoryParameter = new Parameter(); sessionFactoryParameter.setName("sessionFactory"); sessionFactoryParameter.setClazz("org.hibernate.SessionFactory"); // parameters.add(sessionFactoryParameter); final Constructor constructor = new Constructor(parameters, parameters); classWriter.addConstructor(constructor); // Create findById method classWriter.addNewLine(); classWriter.addLine("final public " + dao.getClazz() + " findById(final long id) {"); classWriter.addLine(" if (log.isDebugEnabled()) {"); classWriter.addLine( " log.debug(\"getting " + domain.getName() + " instance with id: \" + id);"); classWriter.addLine(" }"); classWriter.addNewLine(); classWriter.addLine(" try {"); classWriter.addLine( " DBCollection collection = db.getCollection(\"" + domain.getName().toLowerCase() + "\");"); classWriter.addLine(" BasicDBObject basicDBObject = new BasicDBObject(\"id\"," + "id);"); classWriter.addLine(" final DBObject foundInstance = collection.findOne(basicDBObject);"); classWriter.addLine(" " + dao.getClazz() + " instance = null;"); classWriter.addLine(" return toModel(foundInstance);"); classWriter.addLine(" } catch (final Exception re) {"); classWriter.addLine(" log.error(\"getting " + domain.getName() + " by id failed\", re);"); classWriter.addLine(" throw new RuntimeException(re);"); classWriter.addLine(" }"); classWriter.addLine("}"); classWriter.addLine("private " + dao.getClazz() + " toModel(DBObject dbObject) {"); classWriter.addLine(" if (dbObject == null) return null;"); classWriter.addLine(" final ObjectMapper mapper = new ObjectMapper();"); classWriter.addLine(" try{"); classWriter.addLine( " " + dao.getClazz() + " model = mapper.readValue(dbObject.toString(), " + dao.getClazz() + ".class);"); classWriter.addLine(" model.setID(dbObject.get(\"_id\"));"); classWriter.addLine(" return model;"); classWriter.addLine(" } catch (final Exception e) {"); classWriter.addLine(" log.error(\"toModel " + domain.getName() + " failed\", e);"); classWriter.addLine(" throw new RuntimeException(e);"); classWriter.addLine(" }"); classWriter.addLine("}"); // Create findAll method classWriter.addNewLine(); classWriter.addLine("@SuppressWarnings(\"unchecked\")"); classWriter.addLine("public java.util.List<" + dao.getClazz() + "> findAll() {"); classWriter.addLine(" if (log.isDebugEnabled()) {"); classWriter.addLine(" log.debug(\"finding all " + domain.getName() + "\");"); classWriter.addLine(" }"); classWriter.addNewLine(); classWriter.addLine(" DBCursor cursor = null;"); classWriter.addLine(" try {"); classWriter.addLine( " DBCollection collection = db.getCollection(\"" + domain.getName().toLowerCase() + "\");"); classWriter.addLine(" cursor = collection.find();"); classWriter.addLine( " List<" + dao.getClazz() + "> result = new ArrayList<" + dao.getClazz() + ">();"); classWriter.addLine(" while(cursor.hasNext()){"); classWriter.addLine(" result.add(toModel(cursor.next()));"); classWriter.addLine(" }"); classWriter.addLine(" return result;"); classWriter.addLine(" } catch (final RuntimeException re) {"); classWriter.addLine(" log.error(\"finding all " + domain.getName() + " failed\", re);"); classWriter.addLine(" throw re;"); classWriter.addLine(" } finally{"); classWriter.addLine(" cursor.close();"); classWriter.addLine(" }"); classWriter.addLine("}"); // Create find by query method classWriter.addNewLine(); classWriter.addLine("@SuppressWarnings(\"unchecked\")"); classWriter.addLine("@Override"); classWriter.addLine("public java.util.List<" + dao.getClazz() + "> find(Object query) {"); classWriter.addLine(" if (log.isDebugEnabled()) {"); classWriter.addLine(" log.debug(\"finding " + domain.getName() + " by query\");"); classWriter.addLine(" }"); classWriter.addNewLine(); classWriter.addLine(" DBCursor cursor = null;"); classWriter.addLine(" try {"); classWriter.addLine( " DBCollection collection = db.getCollection(\"" + domain.getName().toLowerCase() + "\");"); classWriter.addLine(" cursor = collection.find((DBObject)query);"); classWriter.addLine( " List<" + dao.getClazz() + "> result = new ArrayList<" + dao.getClazz() + ">();"); classWriter.addLine(" while(cursor.hasNext()){"); classWriter.addLine(" result.add(toModel(cursor.next()));"); classWriter.addLine(" }"); classWriter.addLine(" return result;"); classWriter.addLine(" } catch (final RuntimeException re) {"); classWriter.addLine(" log.error(\"find " + domain.getName() + " failed\", re);"); classWriter.addLine(" throw re;"); classWriter.addLine(" } finally{"); classWriter.addLine(" cursor.close();"); classWriter.addLine(" }"); classWriter.addLine("}"); classWriter.generateContentAndStore(); }
public void visit(final String name, final Object value) { ++size; if (named) { bv.putShort(cw.newUTF8(name)); } if (value instanceof String) { bv.put12('s', cw.newUTF8((String) value)); } else if (value instanceof Byte) { bv.put12('B', cw.newInteger(((Byte) value).byteValue()).index); } else if (value instanceof Boolean) { int v = ((Boolean) value).booleanValue() ? 1 : 0; bv.put12('Z', cw.newInteger(v).index); } else if (value instanceof Character) { bv.put12('C', cw.newInteger(((Character) value).charValue()).index); } else if (value instanceof Short) { bv.put12('S', cw.newInteger(((Short) value).shortValue()).index); } else if (value instanceof Type) { bv.put12('c', cw.newUTF8(((Type) value).getDescriptor())); } else if (value instanceof byte[]) { byte[] v = (byte[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('B', cw.newInteger(v[i]).index); } } else if (value instanceof boolean[]) { boolean[] v = (boolean[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('Z', cw.newInteger(v[i] ? 1 : 0).index); } } else if (value instanceof short[]) { short[] v = (short[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('S', cw.newInteger(v[i]).index); } } else if (value instanceof char[]) { char[] v = (char[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('C', cw.newInteger(v[i]).index); } } else if (value instanceof int[]) { int[] v = (int[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('I', cw.newInteger(v[i]).index); } } else if (value instanceof long[]) { long[] v = (long[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('J', cw.newLong(v[i]).index); } } else if (value instanceof float[]) { float[] v = (float[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('F', cw.newFloat(v[i]).index); } } else if (value instanceof double[]) { double[] v = (double[]) value; bv.put12('[', v.length); for (int i = 0; i < v.length; i++) { bv.put12('D', cw.newDouble(v[i]).index); } } else { Item i = cw.newConstItem(value); bv.put12(".s.IFJDCS".charAt(i.type), i.index); } }
public byte[] buildClass(ClassDefinition core) throws IOException, IntrospectionException, SecurityException, IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException { Class coreKlazz = core.getDefinedClass(); String coreName = coreKlazz.getName(); String wrapperName = coreName + "Wrapper"; ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); FieldVisitor fv; MethodVisitor mv; cw.visit( V1_5, ACC_PUBLIC + ACC_SUPER, BuildUtils.getInternalType(wrapperName), BuildUtils.getTypeDescriptor(coreName) + "Lorg/drools/factmodel/traits/CoreWrapper<" + BuildUtils.getTypeDescriptor(coreName) + ">;", BuildUtils.getInternalType(coreName), new String[] { Type.getInternalName(CoreWrapper.class), Type.getInternalName(Externalizable.class) }); { fv = cw.visitField(ACC_PRIVATE, "core", BuildUtils.getTypeDescriptor(coreName), null, null); fv.visitEnd(); } { fv = cw.visitField( ACC_PRIVATE, TraitableBean.MAP_FIELD_NAME, Type.getDescriptor(Map.class), "Ljava/util/Map<Ljava/lang/String;Ljava/lang/Object;>;", null); fv.visitEnd(); } { fv = cw.visitField( ACC_PRIVATE, TraitableBean.TRAITSET_FIELD_NAME, Type.getDescriptor(Map.class), "Ljava/util/Map<Ljava/lang/String;Lorg/drools/factmodel/traits/Thing;>;", null); fv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, BuildUtils.getInternalType(coreName), "<init>", "()V"); // mv.visitVarInsn( ALOAD, 0 ); // mv.visitTypeInsn( NEW, Type.getInternalName( HashMap.class ) ); // mv.visitInsn( DUP ); // mv.visitMethodInsn( INVOKESPECIAL, Type.getInternalName( HashMap.class ), // "<init>", "()V" ); // mv.visitFieldInsn( PUTFIELD, // BuildUtils.getInternalType( wrapperName ), // TraitableBean.MAP_FIELD_NAME, // Type.getDescriptor( Map.class ) ); // mv.visitVarInsn( ALOAD, 0 ); // mv.visitTypeInsn( NEW, Type.getInternalName( VetoableTypedMap.class ) ); // mv.visitInsn( DUP ); // mv.visitTypeInsn( NEW, Type.getInternalName( HashMap.class ) ); // mv.visitInsn( DUP ); // mv.visitMethodInsn( INVOKESPECIAL, Type.getInternalName( HashMap.class ), // "<init>", "()V" ); // mv.visitMethodInsn( INVOKESPECIAL, Type.getInternalName( VetoableTypedMap.class // ), "<init>", "(" + Type.getDescriptor( Map.class ) + ")V" ); // mv.visitFieldInsn( PUTFIELD, // BuildUtils.getInternalType( wrapperName ), // TraitableBean.TRAITSET_FIELD_NAME, // Type.getDescriptor( Map.class ) ); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } if (coreKlazz == null || needsMethod(coreKlazz, "getCore")) { { mv = cw.visitMethod( ACC_PUBLIC, "getCore", "()" + Type.getDescriptor(Object.class), "()" + BuildUtils.getTypeDescriptor(coreName), null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn( GETFIELD, BuildUtils.getInternalType(wrapperName), "core", BuildUtils.getTypeDescriptor(coreName)); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } if (coreKlazz == null || needsMethod(coreKlazz, "getDynamicProperties")) { { mv = cw.visitMethod( ACC_PUBLIC, "getDynamicProperties", "()" + Type.getDescriptor(Map.class), "()Ljava/util/Map<Ljava/lang/String;Ljava/lang/Object;>;", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn( GETFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.MAP_FIELD_NAME, Type.getDescriptor(Map.class)); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); mv = cw.visitMethod( ACC_PUBLIC, "setDynamicProperties", "(" + Type.getDescriptor(Map.class) + ")V", "(Ljava/util/Map<Ljava/lang/String;Ljava/lang/Object;>;)V", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitFieldInsn( PUTFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.MAP_FIELD_NAME, Type.getDescriptor(Map.class)); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } if (coreKlazz == null || needsMethod(coreKlazz, "getTraitMap")) { { mv = cw.visitMethod( ACC_PUBLIC, "getTraitMap", "()" + Type.getDescriptor(Map.class), "()Ljava/util/Map<Ljava/lang/String;Lorg/drools/factmodel/traits/Thing;>;", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn( GETFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.TRAITSET_FIELD_NAME, Type.getDescriptor(Map.class)); Label l0 = new Label(); mv.visitJumpInsn(IFNONNULL, l0); mv.visitVarInsn(ALOAD, 0); mv.visitTypeInsn(NEW, Type.getInternalName(VetoableTypedMap.class)); mv.visitInsn(DUP); mv.visitTypeInsn(NEW, Type.getInternalName(HashMap.class)); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(HashMap.class), "<init>", "()V"); mv.visitMethodInsn( INVOKESPECIAL, Type.getInternalName(VetoableTypedMap.class), "<init>", "(" + Type.getDescriptor(Map.class) + ")V"); mv.visitFieldInsn( PUTFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.TRAITSET_FIELD_NAME, Type.getDescriptor(Map.class)); mv.visitLabel(l0); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn( GETFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.TRAITSET_FIELD_NAME, Type.getDescriptor(Map.class)); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } if (coreKlazz == null || needsMethod(coreKlazz, "setTraitMap", Map.class)) { { mv = cw.visitMethod(ACC_PUBLIC, "setTraitMap", "(Ljava/util/Map;)V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitTypeInsn(NEW, Type.getInternalName(VetoableTypedMap.class)); mv.visitInsn(DUP); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn( INVOKESPECIAL, Type.getInternalName(VetoableTypedMap.class), "<init>", "(" + Type.getDescriptor(Map.class) + ")V"); mv.visitFieldInsn( PUTFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.TRAITSET_FIELD_NAME, Type.getDescriptor(Map.class)); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } if (coreKlazz == null || needsMethod(coreKlazz, "addTrait", String.class, Thing.class)) { { mv = cw.visitMethod( ACC_PUBLIC, "addTrait", "(" + Type.getDescriptor(String.class) + Type.getDescriptor(Thing.class) + ")V", "(" + Type.getDescriptor(String.class) + Type.getDescriptor(Thing.class) + ")V", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn( INVOKEVIRTUAL, BuildUtils.getInternalType(wrapperName), "getTraitMap", "()" + Type.getDescriptor(Map.class)); mv.visitTypeInsn(CHECKCAST, Type.getInternalName(VetoableTypedMap.class)); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn( INVOKEVIRTUAL, Type.getInternalName(VetoableTypedMap.class), "putSafe", "(" + Type.getDescriptor(String.class) + Type.getDescriptor(Thing.class) + ")" + Type.getDescriptor(Thing.class)); mv.visitInsn(POP); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } if (coreKlazz == null || needsMethod(coreKlazz, "getTrait", String.class)) { { mv = cw.visitMethod( ACC_PUBLIC, "getTrait", "(" + Type.getDescriptor(String.class) + ")" + Type.getDescriptor(Thing.class), "(" + Type.getDescriptor(String.class) + ")" + Type.getDescriptor(Thing.class), null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn( INVOKEVIRTUAL, BuildUtils.getInternalType(wrapperName), "getTraitMap", "()" + Type.getDescriptor(Map.class)); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn( INVOKEINTERFACE, Type.getInternalName(Map.class), "get", "(" + Type.getDescriptor(Object.class) + ")" + Type.getDescriptor(Object.class)); mv.visitTypeInsn(CHECKCAST, Type.getInternalName(Thing.class)); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } if (coreKlazz == null || needsMethod(coreKlazz, "hasTrait", String.class)) { { mv = cw.visitMethod( ACC_PUBLIC, "hasTrait", "(" + Type.getDescriptor(String.class) + ")Z", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn( INVOKEVIRTUAL, BuildUtils.getInternalType(wrapperName), "getTraitMap", "()" + Type.getDescriptor(Map.class)); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn( INVOKEINTERFACE, Type.getInternalName(Map.class), "containsKey", "(" + Type.getDescriptor(Object.class) + ")Z"); mv.visitInsn(IRETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } if (coreKlazz == null || needsMethod(coreKlazz, "removeTrait", String.class)) { { mv = cw.visitMethod( ACC_PUBLIC, "removeTrait", "(" + Type.getDescriptor(String.class) + ")" + Type.getDescriptor(Thing.class), "(" + Type.getDescriptor(String.class) + ")" + Type.getDescriptor(Thing.class), null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn( INVOKEVIRTUAL, BuildUtils.getInternalType(wrapperName), "getTraitMap", "()" + Type.getDescriptor(Map.class)); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn( INVOKEINTERFACE, Type.getInternalName(Map.class), "remove", "(" + Type.getDescriptor(Object.class) + ")" + Type.getDescriptor(Object.class)); mv.visitTypeInsn(CHECKCAST, Type.getInternalName(Thing.class)); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } if (coreKlazz == null || needsMethod(coreKlazz, "getTraits")) { { mv = cw.visitMethod( ACC_PUBLIC, "getTraits", "()" + Type.getDescriptor(Collection.class), "()Ljava/util/Collection<Ljava/lang/String;>;", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn( INVOKEVIRTUAL, BuildUtils.getInternalType(wrapperName), "getTraitMap", "()" + Type.getDescriptor(Map.class)); mv.visitMethodInsn( INVOKEINTERFACE, Type.getInternalName(Map.class), "keySet", "()" + Type.getDescriptor(Set.class)); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } } { mv = cw.visitMethod( ACC_PUBLIC, "writeExternal", "(" + Type.getDescriptor(ObjectOutput.class) + ")V", null, new String[] {Type.getInternalName(IOException.class)}); mv.visitCode(); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn( INVOKEVIRTUAL, BuildUtils.getInternalType(wrapperName), "getCore", "()" + Type.getDescriptor(Object.class)); mv.visitMethodInsn( INVOKEINTERFACE, Type.getInternalName(ObjectOutput.class), "writeObject", "(" + Type.getDescriptor(Object.class) + ")V"); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn( GETFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.MAP_FIELD_NAME, Type.getDescriptor(Map.class)); mv.visitMethodInsn( INVOKEINTERFACE, Type.getInternalName(ObjectOutput.class), "writeObject", "(" + Type.getDescriptor(Object.class) + ")V"); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn( GETFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.TRAITSET_FIELD_NAME, Type.getDescriptor(Map.class)); mv.visitMethodInsn( INVOKEINTERFACE, Type.getInternalName(ObjectOutput.class), "writeObject", "(" + Type.getDescriptor(Object.class) + ")V"); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } { mv = cw.visitMethod( ACC_PUBLIC, "readExternal", "(" + Type.getDescriptor(ObjectInput.class) + ")V", null, new String[] { Type.getInternalName(IOException.class), Type.getInternalName(ClassNotFoundException.class) }); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn( INVOKEINTERFACE, Type.getInternalName(ObjectInput.class), "readObject", "()" + Type.getDescriptor(Object.class)); mv.visitTypeInsn(CHECKCAST, BuildUtils.getInternalType(coreName)); mv.visitFieldInsn( PUTFIELD, BuildUtils.getInternalType(wrapperName), "core", BuildUtils.getTypeDescriptor(coreName)); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn( INVOKEINTERFACE, Type.getInternalName(ObjectInput.class), "readObject", "()" + Type.getDescriptor(Object.class)); mv.visitTypeInsn(CHECKCAST, Type.getInternalName(Map.class)); mv.visitFieldInsn( PUTFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.MAP_FIELD_NAME, Type.getDescriptor(Map.class)); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn( INVOKEINTERFACE, Type.getInternalName(ObjectInput.class), "readObject", "()" + Type.getDescriptor(Object.class)); mv.visitTypeInsn(CHECKCAST, Type.getInternalName(Map.class)); mv.visitFieldInsn( PUTFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.TRAITSET_FIELD_NAME, Type.getDescriptor(Map.class)); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } { mv = cw.visitMethod( ACC_PUBLIC, "init", "(" + BuildUtils.getTypeDescriptor(coreName) + ")V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitFieldInsn( PUTFIELD, BuildUtils.getInternalType(wrapperName), "core", BuildUtils.getTypeDescriptor(coreName)); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } Method[] ms = coreKlazz.getMethods(); for (Method method : ms) { if (Modifier.isFinal(method.getModifiers())) { continue; } String signature = TraitFactory.buildSignature(method); { mv = cw.visitMethod(ACC_PUBLIC, method.getName(), signature, null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn( GETFIELD, BuildUtils.getInternalType(wrapperName), "core", BuildUtils.getTypeDescriptor(coreName)); int j = 1; for (Class arg : method.getParameterTypes()) { mv.visitVarInsn(BuildUtils.varType(arg.getName()), j++); } mv.visitMethodInsn( INVOKEVIRTUAL, BuildUtils.getInternalType(coreName), method.getName(), signature); mv.visitInsn(BuildUtils.returnType(method.getReturnType().getName())); int stack = TraitFactory.getStackSize(method); mv.visitMaxs(0, 0); mv.visitEnd(); } } { mv = cw.visitMethod( ACC_PUBLIC + ACC_BRIDGE + ACC_SYNTHETIC, "init", "(" + Type.getDescriptor(Object.class) + ")V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(CHECKCAST, BuildUtils.getInternalType(coreName)); mv.visitMethodInsn( INVOKEVIRTUAL, BuildUtils.getInternalType(wrapperName), "init", "(" + BuildUtils.getTypeDescriptor(coreName) + ")V"); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } { mv = cw.visitMethod( ACC_PUBLIC, "denyTrait", "(" + Type.getDescriptor(Class.class) + ")V", null, new String[] {Type.getInternalName(LogicalTypeInconsistencyException.class)}); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn( GETFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.TRAITSET_FIELD_NAME, Type.getDescriptor(Map.class)); mv.visitTypeInsn(CHECKCAST, Type.getInternalName(VetoableTypedMap.class)); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn( INVOKEVIRTUAL, Type.getInternalName(VetoableTypedMap.class), "addToVetoable", "(" + Type.getDescriptor(Class.class) + ")V"); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } { mv = cw.visitMethod( ACC_PUBLIC, "allowTrait", "(" + Type.getDescriptor(Class.class) + ")V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn( GETFIELD, BuildUtils.getInternalType(wrapperName), TraitableBean.TRAITSET_FIELD_NAME, Type.getDescriptor(Map.class)); mv.visitTypeInsn(CHECKCAST, Type.getInternalName(VetoableTypedMap.class)); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn( INVOKEVIRTUAL, Type.getInternalName(VetoableTypedMap.class), "removeFromVetoable", "(" + Type.getDescriptor(Class.class) + ")V"); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } cw.visitEnd(); return cw.toByteArray(); }
private void generateHibernateDAO(final Dao dao) throws Exception { final ClassWriter classWriter = new ClassWriter( this, getSrcGeneratedDirectory(), GeneratorHelper.getDAOPackage(domain), GeneratorHelper.getDAOClassName(domain)); classWriter.addExtend("com.ponysdk.hibernate.dao.HibernateDAO"); // Add static logger classWriter.addConstants( "private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(" + GeneratorHelper.getDAOClassName(domain) + ".class);"); // Create constructor final List<Parameter> parameters = new ArrayList<Parameter>(); final Parameter sessionFactoryParameter = new Parameter(); sessionFactoryParameter.setName("sessionFactory"); sessionFactoryParameter.setClazz("org.hibernate.SessionFactory"); parameters.add(sessionFactoryParameter); final Constructor constructor = new Constructor(parameters, parameters); classWriter.addConstructor(constructor); // Create findById method classWriter.addNewLine(); classWriter.addLine("final public " + dao.getClazz() + " findById(final long id) {"); classWriter.addLine(" if (log.isDebugEnabled()) {"); classWriter.addLine( " log.debug(\"getting " + domain.getName() + " instance with id: \" + id);"); classWriter.addLine(" }"); classWriter.addNewLine(); classWriter.addLine(" try {"); classWriter.addLine( " " + dao.getClazz() + " instance = (" + dao.getClazz() + ") sessionFactory.getCurrentSession().get(" + dao.getClazz() + ".class, id);"); classWriter.addLine(" return instance;"); classWriter.addLine(" } catch (final RuntimeException re) {"); classWriter.addLine(" log.error(\"getting " + domain.getName() + " by id failed\", re);"); classWriter.addLine(" throw re;"); classWriter.addLine(" }"); classWriter.addLine("}"); // Create findAll method classWriter.addNewLine(); classWriter.addLine("@SuppressWarnings(\"unchecked\")"); classWriter.addLine("public java.util.List<" + dao.getClazz() + "> findAll() {"); classWriter.addLine(" if (log.isDebugEnabled()) {"); classWriter.addLine( " log.debug(\"finding " + domain.getName() + " instance by example\");"); classWriter.addLine(" }"); classWriter.addNewLine(); classWriter.addLine(" try {"); classWriter.addLine( " final java.util.List<" + dao.getClazz() + "> results = sessionFactory.getCurrentSession().createQuery(\"FROM " + domain.getName() + "\").list();"); classWriter.addLine(" return results;"); classWriter.addLine(" } catch (final RuntimeException re) {"); classWriter.addLine(" log.error(\"finding all " + domain.getName() + " failed\", re);"); classWriter.addLine(" throw re;"); classWriter.addLine(" }"); classWriter.addLine("}"); classWriter.generateContentAndStore(); }