Exemplo n.º 1
0
    protected void addTimeStamp(ClassNode node) {
      if (node.getDeclaredField(Verifier.__TIMESTAMP)
          == null) { // in case if verifier visited the call already
        FieldNode timeTagField =
            new FieldNode(
                Verifier.__TIMESTAMP,
                ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC,
                ClassHelper.long_TYPE,
                // "",
                node,
                new ConstantExpression(System.currentTimeMillis()));
        // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final
        // long __timeStamp = " + System.currentTimeMillis() + "L");
        timeTagField.setSynthetic(true);
        node.addField(timeTagField);

        timeTagField =
            new FieldNode(
                Verifier.__TIMESTAMP__ + String.valueOf(System.currentTimeMillis()),
                ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC,
                ClassHelper.long_TYPE,
                // "",
                node,
                new ConstantExpression((long) 0));
        // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final
        // long __timeStamp = " + System.currentTimeMillis() + "L");
        timeTagField.setSynthetic(true);
        node.addField(timeTagField);
      }
    }
  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"))))));
  }
Exemplo n.º 3
0
 public void addProperty(PropertyNode node) {
   node.setDeclaringClass(redirect());
   FieldNode field = node.getField();
   addField(field);
   final ClassNode r = redirect();
   if (r.properties == null) r.properties = new ArrayList<PropertyNode>();
   r.properties.add(node);
 }
Exemplo n.º 4
0
 public static void addFieldIfNonExistent(
     ClassNode classNode, ClassNode fieldType, String fieldName) {
   if (classNode != null && classNode.getField(fieldName) == null) {
     classNode.addField(
         fieldName,
         Modifier.PRIVATE,
         fieldType,
         new ConstructorCallExpression(fieldType, new ArgumentListExpression()));
   }
 }
 protected void addErrorsField(final ClassNode paramTypeClassNode) {
   final ASTNode errorsField = paramTypeClassNode.getField(ERRORS_PROPERTY_NAME);
   if (errorsField == null) {
     paramTypeClassNode.addField(
         new FieldNode(
             ERRORS_PROPERTY_NAME,
             Modifier.PRIVATE,
             ERRORS_CLASS_NODE,
             paramTypeClassNode,
             NULL_EXPRESSION));
   }
 }
  @Test
  public void transformationOfAnnotationOnField() {
    ClassNode classNode = new ClassNode("Test", 0, new ClassNode(Object.class));
    this.moduleNode.addClass(classNode);

    FieldNode fieldNode = new FieldNode("test", 0, new ClassNode(Object.class), classNode, null);
    classNode.addField(fieldNode);

    fieldNode.addAnnotation(this.grabAnnotation);

    assertGrabAnnotationHasBeenTransformed();
  }
 private void addProperty(ClassNode cNode, PropertyNode pNode) {
   final FieldNode fn = pNode.getField();
   cNode.getFields().remove(fn);
   cNode.addProperty(
       pNode.getName(),
       pNode.getModifiers() | ACC_FINAL,
       pNode.getType(),
       pNode.getInitialExpression(),
       pNode.getGetterBlock(),
       pNode.getSetterBlock());
   final FieldNode newfn = cNode.getField(fn.getName());
   cNode.getFields().remove(newfn);
   cNode.addField(fn);
 }
 private List<FieldNode> convertParamsToFields(ClassNode builder, Parameter[] parameters) {
   List<FieldNode> fieldNodes = new ArrayList<FieldNode>();
   for (Parameter parameter : parameters) {
     Map<String, ClassNode> genericsSpec = createGenericsSpec(builder);
     ClassNode correctedType = correctToGenericsSpecRecurse(genericsSpec, parameter.getType());
     FieldNode fieldNode =
         new FieldNode(
             parameter.getName(),
             parameter.getModifiers(),
             correctedType,
             builder,
             DEFAULT_INITIAL_VALUE);
     fieldNodes.add(fieldNode);
     builder.addField(fieldNode);
   }
   return fieldNodes;
 }
