Ejemplo n.º 1
0
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   // System.out.println("supported options: "+
   // Arrays.toString(getSupportedOptions().toArray()));
   if (!roundEnv.processingOver()) {
     for (TypeElement currAnno : annotations) {
       // System.out.println("Found " + currAnno.getQualifiedName());
       if (currAnno.getQualifiedName().contentEquals(GENERATE_POJO_BUILDER_CLASS.getName())) {
         Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(currAnno);
         // System.out.println("[GenerateBuilder] annotatedElements="+
         // Arrays.toString(annotatedElements.toArray()));
         for (Element elem : annotatedElements) {
           if (elem.getKind() == ElementKind.CLASS) {
             TypeElement typeElem = (TypeElement) elem;
             GeneratePojoBuilder annotation = typeElem.getAnnotation(GENERATE_POJO_BUILDER_CLASS);
             generatePojoBuilderProcessor.process(typeElem, annotation);
           } else if (elem.getKind() == ElementKind.METHOD) {
             ExecutableElement execElem = (ExecutableElement) elem;
             GeneratePojoBuilder annotation = execElem.getAnnotation(GENERATE_POJO_BUILDER_CLASS);
             generatePojoBuilderProcessor.process(execElem, annotation);
           }
         }
       }
     }
   }
   return false;
 }
Ejemplo n.º 2
0
 private void filterClass(
     Collection<TypeElement> rootElements, Collection<? extends Element> elements) {
   for (Element element : elements) {
     if (element.getKind().equals(ElementKind.CLASS)
         || element.getKind().equals(ElementKind.INTERFACE)) {
       rootElements.add((TypeElement) element);
       filterClass(rootElements, ElementFilter.typesIn(element.getEnclosedElements()));
     }
   }
 }
Ejemplo n.º 3
0
 default Result checkSignature(Element elem) {
   if (elem.getKind() != ElementKind.INTERFACE) {
     String err =
         "A signature template must be an interface, but an element annotated with "
             + "`@Signature` has TypeKind {0}.";
     err = format(err, elem.getKind());
     return error(err, AllSignatureChecks.class, elem);
   }
   return checkSignature((TypeElement) elem);
 }
Ejemplo n.º 4
0
 @Override
 public VisitorConfig getConfig(TypeElement e, List<? extends Element> elements) {
   boolean fields = false, methods = false;
   for (Element element : elements) {
     if (hasRelevantAnnotation(element)) {
       fields |= element.getKind().equals(ElementKind.FIELD);
       methods |= element.getKind().equals(ElementKind.METHOD);
     }
   }
   return VisitorConfig.get(fields, methods);
 }
Ejemplo n.º 5
0
 @Override
 public String shorten(TypeElement type) {
   Element parent = type.getEnclosingElement();
   if (parent.getKind() == ElementKind.PACKAGE) {
     return getPrefixForTopLevelClass(parent.toString(), type.getSimpleName())
         + type.getSimpleName();
   } else if (parent.getKind().isInterface() || parent.getKind().isClass()) {
     return shorten((TypeElement) parent) + "." + type.getSimpleName();
   } else {
     return type.getQualifiedName().toString();
   }
 }
 private boolean isNested(Element returnType, VariableElement field, TypeElement element) {
   if (hasAnnotation(field, nestedConfigurationPropertyAnnotation())) {
     return true;
   }
   return this.typeUtils.isEnclosedIn(returnType, element)
       && returnType.getKind() != ElementKind.ENUM;
 }
