private ClassNode configureClass(Class c) { if (c.isPrimitive()) { return ClassHelper.make(c); } else { return ClassHelper.makeWithoutCaching(c, false); } }
private ClassNode configureTypeVariableReference(TypeVariable tv) { ClassNode cn = ClassHelper.makeWithoutCaching(tv.getName()); cn.setGenericsPlaceHolder(true); ClassNode cn2 = ClassHelper.makeWithoutCaching(tv.getName()); cn2.setGenericsPlaceHolder(true); GenericsType[] gts = new GenericsType[] {new GenericsType(cn2)}; cn.setGenericsTypes(gts); cn.setRedirect(ClassHelper.OBJECT_TYPE); return cn; }
/** * Visits a class literal. If the type of the classnode is a primitive type, the generated * bytecode will be a GETSTATIC Integer.TYPE. If the classnode is not a primitive type, we will * generate a LDC instruction. */ public static void visitClassLiteral(MethodVisitor mv, ClassNode classNode) { if (ClassHelper.isPrimitiveType(classNode)) { mv.visitFieldInsn( GETSTATIC, getClassInternalName(ClassHelper.getWrapper(classNode)), "TYPE", "Ljava/lang/Class;"); } else { mv.visitLdcInsn(org.objectweb.asm.Type.getType(getTypeDescription(classNode))); } }
public ClassNode box() { MethodVisitor mv = controller.getMethodVisitor(); int size = stack.size(); ClassNode type = stack.get(size - 1); if (ClassHelper.isPrimitiveType(type) && ClassHelper.VOID_TYPE != type) { ClassNode wrapper = ClassHelper.getWrapper(type); BytecodeHelper.doCastToWrappedType(mv, type, wrapper); type = wrapper; } // else nothing to box stack.set(size - 1, type); return type; }
private void doConvertAndCast(ClassNode targetType, boolean coerce) { int size = stack.size(); throwExceptionForNoStackElement(size, targetType, coerce); ClassNode top = stack.get(size - 1); targetType = targetType.redirect(); if (targetType == top) return; if (coerce) { controller.getInvocationWriter().coerce(top, targetType); return; } boolean primTarget = ClassHelper.isPrimitiveType(targetType); boolean primTop = ClassHelper.isPrimitiveType(top); if (primTop && primTarget) { // here we box and unbox to get the goal type if (convertPrimitive(top, targetType)) { replace(targetType); return; } box(); } else if (primTop) { // top is primitive, target is not // so box and do groovy cast controller.getInvocationWriter().castToNonPrimitiveIfNecessary(top, targetType); } else if (primTarget) { // top is not primitive so unbox // leave that BH#doCast later } else { controller.getInvocationWriter().castToNonPrimitiveIfNecessary(top, targetType); } MethodVisitor mv = controller.getMethodVisitor(); if (primTarget && !ClassHelper.boolean_TYPE.equals(targetType) && !primTop && ClassHelper.getWrapper(targetType).equals(top)) { BytecodeHelper.doCastToPrimitive(mv, top, targetType); } else { top = stack.get(size - 1); if (!WideningCategories.implementsInterfaceOrSubclassOf(top, targetType)) { BytecodeHelper.doCast(mv, targetType); } } replace(targetType); }
/** * Test create class registration. * * @throws AViewException */ @Ignore public void testCreateClassRegistration() throws AViewException { ClassRegistration clr = new ClassRegistration(); User user = UserHelper.getUser(554l); Class aviewClass = ClassHelper.getClass(14l); clr.setIsModerator("N"); clr.setAviewClass(aviewClass); clr.setUser(user); clr.setEnable2DSharing("Y"); clr.setEnable3DSharing("Y"); clr.setEnableAudioVideo("Y"); clr.setEnableDesktopSharing("Y"); clr.setEnableDocumentSharing("Y"); clr.setEnableVideoSharing("Y"); clr.setNodeTypeId(NodeTypeHelper.getClassroomNodeType()); ClassRegistrationHelper.createClassRegistration(clr, 44l, StatusHelper.getActiveStatusId()); List<ClassRegistration> clrLst = ClassRegistrationHelper.searchForClassRegister( user.getUserName(), user.getFname(), user.getLname(), aviewClass.getClassId(), clr.getIsModerator(), aviewClass.getCourseId(), null); assertEquals("Did not create CreateClassRegistration", 128l, clrLst.size()); }
private void setAnnotationMetaData(Annotation[] annotations, AnnotatedNode an) { for (Annotation annotation : annotations) { AnnotationNode node = new AnnotationNode(ClassHelper.make(annotation.annotationType())); configureAnnotation(node, annotation); an.addAnnotation(node); } }
@Override public Object[] getInstances(boolean create) { Object[] result = {}; if (m_xmlTest.isJUnit()) { if (create) { result = new Object[] { ClassHelper.createInstance( m_class, m_classes, m_xmlTest, m_annotationFinder, m_objectFactory) }; } } else { result = new Object[] {getDefaultInstance()}; } if (m_instances.size() > 0) { result = m_instances.toArray(new Object[m_instances.size()]); } m_instanceCount = m_instances.size(); m_instanceHashCodes = new long[m_instanceCount]; for (int i = 0; i < m_instanceCount; i++) { m_instanceHashCodes[i] = m_instances.get(i).hashCode(); } return result; }
/** * ensure last marked parameter on the stack is a primitive boolean if mark==stack size, we assume * an empty expression or statement. was used and we will use the value given in emptyDefault as * boolean if mark==stack.size()-1 the top element will be cast to boolean using Groovy truth. In * other cases we throw a GroovyBugError */ public void castToBool(int mark, boolean emptyDefault) { int size = stack.size(); MethodVisitor mv = controller.getMethodVisitor(); if (mark == size) { // no element, so use emptyDefault if (emptyDefault) { mv.visitIntInsn(BIPUSH, 1); } else { mv.visitIntInsn(BIPUSH, 0); } stack.add(null); } else if (mark == stack.size() - 1) { ClassNode last = stack.get(size - 1); // nothing to do in that case if (last == ClassHelper.boolean_TYPE) return; // not a primitive type, so call booleanUnbox if (!ClassHelper.isPrimitiveType(last)) { controller.getInvocationWriter().castNonPrimitiveToBool(last); } else { primitive2b(mv, last); } } else { throw new GroovyBugError( "operand stack contains " + stack.size() + " elements, but we expected only " + mark); } stack.set(mark, ClassHelper.boolean_TYPE); }
protected void injectMethodMissing(ClassNode classNode) { FieldNode methodMissingInterceptor = classNode.addField( "this$methodMissingInterceptor", Modifier.FINAL | Modifier.STATIC | Modifier.PRIVATE | ACC_SYNTHETIC, METHOD_MISSING_INTERCEPTOR_CLASS, ctor( METHOD_MISSING_INTERCEPTOR_CLASS, args(classx(classNode), domainHandlerInstance()))); classNode.addMethod( new MethodNode( "$static_methodMissing", Modifier.PUBLIC | Modifier.STATIC, ClassHelper.OBJECT_TYPE, params( param(ClassHelper.STRING_TYPE, "methodName"), param(ClassHelper.makeWithoutCaching(Object[].class), "arguments")), ClassNode.EMPTY_ARRAY, returns( call( field(methodMissingInterceptor), "handleMethodMissing", args(var("methodName"), var("arguments")))))); }
public List<Object> getByWhere(Class<?> clz, String where) { final Cursor cur = db.rawQuery(SqlGetter.getGetSql(clz, where), null); ArrayList<Object> list = new ArrayList<Object>(0); if (cur != null && cur.getCount() > 0) while (cur.moveToNext()) { try { final Object ins = Class.forName(clz.getName()).newInstance(); ClassHelper.callUsefullFields( ins.getClass(), new FieldCallback() { // id public void call(Field f) { setFieldValue(f, ins, cur.getString(cur.getColumnIndex(f.getName()))); } }, new FieldCallback() { // 普通 public void call(Field f) { setFieldValue(f, ins, cur.getString(cur.getColumnIndex(f.getName()))); } }); list.add(ins); } catch (Exception e) { } } closeCursor(cur); return list; }
private void printTypeName(PrintWriter out, ClassNode type) { if (ClassHelper.isPrimitiveType(type)) { if (type == ClassHelper.boolean_TYPE) { out.print("boolean"); } else if (type == ClassHelper.char_TYPE) { out.print("char"); } else if (type == ClassHelper.int_TYPE) { out.print("int"); } else if (type == ClassHelper.short_TYPE) { out.print("short"); } else if (type == ClassHelper.long_TYPE) { out.print("long"); } else if (type == ClassHelper.float_TYPE) { out.print("float"); } else if (type == ClassHelper.double_TYPE) { out.print("double"); } else if (type == ClassHelper.byte_TYPE) { out.print("byte"); } else { out.print("void"); } } else { String name = type.getName(); // check for an alias ClassNode alias = currentModule.getImportType(name); if (alias != null) name = alias.getName(); out.print(name.replace('$', '.')); } }
private void printGenericsBounds(PrintWriter out, ClassNode type, boolean skipName) { if (!skipName) printTypeName(out, type); if (!java5) return; if (!ClassHelper.isCachedType(type)) { printGenericsBounds(out, type.getGenericsTypes()); } }
private void printField(PrintWriter out, FieldNode fieldNode, boolean isInterface) { if ((fieldNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return; printAnnotations(out, fieldNode); if (!isInterface) { printModifiers(out, fieldNode.getModifiers()); } ClassNode type = fieldNode.getType(); printType(out, type); out.print(" "); out.print(fieldNode.getName()); if (isInterface || (fieldNode.getModifiers() & Opcodes.ACC_FINAL) != 0) { out.print(" = "); Expression valueExpr = fieldNode.getInitialValueExpression(); if (valueExpr instanceof ConstantExpression) { valueExpr = Verifier.transformToPrimitiveConstantIfPossible((ConstantExpression) valueExpr); } if (valueExpr instanceof ConstantExpression && fieldNode.isStatic() && fieldNode.isFinal() && ClassHelper.isStaticConstantInitializerType(valueExpr.getType()) && valueExpr.getType().equals(fieldNode.getType())) { // GROOVY-5150 : Initialize value with a dummy constant so that Java cross compiles // correctly if (ClassHelper.STRING_TYPE.equals(valueExpr.getType())) { out.print("\"" + escapeSpecialChars(valueExpr.getText()) + "\""); } else if (ClassHelper.char_TYPE.equals(valueExpr.getType())) { out.print("'" + valueExpr.getText() + "'"); } else { ClassNode constantType = valueExpr.getType(); out.print('('); printType(out, type); out.print(") "); out.print(valueExpr.getText()); if (ClassHelper.Long_TYPE.equals(ClassHelper.getWrapper(constantType))) out.print('L'); } } else if (ClassHelper.isPrimitiveType(type)) { String val = type == ClassHelper.boolean_TYPE ? "false" : "0"; out.print("new " + ClassHelper.getWrapper(type) + "((" + type + ")" + val + ")"); } else { out.print("null"); } } out.println(";"); }
private boolean isKnownImmutableClass(ClassNode fieldType, List<String> knownImmutableClasses) { if (!fieldType.isResolved()) return false; return fieldType.isEnum() || ClassHelper.isPrimitiveType(fieldType) || fieldType.getAnnotations(MY_TYPE).size() != 0 || inImmutableList(fieldType.getName()) || knownImmutableClasses.contains(fieldType.getName()); }
protected Parameter[] makeParameters(Class[] parameterTypes) { if (parameterTypes.length == 0) return Parameter.EMPTY_ARRAY; Parameter[] parameters = new Parameter[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { parameters[i] = new Parameter(ClassHelper.makeWithoutCaching(parameterTypes[i]), "arg" + i); } return parameters; }
public boolean save(Object obj) { Map<String, Object> map = ClassHelper.getFieldValueMap(obj, false); ContentValues cv = new ContentValues(); for (Map.Entry<String, Object> en : map.entrySet()) cv.put(en.getKey(), en.getValue().toString()); long c = db.insert(SqlGetter.getTableName(obj.getClass()), null, cv); return c > 0; }
private ClassNode configureWildcardType(WildcardType wildcardType) { ClassNode base = ClassHelper.makeWithoutCaching("?"); base.setRedirect(ClassHelper.OBJECT_TYPE); // TODO: more than one lower bound for wildcards? ClassNode[] lowers = configureTypes(wildcardType.getLowerBounds()); ClassNode lower = null; // TODO: is it safe to remove this? What was the original intention? if (lower != null) lower = lowers[0]; ClassNode[] upper = configureTypes(wildcardType.getUpperBounds()); GenericsType t = new GenericsType(base, upper, lower); t.setWildcard(true); ClassNode ref = ClassHelper.makeWithoutCaching(Object.class, false); ref.setGenericsTypes(new GenericsType[] {t}); return ref; }
public ClassNode getPlainNodeReference() { if (ClassHelper.isPrimitiveType(this)) return this; ClassNode n = new ClassNode(name, modifiers, superClass, null, null); n.isPrimaryNode = false; n.setRedirect(redirect()); if (isArray()) { n.componentType = redirect().getComponentType(); } return n; }
public boolean update(Object obj, String idValue) { String tableName = SqlGetter.getTableName(obj.getClass()); String idName = SqlGetter.getPrimaryKeyName(obj.getClass()); Map<String, Object> map = ClassHelper.getFieldValueMap(obj, false); ContentValues cv = new ContentValues(); for (Map.Entry<String, Object> en : map.entrySet()) cv.put(en.getKey(), en.getValue().toString()); int c = db.update(tableName, cv, idName + " = '" + idValue + "'", null); return c > 0; }
private void validateFields(BlockStatement block) { Validation.Option mode = getEnumMemberValue( getAnnotation(annotatedClass, VALIDATION_ANNOTATION), "option", Validation.Option.class, Validation.Option.IGNORE_UNMARKED); for (FieldNode fieldNode : annotatedClass.getFields()) { if (shouldFieldBeIgnoredForValidation(fieldNode)) continue; ClosureExpression validationClosure = createGroovyTruthClosureExpression(block.getVariableScope()); String message = null; AnnotationNode validateAnnotation = getAnnotation(fieldNode, VALIDATE_ANNOTATION); if (validateAnnotation != null) { message = getMemberStringValue( validateAnnotation, "message", "'" + fieldNode.getName() + "' must be set!"); Expression member = validateAnnotation.getMember("value"); if (member instanceof ClassExpression) { ClassNode memberType = member.getType(); if (memberType.equals(ClassHelper.make(Validate.Ignore.class))) continue; else if (!memberType.equals(ClassHelper.make(Validate.GroovyTruth.class))) { addError( "value of Validate must be either Validate.GroovyTruth, Validate.Ignore or a closure.", fieldNode); } } else if (member instanceof ClosureExpression) { validationClosure = (ClosureExpression) member; } } if (validateAnnotation != null || mode == Validation.Option.VALIDATE_UNMARKED) { block.addStatement( new AssertStatement( new BooleanExpression( callX(validationClosure, "call", args(varX(fieldNode.getName())))), message == null ? ConstantExpression.NULL : new ConstantExpression(message))); } } }
private ClassNode makeClassNode(CompileUnit cu, Type t, Class c) { ClassNode back = null; if (cu != null) back = cu.getClass(c.getName()); if (back == null) back = ClassHelper.make(c); if (!(t instanceof Class)) { ClassNode front = configureType(t); front.setRedirect(back); return front; } return back; }
/** load the constant on the operand stack. */ public void pushConstant(ConstantExpression expression) { MethodVisitor mv = controller.getMethodVisitor(); Object value = expression.getValue(); ClassNode origType = expression.getType().redirect(); ClassNode type = ClassHelper.getUnwrapper(origType); boolean boxing = origType != type; boolean asPrimitive = boxing || ClassHelper.isPrimitiveType(type); if (value == null) { mv.visitInsn(ACONST_NULL); } else if (boxing && value instanceof Boolean) { // special path for boxed boolean Boolean bool = (Boolean) value; String text = bool ? "TRUE" : "FALSE"; mv.visitFieldInsn(GETSTATIC, "java/lang/Boolean", text, "Ljava/lang/Boolean;"); boxing = false; type = origType; } else if (asPrimitive) { pushPrimitiveConstant(mv, value, type); } else if (value instanceof BigDecimal) { String className = BytecodeHelper.getClassInternalName(value.getClass().getName()); mv.visitTypeInsn(NEW, className); mv.visitInsn(DUP); mv.visitLdcInsn(value.toString()); mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", "(Ljava/lang/String;)V", false); } else if (value instanceof BigInteger) { String className = BytecodeHelper.getClassInternalName(value.getClass().getName()); mv.visitTypeInsn(NEW, className); mv.visitInsn(DUP); mv.visitLdcInsn(value.toString()); mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", "(Ljava/lang/String;)V", false); } else if (value instanceof String) { mv.visitLdcInsn(value); } else { throw new ClassGeneratorException( "Cannot generate bytecode for constant: " + value + " of type: " + type.getName()); } push(type); if (boxing) box(); }
public static void doCast(MethodVisitor mv, ClassNode type) { if (type == ClassHelper.OBJECT_TYPE) return; if (ClassHelper.isPrimitiveType(type) && type != ClassHelper.VOID_TYPE) { unbox(mv, type); } else { mv.visitTypeInsn( CHECKCAST, type.isArray() ? BytecodeHelper.getTypeDescription(type) : BytecodeHelper.getClassInternalName(type.getName())); } }
private static void writeGenericsBoundType( StringBuffer ret, ClassNode printType, boolean writeInterfaceMarker) { if (writeInterfaceMarker && printType.isInterface()) ret.append(":"); if (printType.equals(ClassHelper.OBJECT_TYPE) && printType.getGenericsTypes() != null) { ret.append("T"); ret.append(printType.getGenericsTypes()[0].getName()); ret.append(";"); } else { ret.append(getTypeDescription(printType, false)); addSubTypes(ret, printType.getGenericsTypes(), "<", ">"); if (!ClassHelper.isPrimitiveType(printType)) ret.append(";"); } }
/** * Test update class registration. * * @throws AViewException */ @Ignore public void testUpdateClassRegistration() throws AViewException { Integer nodeTypeId = 2; Long clrId = 522l; User user = UserHelper.getUser(591l); Class aviewClass = ClassHelper.getClass(77l); List<ClassRegistration> clrLst = ClassRegistrationHelper.searchForClassRegister( user.getUserName(), user.getFname(), user.getLname(), aviewClass.getClassId(), "Y", null, null); int i = 0; ClassRegistration clr = null; for (i = 0; i <= clrLst.size(); i++) { if (clrId.equals(clrLst.get(i).getClassRegisterId())) { clr = (ClassRegistration) (clrLst.get(i)); break; } } clr.setNodeTypeId(nodeTypeId); ClassRegistrationHelper.updateClassRegistration(clr, 44l); List<ClassRegistration> updatedClrLst = ClassRegistrationHelper.searchForClassRegister( user.getUserName(), user.getFname(), user.getLname(), aviewClass.getClassId(), "Y", null, null); int j = 0; ClassRegistration updatedClr = null; for (j = 0; j <= updatedClrLst.size(); j++) { if (clrId.equals(clrLst.get(i).getClassRegisterId())) { updatedClr = (ClassRegistration) (updatedClrLst.get(i)); break; } } assertEquals( "Did not Update CreateClassRegistration", updatedClr.getNodeTypeId(), clr.getNodeTypeId()); }
/** * Test delete class register. * * @throws AViewException */ @Ignore public void testDeleteClassRegister() throws AViewException { Long clrId = 2l; User user = UserHelper.getUser(594l); Class aviewClass = ClassHelper.getClass(58l); List<ClassRegistration> clrLst = ClassRegistrationHelper.searchForClassRegister( user.getUserName(), user.getFname(), user.getLname(), aviewClass.getClassId(), "Y", null, null); int i = 0; ClassRegistration clr = new ClassRegistration(); for (i = 0; i <= clrLst.size(); i++) { if (clrId.equals(clrLst.get(i).getClassRegisterId())) { clr = (ClassRegistration) (clrLst.get(i)); break; } } assertTrue( "User must be active first", (clr.getStatusId() == StatusHelper.getActiveStatusId())); UserHelper.deleteUser(clrId, 44l); List<ClassRegistration> updatedClrLst = ClassRegistrationHelper.searchForClassRegister( user.getUserName(), user.getFname(), user.getLname(), aviewClass.getClassId(), "Y", null, null); int j = 0; ClassRegistration updatedClr = new ClassRegistration(); for (j = 0; j <= updatedClrLst.size(); j++) { if (clrId.equals(clrLst.get(i).getClassRegisterId())) { updatedClr = (ClassRegistration) (updatedClrLst.get(i)); break; } } assertTrue( "User is not deleted", (updatedClr.getStatusId() == StatusHelper.getDeletedStatusId())); }
private void printDefaultValue(PrintWriter out, ClassNode type) { if (type.redirect() != ClassHelper.OBJECT_TYPE && type.redirect() != ClassHelper.boolean_TYPE) { out.print("("); printType(out, type); out.print(")"); } if (ClassHelper.isPrimitiveType(type)) { if (type == ClassHelper.boolean_TYPE) { out.print("false"); } else { out.print("0"); } } else { out.print("null"); } }
/** * array types are special: eg.: String[]: classname: [Ljava/lang/String; int[]: [I * * @return the ASM type description */ private static String getTypeDescription(ClassNode c, boolean end) { StringBuffer buf = new StringBuffer(); ClassNode d = c; while (true) { if (ClassHelper.isPrimitiveType(d)) { char car; if (d == ClassHelper.int_TYPE) { car = 'I'; } else if (d == ClassHelper.VOID_TYPE) { car = 'V'; } else if (d == ClassHelper.boolean_TYPE) { car = 'Z'; } else if (d == ClassHelper.byte_TYPE) { car = 'B'; } else if (d == ClassHelper.char_TYPE) { car = 'C'; } else if (d == ClassHelper.short_TYPE) { car = 'S'; } else if (d == ClassHelper.double_TYPE) { car = 'D'; } else if (d == ClassHelper.float_TYPE) { car = 'F'; } else /* long */ { car = 'J'; } buf.append(car); return buf.toString(); } else if (d.isArray()) { buf.append('['); d = d.getComponentType(); } else { buf.append('L'); String name = d.getName(); int len = name.length(); for (int i = 0; i < len; ++i) { char car = name.charAt(i); buf.append(car == '.' ? '/' : car); } if (end) buf.append(';'); return buf.toString(); } } }
protected void injectMethod(ClassNode classNode, MethodSignature methodSignature) { Parameter[] parameters = makeParameters(methodSignature.getParameterTypes()); int modifiers = Modifier.PUBLIC; if (methodSignature.isStatic()) modifiers |= Modifier.STATIC; String returnTypeClassName = methodSignature.getReturnType().getName(); ClassNode returnType = GRIFFON_DOMAIN_CLASSNAME.equals(returnTypeClassName) ? classNode : ClassHelper.makeWithoutCaching(methodSignature.getReturnType()); classNode.addMethod( new MethodNode( methodSignature.getMethodName(), modifiers, returnType, parameters, ClassNode.EMPTY_ARRAY, makeMethodBody(classNode, methodSignature, parameters))); }