Exemplo n.º 9
0
 public void buildClass(
     BuilderASTTransformation transform, ClassNode buildee, AnnotationNode anno) {
   List<String> excludes = new ArrayList<String>();
   List<String> includes = new ArrayList<String>();
   if (!getIncludeExclude(transform, anno, buildee, excludes, includes)) return;
   ClassNode builder = createBuilder(anno, buildee);
   createBuilderFactoryMethod(anno, buildee, builder);
   List<FieldNode> fields = getInstancePropertyFields(buildee);
   List<FieldNode> filteredFields = selectFieldsFromExistingClass(fields, includes, excludes);
   for (FieldNode fieldNode : filteredFields) {
     ClassNode correctedType = getCorrectedType(buildee, fieldNode);
     String fieldName = fieldNode.getName();
     builder.addField(createFieldCopy(buildee, fieldName, correctedType));
     builder.addMethod(
         createBuilderMethodForProp(
             builder, new PropertyInfo(fieldName, correctedType), getPrefix(anno)));
   }
   builder.addMethod(createBuildMethod(anno, buildee, filteredFields));
 }
Exemplo n.º 10
0
  private void createValidateMethod() {
    Validation.Mode mode =
        getEnumMemberValue(
            getAnnotation(annotatedClass, VALIDATION_ANNOTATION),
            "mode",
            Validation.Mode.class,
            Validation.Mode.AUTOMATIC);

    annotatedClass.addField(
        "$manualValidation",
        ACC_PRIVATE,
        ClassHelper.Boolean_TYPE,
        new ConstantExpression(mode == Validation.Mode.MANUAL));
    MethodBuilder.createPublicMethod("manualValidation")
        .param(Boolean_TYPE, "validation")
        .assignS(varX("$manualValidation"), varX("validation"))
        .addTo(annotatedClass);

    MethodBuilder methodBuilder = MethodBuilder.createPublicMethod(VALIDATE_METHOD);

    if (ASTHelper.isDSLObject(annotatedClass.getSuperClass())) {
      methodBuilder.statement(callSuperX(VALIDATE_METHOD));
    }

    BlockStatement block = new BlockStatement();
    validateFields(block);
    validateCustomMethods(block);

    TryCatchStatement tryCatchStatement = new TryCatchStatement(block, EmptyStatement.INSTANCE);
    tryCatchStatement.addCatch(
        new CatchStatement(
            param(ASSERTION_ERROR_TYPE, "e"),
            new ThrowStatement(
                ctorX(VALIDATION_EXCEPTION_TYPE, args(propX(varX("e"), "message"), varX("e"))))));
    tryCatchStatement.addCatch(
        new CatchStatement(
            param(EXCEPTION_TYPE, "e"),
            new ThrowStatement(
                ctorX(VALIDATION_EXCEPTION_TYPE, args(propX(varX("e"), "message"), varX("e"))))));

    methodBuilder.statement(tryCatchStatement).addTo(annotatedClass);
  }
Exemplo n.º 11
0
  public void configureClassNode(CompileUnit compileUnit, ClassNode classNode) {
    Class clazz = classNode.getTypeClass();
    Field[] fields = clazz.getDeclaredFields();
    for (Field f : fields) {
      ClassNode ret = makeClassNode(compileUnit, f.getGenericType(), f.getType());
      classNode.addField(f.getName(), f.getModifiers(), ret, null);
    }
    Method[] methods = clazz.getDeclaredMethods();
    for (Method m : methods) {
      ClassNode ret = makeClassNode(compileUnit, m.getGenericReturnType(), m.getReturnType());
      Parameter[] params =
          makeParameters(compileUnit, m.getGenericParameterTypes(), m.getParameterTypes());
      ClassNode[] exceptions =
          makeClassNodes(compileUnit, m.getGenericExceptionTypes(), m.getExceptionTypes());
      MethodNode mn = new MethodNode(m.getName(), m.getModifiers(), ret, params, exceptions, null);
      setMethodDefaultValue(mn, m);
      setAnnotationMetaData(m.getAnnotations(), mn);
      mn.setGenericsTypes(configureTypeVariable(m.getTypeParameters()));
      classNode.addMethod(mn);
    }
    Constructor[] constructors = clazz.getDeclaredConstructors();
    for (Constructor ctor : constructors) {
      Parameter[] params =
          makeParameters(compileUnit, ctor.getGenericParameterTypes(), ctor.getParameterTypes());
      ClassNode[] exceptions =
          makeClassNodes(compileUnit, ctor.getGenericExceptionTypes(), ctor.getExceptionTypes());
      classNode.addConstructor(ctor.getModifiers(), params, exceptions, null);
    }

    Class sc = clazz.getSuperclass();
    if (sc != null)
      classNode.setUnresolvedSuperClass(
          makeClassNode(compileUnit, clazz.getGenericSuperclass(), sc));
    makeInterfaceTypes(compileUnit, classNode, clazz);
    setAnnotationMetaData(classNode.getTypeClass().getAnnotations(), classNode);

    PackageNode packageNode = classNode.getPackage();
    if (packageNode != null) {
      setAnnotationMetaData(classNode.getTypeClass().getPackage().getAnnotations(), packageNode);
    }
  }