Ejemplo n.º 7
0
  /**
   * Returns true if and only if a component can instantiate new instances (typically of a module)
   * rather than requiring that they be passed.
   */
  static boolean componentCanMakeNewInstances(TypeElement typeElement) {
    switch (typeElement.getKind()) {
      case CLASS:
        break;
      case ENUM:
      case ANNOTATION_TYPE:
      case INTERFACE:
        return false;
      default:
        throw new AssertionError("TypeElement cannot have kind: " + typeElement.getKind());
    }

    if (typeElement.getModifiers().contains(ABSTRACT)) {
      return false;
    }

    if (requiresEnclosingInstance(typeElement)) {
      return false;
    }

    for (Element enclosed : typeElement.getEnclosedElements()) {
      if (enclosed.getKind().equals(CONSTRUCTOR)
          && ((ExecutableElement) enclosed).getParameters().isEmpty()
          && !enclosed.getModifiers().contains(PRIVATE)) {
        return true;
      }
    }

    // TODO(gak): still need checks for visibility

    return false;
  }
  private static List<? extends TypeMirror> computeReturn(
      Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ReturnTree rt = (ReturnTree) parent.getLeaf();

    if (rt.getExpression() == error) {
      TreePath method = findMethod(parent);

      if (method == null) {
        return null;
      }

      Element el = info.getTrees().getElement(method);

      if (el == null || el.getKind() != ElementKind.METHOD) {
        return null;
      }

      types.add(ElementKind.PARAMETER);
      types.add(ElementKind.LOCAL_VARIABLE);
      types.add(ElementKind.FIELD);

      return Collections.singletonList(((ExecutableElement) el).getReturnType());
    }

    return null;
  }
  private void handleEmbeddedType(Element element, Set<TypeElement> elements) {
    TypeMirror type = element.asType();
    if (element.getKind() == ElementKind.METHOD) {
      type = ((ExecutableElement) element).getReturnType();
    }
    String typeName = type.toString();

    if (typeName.startsWith(Collection.class.getName())
        || typeName.startsWith(List.class.getName())
        || typeName.startsWith(Set.class.getName())) {
      type = ((DeclaredType) type).getTypeArguments().get(0);

    } else if (typeName.startsWith(Map.class.getName())) {
      type = ((DeclaredType) type).getTypeArguments().get(1);
    }

    TypeElement typeElement = typeExtractor.visit(type);

    if (typeElement != null
        && !TypeUtils.hasAnnotationOfType(typeElement, conf.getEntityAnnotations())) {
      if (!typeElement.getQualifiedName().toString().startsWith("java.")) {
        elements.add(typeElement);
      }
    }
  }
Ejemplo n.º 10
0
  private void createConstructorAndBuilder() {
    List<ExecutableElement> constructors = new ArrayList<ExecutableElement>();
    for (Element e : annotatedElement.getEnclosedElements()) {
      if (e.getKind() == CONSTRUCTOR) {
        constructors.add((ExecutableElement) e);
      }
    }

    for (ExecutableElement userConstructor : constructors) {
      JMethod copyConstructor = generatedClass.constructor(PUBLIC);
      JMethod staticHelper =
          generatedClass.method(PUBLIC | STATIC, generatedClass._extends(), "build");

      codeModelHelper.generifyStaticHelper(this, staticHelper, getAnnotatedElement());

      JBlock body = copyConstructor.body();
      JInvocation superCall = body.invoke("super");
      JInvocation newInvocation = JExpr._new(generatedClass);
      for (VariableElement param : userConstructor.getParameters()) {
        String paramName = param.getSimpleName().toString();
        JClass paramType = codeModelHelper.typeMirrorToJClass(param.asType(), this);
        copyConstructor.param(paramType, paramName);
        staticHelper.param(paramType, paramName);
        superCall.arg(JExpr.ref(paramName));
        newInvocation.arg(JExpr.ref(paramName));
      }

      JVar newCall = staticHelper.body().decl(generatedClass, "instance", newInvocation);
      staticHelper.body().invoke(newCall, getOnFinishInflate());
      staticHelper.body()._return(newCall);
      body.invoke(getInit());
    }
  }
Ejemplo n.º 11
0
  private ExecutableElement[] findGetterAndSetter(TypeElement cls, VariableElement variable) {
    ExecutableElement[] gs = new ExecutableElement[] {null, null};

    List<? extends Element> enclosedElements = cls.getEnclosedElements();
    String capitalizedVarName = StringUtils.startUpperCase(variable.getSimpleName().toString());
    String getterName = String.format("get%s", capitalizedVarName);
    String setterName = String.format("set%s", capitalizedVarName);

    for (int i = 0, c = enclosedElements.size(); i < c; i++) {
      Element e = enclosedElements.get(i);
      if (e.getKind() == ElementKind.METHOD) {
        if (getterName.equals(e.getSimpleName().toString())) {
          gs[0] = (ExecutableElement) e;
        } else if (setterName.equals(e.getSimpleName().toString())) {
          gs[1] = (ExecutableElement) e;
        } else {
          continue;
        }

        if (gs[0] != null && gs[1] != null) {
          break;
        }
      }
    }

    return gs;
  }
  private <A extends Annotation> ActionModel processAction(
      int genericPosition, Element element, Element outputElement, Class<A> annotationClass) {
    A annotation = element.getAnnotation(annotationClass);
    if (annotation != null) {
      System.out.println("Element: " + element.getSimpleName());
      if (elementTools.isMethod(element)) {
        TypeMirror outputGeneric =
            ((DeclaredType) outputElement.asType()).getTypeArguments().get(genericPosition);
        List<? extends VariableElement> parameters = ((ExecutableElement) element).getParameters();
        if (parameters.size() == 1
            && processingEnv.getTypeUtils().isSameType(parameters.get(0).asType(), outputGeneric)) {
          ActionModel actionModel = new ActionModel();
          actionModel.setMethodName(elementTools.getFieldName(element));
          actionModel.setType(element.asType());
          if (element.getKind() == ElementKind.METHOD) {
            actionModel.setType(((ExecutableElement) element).getParameters().get(0).asType());
          }

          System.out.println("It maches!!!" + actionModel);
          return actionModel;
        } else {
          System.out.println("Does not match");
        }
      }
    }
    return null;
  }