Exemplo n.º 12
0
 public void buildMethod(
     BuilderASTTransformation transform, MethodNode mNode, AnnotationNode anno) {
   if (transform.getMemberValue(anno, "includes") != null
       || transform.getMemberValue(anno, "includes") != null) {
     transform.addError(
         "Error during "
             + BuilderASTTransformation.MY_TYPE_NAME
             + " processing: includes/excludes only allowed on classes",
         anno);
   }
   ClassNode buildee = mNode.getDeclaringClass();
   ClassNode builder = createBuilder(anno, buildee);
   createBuilderFactoryMethod(anno, buildee, builder);
   for (Parameter parameter : mNode.getParameters()) {
     builder.addField(createFieldCopy(buildee, parameter));
     builder.addMethod(
         createBuilderMethodForProp(
             builder,
             new PropertyInfo(parameter.getName(), parameter.getType()),
             getPrefix(anno)));
   }
   builder.addMethod(createBuildMethodForMethod(anno, buildee, mNode, mNode.getParameters()));
 }
  private void addDefaultDatabindingWhitelistField(
      final SourceUnit sourceUnit, final ClassNode classNode) {
    final FieldNode defaultWhitelistField =
        classNode.getDeclaredField(DEFAULT_DATABINDING_WHITELIST);
    if (defaultWhitelistField == null) {
      final Set<String> propertyNamesToIncludeInWhiteList =
          getPropertyNamesToIncludeInWhiteList(sourceUnit, classNode);

      final ListExpression listExpression = new ListExpression();
      for (String propertyName : propertyNamesToIncludeInWhiteList) {
        listExpression.addExpression(new ConstantExpression(propertyName));

        final FieldNode declaredField = classNode.getDeclaredField(propertyName);
        if (declaredField != null) {
          final ClassNode type = declaredField.getType();
          if (type != null && !SIMPLE_TYPES.contains(type)) {
            if (STRUCTURED_EDITOR_TYPES.contains(type)) {
              listExpression.addExpression(new ConstantExpression(propertyName + "_*"));
            } else {
              String packageName = type.getPackageName();
              if (packageName != null && packageName.startsWith(JODATIME_PACKAGE)) {
                listExpression.addExpression(new ConstantExpression(propertyName + "_*"));
              } else {
                listExpression.addExpression(new ConstantExpression(propertyName + ".*"));
              }
            }
          }
        }
      }

      classNode.addField(
          DEFAULT_DATABINDING_WHITELIST,
          Modifier.STATIC | Modifier.PUBLIC | Modifier.FINAL,
          new ClassNode(List.class),
          listExpression);
    }
  }
Exemplo n.º 14
0
 public void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
   ClassNode classNode = (ClassNode) nodes[1];
   classNode.addField(new FieldNode("f3", ACC_PUBLIC, ClassHelper.OBJECT_TYPE, classNode, null));
 }
Exemplo n.º 15
0
 public FieldNode addField(String name, int modifiers, ClassNode type, Expression initialValue) {
   FieldNode node = new FieldNode(name, modifiers, type, redirect(), initialValue);
   addField(node);
   return node;
 }
Exemplo n.º 16
0
  protected MethodNode addClassUnderTestMethod(
      ClassNode classNode, ClassExpression targetClass, String type) {

    String methodName = "setup" + type + "UnderTest";
    String fieldName = GrailsNameUtils.getPropertyName(type);
    String getterName = GrailsNameUtils.getGetterName(fieldName);
    fieldName = '$' + fieldName;

    if (classNode.getField(fieldName) == null) {
      classNode.addField(fieldName, Modifier.PRIVATE, targetClass.getType(), null);
    }

    MethodNode methodNode =
        classNode.getMethod(methodName, GrailsArtefactClassInjector.ZERO_PARAMETERS);

    VariableExpression fieldExpression = new VariableExpression(fieldName);
    if (methodNode == null) {
      BlockStatement setupMethodBody = new BlockStatement();
      addMockCollaborator(type, targetClass, setupMethodBody);

      methodNode =
          new MethodNode(
              methodName,
              Modifier.PUBLIC,
              ClassHelper.VOID_TYPE,
              GrailsArtefactClassInjector.ZERO_PARAMETERS,
              null,
              setupMethodBody);
      methodNode.addAnnotation(BEFORE_ANNOTATION);
      methodNode.addAnnotation(MIXIN_METHOD_ANNOTATION);
      classNode.addMethod(methodNode);
    }

    MethodNode getter =
        classNode.getMethod(getterName, GrailsArtefactClassInjector.ZERO_PARAMETERS);
    if (getter == null) {
      BlockStatement getterBody = new BlockStatement();
      getter =
          new MethodNode(
              getterName,
              Modifier.PUBLIC,
              targetClass.getType().getPlainNodeReference(),
              GrailsArtefactClassInjector.ZERO_PARAMETERS,
              null,
              getterBody);

      BinaryExpression testTargetAssignment =
          new BinaryExpression(
              fieldExpression,
              ASSIGN,
              new ConstructorCallExpression(
                  targetClass.getType(), GrailsArtefactClassInjector.ZERO_ARGS));

      IfStatement autowiringIfStatement =
          getAutowiringIfStatement(targetClass, fieldExpression, testTargetAssignment);
      getterBody.addStatement(autowiringIfStatement);

      getterBody.addStatement(new ReturnStatement(fieldExpression));
      classNode.addMethod(getter);
    }

    return methodNode;
  }
Exemplo n.º 17
0
  public void configureClassNode(CompileUnit compileUnit, ClassNode classNode) {
    try {
      Class clazz = classNode.getTypeClass();
      Field[] fields = clazz.getDeclaredFields();
      for (Field f : fields) {
        ClassNode ret = makeClassNode(compileUnit, f.getGenericType(), f.getType());
        FieldNode fn = new FieldNode(f.getName(), f.getModifiers(), ret, classNode, null);
        setAnnotationMetaData(f.getAnnotations(), fn);
        classNode.addField(fn);
      }
      Method[] methods = clazz.getDeclaredMethods();
      for (Method m : methods) {
        ClassNode ret = makeClassNode(compileUnit, m.getGenericReturnType(), m.getReturnType());
        Parameter[] params =
            makeParameters(
                compileUnit,
                m.getGenericParameterTypes(),
                m.getParameterTypes(),
                m.getParameterAnnotations());
        ClassNode[] exceptions =
            makeClassNodes(compileUnit, m.getGenericExceptionTypes(), m.getExceptionTypes());
        MethodNode mn =
            new MethodNode(m.getName(), m.getModifiers(), ret, params, exceptions, null);
        mn.setSynthetic(m.isSynthetic());
        setMethodDefaultValue(mn, m);
        setAnnotationMetaData(m.getAnnotations(), mn);
        mn.setGenericsTypes(configureTypeVariable(m.getTypeParameters()));
        classNode.addMethod(mn);
      }
      Constructor[] constructors = clazz.getDeclaredConstructors();
      for (Constructor ctor : constructors) {
        Parameter[] params =
            makeParameters(
                compileUnit,
                ctor.getGenericParameterTypes(),
                ctor.getParameterTypes(),
                ctor.getParameterAnnotations());
        ClassNode[] exceptions =
            makeClassNodes(compileUnit, ctor.getGenericExceptionTypes(), ctor.getExceptionTypes());
        classNode.addConstructor(ctor.getModifiers(), params, exceptions, null);
      }

      Class sc = clazz.getSuperclass();
      if (sc != null)
        classNode.setUnresolvedSuperClass(
            makeClassNode(compileUnit, clazz.getGenericSuperclass(), sc));
      makeInterfaceTypes(compileUnit, classNode, clazz);
      setAnnotationMetaData(classNode.getTypeClass().getAnnotations(), classNode);

      PackageNode packageNode = classNode.getPackage();
      if (packageNode != null) {
        setAnnotationMetaData(classNode.getTypeClass().getPackage().getAnnotations(), packageNode);
      }
    } catch (NoClassDefFoundError e) {
      throw new NoClassDefFoundError(
          "Unable to load class "
              + classNode.toString(false)
              + " due to missing dependency "
              + e.getMessage());
    } catch (MalformedParameterizedTypeException e) {
      throw new RuntimeException(
          "Unable to configure class node for class "
              + classNode.toString(false)
              + " due to malformed parameterized types",
          e);
    }
  }