Ejemplo n.º 13
0
  private boolean tryToUseSourceAsAWorkaround() {
    if (element.getKind() != ElementKind.METHOD) {
      // we don't bother with non-method attributes
      // (like factory builder, where attributes are parameters)
      return false;
    }

    CharSequence returnTypeString =
        SourceExtraction.getReturnTypeString((ExecutableElement) element);
    if (returnTypeString.length() == 0) {
      // no source could be extracted for some reason, workaround will not work
      return false;
    }

    Entry<String, List<String>> extractedTypes = SourceTypes.extract(returnTypeString);

    // forces source imports based resolution,
    // we should not rely that types would be fully qualified
    Entry<String, List<String>> resolvedTypes = resolveTypes(extractedTypes);

    this.rawTypeName = resolvedTypes.getKey();
    this.workaroundTypeParameters = resolvedTypes.getValue();
    this.workaroundTypeString = SourceTypes.stringify(resolvedTypes);

    // workaround may have successed, need to continue with whatever we have
    return true;
  }
Ejemplo n.º 14
0
 // Assumes targetKinds and E are sensible.
 private static <E extends Element> List<E> listFilter(
     Iterable<? extends Element> elements, Set<ElementKind> targetKinds, Class<E> clazz) {
   List<E> list = new ArrayList<E>();
   for (Element e : elements) {
     if (targetKinds.contains(e.getKind())) list.add(clazz.cast(e));
   }
   return list;
 }