Exemplo n.º 18
0
 private void addFields(ClassNode buildee, List<FieldNode> filteredFields, ClassNode builder) {
   for (FieldNode filteredField : filteredFields) {
     builder.addField(createFieldCopy(buildee, filteredField));
   }
 }
  public static void apply(ClassNode declaringClass) {
    injectInterface(declaringClass, MYBATIS_CONTRIBUTION_HANDLER_CNODE);

    // add field:
    // protected MybatisProvider this$MybatisProvider = DefaultMybatisProvider.instance
    FieldNode providerField =
        declaringClass.addField(
            MYBATIS_PROVIDER_FIELD_NAME,
            ACC_PRIVATE | ACC_SYNTHETIC,
            MYBATIS_PROVIDER_CNODE,
            defaultMybatisProviderInstance());

    // add method:
    // MybatisProvider getMybatisProvider() {
    //     return this$MybatisProvider
    // }
    injectMethod(
        declaringClass,
        new MethodNode(
            METHOD_GET_MYBATIS_PROVIDER,
            ACC_PUBLIC,
            MYBATIS_PROVIDER_CNODE,
            Parameter.EMPTY_ARRAY,
            NO_EXCEPTIONS,
            returns(field(providerField))));

    // add method:
    // void setMybatisProvider(MybatisProvider provider) {
    //     this$MybatisProvider = provider ?: DefaultMybatisProvider.instance
    // }
    injectMethod(
        declaringClass,
        new MethodNode(
            METHOD_SET_MYBATIS_PROVIDER,
            ACC_PUBLIC,
            ClassHelper.VOID_TYPE,
            params(param(MYBATIS_PROVIDER_CNODE, PROVIDER)),
            NO_EXCEPTIONS,
            block(
                ifs_no_return(
                    cmp(var(PROVIDER), ConstantExpression.NULL),
                    assigns(field(providerField), defaultMybatisProviderInstance()),
                    assigns(field(providerField), var(PROVIDER))))));

    for (MethodNode method : MYBATIS_CONTRIBUTION_HANDLER_CNODE.getMethods()) {
      if (Arrays.binarySearch(DELEGATING_METHODS, method.getName()) < 0) continue;
      List<Expression> variables = new ArrayList<Expression>();
      Parameter[] parameters = new Parameter[method.getParameters().length];
      for (int i = 0; i < method.getParameters().length; i++) {
        Parameter p = method.getParameters()[i];
        parameters[i] = new Parameter(makeClassSafe(p.getType()), p.getName());
        parameters[i].getType().setGenericsTypes(p.getType().getGenericsTypes());
        variables.add(var(p.getName()));
      }
      ClassNode returnType = makeClassSafe(method.getReturnType());
      returnType.setGenericsTypes(method.getReturnType().getGenericsTypes());
      returnType.setGenericsPlaceHolder(method.getReturnType().isGenericsPlaceHolder());

      MethodNode newMethod =
          new MethodNode(
              method.getName(),
              ACC_PUBLIC,
              returnType,
              parameters,
              NO_EXCEPTIONS,
              returns(call(field(providerField), method.getName(), args(variables))));
      newMethod.setGenericsTypes(method.getGenericsTypes());
      injectMethod(declaringClass, newMethod);
    }
  }
Exemplo n.º 20
0
 protected void setUp() throws Exception {
   classNode.addField("field", ACC_PUBLIC, ClassHelper.STRING_TYPE, null);
 }