Ejemplo n.º 15
0
 private boolean hasMethod(String methodName) {
   for (Element element : typeElement.getEnclosedElements()) {
     if (element.getKind() == ElementKind.METHOD
         && methodName.equalsIgnoreCase(element.getSimpleName().toString())) {
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 16
0
 // Assumes targetKinds and E are sensible.
 private static <E extends Element> Set<E> setFilter(
     Set<? extends Element> elements, Set<ElementKind> targetKinds, Class<E> clazz) {
   // Return set preserving iteration order of input set.
   Set<E> set = new LinkedHashSet<E>();
   for (Element e : elements) {
     if (targetKinds.contains(e.getKind())) set.add(clazz.cast(e));
   }
   return set;
 }
  private void createBeanInfo(TypeElement classElement) throws Exception {
    if (verbose) {
      processingEnv
          .getMessager()
          .printMessage(
              Diagnostic.Kind.NOTE, "Generating BeanInfo for " + classElement.getSimpleName());
    }

    String className = classElement.getSimpleName().toString();
    String qualifiedName = classElement.getQualifiedName().toString();
    PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();
    String packageName = packageElement.getQualifiedName().toString();

    Map<String, VariableElement> fields = new HashMap<String, VariableElement>();

    Writer writer = null;

    try {
      // Build Bean Info
      TypeElement curClassElement = classElement;
      do {

        for (Element e : curClassElement.getEnclosedElements()) {
          if (e.getKind().equals(ElementKind.FIELD)
              && !e.getModifiers().contains(Modifier.TRANSIENT)
              && !e.getModifiers().contains(Modifier.STATIC)) {

            fields.put(e.getSimpleName().toString(), (VariableElement) e);
          }
        }

        TypeMirror t = curClassElement.getSuperclass();
        if (t instanceof DeclaredType) {
          curClassElement = (TypeElement) ((DeclaredType) t).asElement();
        } else {
          curClassElement = null;
        }

      } while (curClassElement != null);
      VelocityContext vc = new VelocityContext();
      vc.put("className", className);
      vc.put("packageName", packageName);
      vc.put("fields", fields);
      // Create source file
      JavaFileObject jfo = processingEnv.getFiler().createSourceFile(qualifiedName + "BeanInfo");
      if (verbose) {
        processingEnv
            .getMessager()
            .printMessage(Diagnostic.Kind.NOTE, "creating source file: " + jfo.toUri());
      }
      writer = jfo.openWriter();
      template.merge(vc, writer);
    } finally {
      closeQuietly(writer);
    }
  }
Ejemplo n.º 18
0
 private boolean doesClassContainNoArgsConstructor(Element el) {
   for (Element subelement : el.getEnclosedElements()) {
     if (subelement.getKind() == ElementKind.CONSTRUCTOR
         && subelement.getModifiers().contains(Modifier.PUBLIC)) {
       TypeMirror mirror = subelement.asType();
       if (mirror.accept(noArgsVisitor, null)) return true;
     }
   }
   return false;
 }
Ejemplo n.º 19
0
 public void printElement(TypeElement typeElement) {
   List<? extends AnnotationMirror> annotationMirrors = typeElement.getAnnotationMirrors();
   generator.log("class: " + typeElement + ", annotations: " + annotationMirrors);
   for (Element ele : typeElement.getEnclosedElements()) {
     if (ele.getKind().equals(ElementKind.METHOD)) {
       ExecutableElement method = (ExecutableElement) ele;
       printMethod(method);
     }
   }
 }
  /**
   * {@inheritDoc}
   *
   * <p>In most cases, subclasses want to call this method first because it may clear all
   * annotations and use the hierarchy's root annotations.
   */
  @Override
  public void postAsMemberOf(AnnotatedTypeMirror type, AnnotatedTypeMirror owner, Element element) {
    super.postAsMemberOf(type, owner, element);

    if (element.getKind().isField()) {
      Collection<? extends AnnotationMirror> declaredFieldAnnotations = getDeclAnnotations(element);
      AnnotatedTypeMirror fieldAnnotations = getAnnotatedType(element);
      computeFieldAccessType(type, declaredFieldAnnotations, owner, fieldAnnotations, element);
    }
  }
Ejemplo n.º 21
0
  private List<Element> getFixedFieldAnnotateMethod(Element clazz) {
    List<Element> listGetter = new ArrayList<Element>();

    for (Element element : clazz.getEnclosedElements()) {
      if (element.getKind().equals(ElementKind.METHOD)
          && element.getSimpleName().toString().startsWith("get")) {
        listGetter.add(element);
      }
    }
    return listGetter;
  }
 @Override
 public Void visitExecutable(AnnotatedExecutableType t, Void p) {
   Void result = super.visitExecutable(t, p);
   Element elem = t.getElement();
   if (elem.getKind() == ElementKind.CONSTRUCTOR) {
     AnnotatedDeclaredType returnType = (AnnotatedDeclaredType) t.getReturnType();
     DeclaredType underlyingType = returnType.getUnderlyingType();
     returnType.replaceAnnotation(getFreeOrRawAnnotationOfSuperType(underlyingType));
   }
   return result;
 }
Ejemplo n.º 23
0
  public void parse(TypeElement layoutElement) {
    if (!layoutElement.getInterfaces().isEmpty()) {
      parseSuperLayout(
          (TypeElement) ((DeclaredType) layoutElement.getInterfaces().get(0)).asElement());
    }

    parseName(layoutElement);

    objectTypeSuperclass = layoutElement.getAnnotation(Layout.class).objectTypeSuperclass();

    for (Element element : layoutElement.getEnclosedElements()) {
      if (element.getKind() == ElementKind.FIELD) {
        final String simpleName = element.getSimpleName().toString();

        if (simpleName.endsWith("_IDENTIFIER")) {
          parseIdentifier((VariableElement) element);
        } else {
          throw new AssertionError("Unknown field in layout interface");
        }
      } else if (element.getKind() == ElementKind.METHOD) {
        final String simpleName = element.getSimpleName().toString();

        if (simpleName.equals("create" + name + "Shape")) {
          parseShapeConstructor((ExecutableElement) element);
        } else if (simpleName.equals("create" + name)) {
          parseConstructor((ExecutableElement) element);
        } else if (simpleName.equals("is" + name)) {
          parseGuard((ExecutableElement) element);
        } else if (simpleName.startsWith("get")) {
          parseGetter((ExecutableElement) element);
        } else if (simpleName.startsWith("set")) {
          parseSetter((ExecutableElement) element);
        } else {
          throw new AssertionError("Unknown method in layout interface " + interfaceFullName);
        }
      }
    }

    assert constructorProperties.size() == properties.size();
    assert constructorProperties.containsAll(properties.keySet());
  }
Ejemplo n.º 24
0
  static boolean checkAbstractValueType(Element element, Collection<String> violations) {
    boolean ofSupportedKind =
        false
            || element.getKind() == ElementKind.INTERFACE
            || element.getKind() == ElementKind.ANNOTATION_TYPE
            || element.getKind() == ElementKind.CLASS;

    boolean staticOrTopLevel =
        false
            || element.getEnclosingElement().getKind() == ElementKind.PACKAGE
            || element.getModifiers().contains(Modifier.STATIC);

    boolean nonFinal = !element.getModifiers().contains(Modifier.FINAL);
    boolean hasNoTypeParameters = ((TypeElement) element).getTypeParameters().isEmpty();

    boolean publicOrPackageVisible =
        !element.getModifiers().contains(Modifier.PRIVATE)
            && !element.getModifiers().contains(Modifier.PROTECTED);

    if (!ofSupportedKind) {
      violations.add("must be class or interface or annotation type");
    }

    if (!nonFinal) {
      violations.add("must be non-final");
    }

    if (!hasNoTypeParameters) {
      violations.add("should have no type parameters");
    }

    if (!publicOrPackageVisible) {
      violations.add("should be public or package-visible");
    }

    if (!staticOrTopLevel) {
      violations.add("should be top-level or static inner class");
    }

    return violations.isEmpty();
  }
Ejemplo n.º 25
0
  private void collectFields() {
    for (Element element : typeElement.getEnclosedElements()) {
      if (element.getKind() == ElementKind.FIELD) {
        String fieldName = element.getSimpleName().toString();
        boolean isPublic = isPublicField(element);
        boolean hasGet = hasGetMethod(fieldName);
        boolean hasSet = hasSetMethod(fieldName);

        fields.put(fieldName, new Field(fieldName, hasGet, hasSet, isPublic));
      }
    }
  }
 @Override
 public Result checkCapsule(TypeElement template) {
   for (Element element : template.getEnclosedElements()) {
     if (element.getKind() == ElementKind.FIELD) {
       if (hasLocalSignatureField(element)) {
         String err = "Cannot have a `@Local` field whose type is a signature.";
         return error(err, CheckForLocalSignatureFields.class, element);
       }
     }
   }
   return OK;
 }
Ejemplo n.º 27
0
 // TODO(sgoldfed): better format for other types of elements?
 static String elementToString(Element element) {
   switch (element.getKind()) {
     case FIELD:
       // fall through
     case CONSTRUCTOR:
       // fall through
     case METHOD:
       return element.getEnclosingElement() + "." + element;
     default:
       return element.toString();
   }
 }
Ejemplo n.º 28
0
 /** Returns the no-args constructor for {@code type}, or null if no such constructor exists. */
 public static ExecutableElement getNoArgsConstructor(TypeElement type) {
   for (Element enclosed : type.getEnclosedElements()) {
     if (enclosed.getKind() != ElementKind.CONSTRUCTOR) {
       continue;
     }
     ExecutableElement constructor = (ExecutableElement) enclosed;
     if (constructor.getParameters().isEmpty()) {
       return constructor;
     }
   }
   return null;
 }
Ejemplo n.º 29
0
  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
      return true;
    }

    for (Element element : roundEnv.getElementsAnnotatedWith(ServiceProvider.class)) {
      assert element.getKind().isClass();
      processElement((TypeElement) element);
    }

    return true;
  }
Ejemplo n.º 30
0
 private boolean hasParcelableConstructor(TypeElement typeElement) {
   for (Element e : typeElement.getEnclosedElements()) {
     if (e.getKind() == ElementKind.CONSTRUCTOR && hasSomeModifier(e, Modifier.PUBLIC)) {
       ExecutableElement c = (ExecutableElement) e;
       List<? extends VariableElement> params = c.getParameters();
       if (params.size() == 1
           && ClassName.get(params.get(0).asType()).equals(ClassName.get(Parcel.class))) {
         return true;
       }
     }
   }
   return false;
 }