Java Code Examples for com.sun.source.tree.ModifiersTree#getAnnotations()

The following examples show how to use com.sun.source.tree.ModifiersTree#getAnnotations() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NopenChecker.java    From nopen with Apache License 2.0 5 votes vote down vote up
@Override public Description matchClass(ClassTree tree, VisitorState state) {
  if (tree.getKind() != CLASS) {
    return NO_MATCH;
  }

  ModifiersTree modifiers = tree.getModifiers();
  Set<Modifier> modifierFlags = modifiers.getFlags();
  if (modifierFlags.contains(FINAL) || modifierFlags.contains(ABSTRACT)) {
    return NO_MATCH;
  }

  switch (ASTHelpers.getSymbol(tree).getNestingKind()) {
    case LOCAL:
    case ANONYMOUS:
      return NO_MATCH;

    case MEMBER:
      if (modifierFlags.contains(PRIVATE)) {
        return NO_MATCH;
      }
      break;

    case TOP_LEVEL:
      break;
  }

  for (AnnotationTree annotation : modifiers.getAnnotations()) {
    AnnotationMirror annotationMirror = ASTHelpers.getAnnotationMirror(annotation);
    if (annotationMirror.getAnnotationType().toString().equals(OPEN_FQCN)) {
      return NO_MATCH;
    }
  }
  return describeMatch(tree);
}
 
Example 2
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Can a local with a set of modifiers be declared with horizontal annotations? This is currently
 * true if there is at most one marker annotation, and no others.
 *
 * @param modifiers the list of {@link ModifiersTree}s
 * @return whether the local can be declared with horizontal annotations
 */
private Direction canLocalHaveHorizontalAnnotations(ModifiersTree modifiers) {
    int markerAnnotations = 0;
    for (AnnotationTree annotation : modifiers.getAnnotations()) {
        if (annotation.getArguments().isEmpty()) {
            markerAnnotations++;
        }
    }
    return markerAnnotations <= 1 && markerAnnotations == modifiers.getAnnotations().size()
            ? Direction.HORIZONTAL
            : Direction.VERTICAL;
}
 
Example 3
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Should a field with a set of modifiers be declared with horizontal annotations? This is
 * currently true if all annotations are marker annotations.
 */
private Direction fieldAnnotationDirection(ModifiersTree modifiers) {
    for (AnnotationTree annotation : modifiers.getAnnotations()) {
        if (!annotation.getArguments().isEmpty()) {
            return Direction.VERTICAL;
        }
    }
    return Direction.HORIZONTAL;
}
 
Example 4
Source File: RemoveOverride.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    ModifiersTree mt = (ModifiersTree) ctx.getPath().getLeaf();
    
    for (AnnotationTree at : mt.getAnnotations()) {
        Element el = ctx.getWorkingCopy().getTrees().getElement(new TreePath(ctx.getPath(), at));
        
        if (el != null && el.getKind().isInterface() && ((TypeElement ) el).getQualifiedName().contentEquals("java.lang.Override")) {
            ctx.getWorkingCopy().rewrite(mt, ctx.getWorkingCopy().getTreeMaker().removeModifiersAnnotation(mt, at));
            return ;
        }
    }
}
 
Example 5
Source File: PersistentTimerInEjbLite.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void fixTimerAnnotation(WorkingCopy copy) {
    TypeElement scheduleAnnotation = copy.getElements().getTypeElement(EJBAPIAnnotations.SCHEDULE);
    ModifiersTree modifiers = ((MethodTree) copy.getTrees().getPath(methodElement.resolve(copy)).getLeaf()).getModifiers();
    TreeMaker tm = copy.getTreeMaker();
    for (AnnotationTree at : modifiers.getAnnotations()) {
        TreePath tp = new TreePath(new TreePath(copy.getCompilationUnit()), at.getAnnotationType());
        Element e = copy.getTrees().getElement(tp);
        if (scheduleAnnotation.equals(e)) {
            List<? extends ExpressionTree> arguments = at.getArguments();
            for (ExpressionTree et : arguments) {
                if (et.getKind() == Tree.Kind.ASSIGNMENT) {
                    AssignmentTree assignment = (AssignmentTree) et;
                    AssignmentTree newAssignment = tm.Assignment(assignment.getVariable(), tm.Literal(false));
                    if (EJBAPIAnnotations.PERSISTENT.equals(assignment.getVariable().toString())) {
                        copy.rewrite(
                                modifiers,
                                copy.getTreeUtilities().translate(modifiers, Collections.singletonMap(et, newAssignment)));
                        return;
                    }
                }
            }
            List<ExpressionTree> newArguments = new ArrayList<ExpressionTree>(arguments);
            ExpressionTree persistenQualIdent = tm.QualIdent(EJBAPIAnnotations.PERSISTENT);
            newArguments.add(tm.Assignment(persistenQualIdent, tm.Literal(false)));
            AnnotationTree newAnnotation = tm.Annotation(tp.getLeaf(), newArguments);
            copy.rewrite(at, newAnnotation);
            return;
        }
    }
}
 
Example 6
Source File: ControllerGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private AnnotationTree findFxmlAnnotation(ModifiersTree modTree) {
    for (AnnotationTree annTree : modTree.getAnnotations()) {
        TreePath tp = new TreePath(new TreePath(wcopy.getCompilationUnit()), annTree.getAnnotationType());
        Element  e  = wcopy.getTrees().getElement(tp);
        if (fxmlAnnotationType.equals(e)) {
            return annTree;
        }
    }
    return null;
}
 
Example 7
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Can a local with a set of modifiers be declared with horizontal annotations? This is currently
 * true if there is at most one marker annotation, and no others.
 *
 * @param modifiers the list of {@link ModifiersTree}s
 * @return whether the local can be declared with horizontal annotations
 */
private Direction canLocalHaveHorizontalAnnotations(ModifiersTree modifiers) {
    int markerAnnotations = 0;
    for (AnnotationTree annotation : modifiers.getAnnotations()) {
        if (annotation.getArguments().isEmpty()) {
            markerAnnotations++;
        }
    }
    return markerAnnotations <= 1 && markerAnnotations == modifiers.getAnnotations().size()
            ? Direction.HORIZONTAL
            : Direction.VERTICAL;
}
 
Example 8
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Should a field with a set of modifiers be declared with horizontal annotations? This is
 * currently true if all annotations are marker annotations.
 */
private Direction fieldAnnotationDirection(ModifiersTree modifiers) {
    for (AnnotationTree annotation : modifiers.getAnnotations()) {
        if (!annotation.getArguments().isEmpty()) {
            return Direction.VERTICAL;
        }
    }
    return Direction.HORIZONTAL;
}
 
Example 9
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
/**
 * Can a local with a set of modifiers be declared with horizontal annotations? This is currently
 * true if there is at most one parameterless annotation, and no others.
 *
 * @param modifiers the list of {@link ModifiersTree}s
 * @return whether the local can be declared with horizontal annotations
 */
private Direction canLocalHaveHorizontalAnnotations(ModifiersTree modifiers) {
  int parameterlessAnnotations = 0;
  for (AnnotationTree annotation : modifiers.getAnnotations()) {
    if (annotation.getArguments().isEmpty()) {
      parameterlessAnnotations++;
    }
  }
  return parameterlessAnnotations <= 1
          && parameterlessAnnotations == modifiers.getAnnotations().size()
      ? Direction.HORIZONTAL
      : Direction.VERTICAL;
}
 
Example 10
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
/**
 * Should a field with a set of modifiers be declared with horizontal annotations? This is
 * currently true if all annotations are parameterless annotations.
 */
private Direction fieldAnnotationDirection(ModifiersTree modifiers) {
  for (AnnotationTree annotation : modifiers.getAnnotations()) {
    if (!annotation.getArguments().isEmpty()) {
      return Direction.VERTICAL;
    }
  }
  return Direction.HORIZONTAL;
}
 
Example 11
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private List<Annotation> convertAnnotations(ModifiersTree modifiers, TreePath parent) {
  List<Annotation> annotations = new ArrayList<>();
  TreePath path = getTreePath(parent, modifiers);
  for (AnnotationTree annotation : modifiers.getAnnotations()) {
    annotations.add((Annotation) convert(annotation, path));
  }
  return annotations;
}
 
Example 12
Source File: UnifyAccessType.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public ChangeInfo implement(){
    CancellableTask<WorkingCopy> task = new CancellableTask<WorkingCopy>(){
        public void cancel() {}
        
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            TypeElement clazz = classHandle.resolve(workingCopy);
            
            if (clazz != null){
                
                for (ExecutableElement methodElem : ElementFilter.methodsIn(clazz.getEnclosedElements())){
                    if (methodElem.getSimpleName().toString().startsWith("get")){ //NOI18N
                        VariableElement fieldElem = ModelUtils.getField(clazz, ModelUtils.getFieldNameFromAccessor(methodElem.getSimpleName().toString()));
                        
                        if (fieldElem != null){
                            MethodTree methodTree = workingCopy.getTrees().getTree((methodElem));
                            VariableTree fieldTree = (VariableTree) workingCopy.getTrees().getTree(fieldElem);
                            
                            ModifiersTree srcModifiersTree = getSourceModifiers(fieldTree, methodTree);
                            
                            List <AnnotationTree> remainingAnnotations = new LinkedList<AnnotationTree>();
                            List <AnnotationTree> newTargetAnnots = new LinkedList<AnnotationTree>();
                            
                            for (AnnotationTree annTree : srcModifiersTree.getAnnotations()){
                                if (isJPAAttrAnnotation(workingCopy, annTree)){
                                    newTargetAnnots.add(annTree);
                                } else {
                                    remainingAnnotations.add(annTree);
                                }
                            }
                            
                            if (newTargetAnnots.size() > 0){
                                TreeMaker make = workingCopy.getTreeMaker();
                                ModifiersTree targetModifiers = getTargetModifiers(fieldTree, methodTree);
                                
                                workingCopy.rewrite(srcModifiersTree, make.Modifiers(srcModifiersTree, remainingAnnotations));
                                newTargetAnnots.addAll(targetModifiers.getAnnotations());
                                workingCopy.rewrite(targetModifiers,make.Modifiers(targetModifiers,newTargetAnnots));
                            }
                        }
                    }
                }
            }
        }
    };
    
    JavaSource javaSource = JavaSource.forFileObject(fileObject);
    
    try{
        javaSource.runModificationTask(task).commit();
    } catch (IOException e){
        JPAProblemFinder.LOG.log(Level.SEVERE, e.getMessage(), e);
    }
    return null;
}
 
Example 13
Source File: UseNbBundleMessages.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean isAlreadyRegistered(TreePath treePath, String key) {
    ModifiersTree modifiers;
    Tree tree = treePath.getLeaf();
    switch (tree.getKind()) {
    case METHOD:
        modifiers = ((MethodTree) tree).getModifiers();
        break;
    case VARIABLE:
        modifiers = ((VariableTree) tree).getModifiers();
        break;
    case CLASS:
    case ENUM:
    case INTERFACE:
    case ANNOTATION_TYPE:
        modifiers = ((ClassTree) tree).getModifiers();
        break;
    default:
        modifiers = null;
    }
    if (modifiers != null) {
        for (AnnotationTree ann : modifiers.getAnnotations()) {
            Tree annotationType = ann.getAnnotationType();
            if (annotationType.toString().matches("((org[.]openide[.]util[.])?NbBundle[.])?Messages")) { // XXX see above
                List<? extends ExpressionTree> args = ann.getArguments();
                if (args.size() != 1) {
                    continue; // ?
                }
                AssignmentTree assign = (AssignmentTree) args.get(0);
                if (!assign.getVariable().toString().equals("value")) {
                    continue; // ?
                }
                ExpressionTree arg = assign.getExpression();
                if (arg.getKind() == Tree.Kind.STRING_LITERAL) {
                    if (isRegistered(key, arg)) {
                        return true;
                    }
                } else if (arg.getKind() == Tree.Kind.NEW_ARRAY) {
                    for (ExpressionTree elt : ((NewArrayTree) arg).getInitializers()) {
                        if (isRegistered(key, elt)) {
                            return true;
                        }
                    }
                } else {
                    // ?
                }
            }
        }
    }
    TreePath parentPath = treePath.getParentPath();
    if (parentPath == null) {
        return false;
    }
    // XXX better to check all sources in the same package
    return isAlreadyRegistered(parentPath, key);
}
 
Example 14
Source File: ErrorBuilder.java    From NullAway with MIT License 4 votes vote down vote up
Description.Builder addSuppressWarningsFix(
    Tree suggestTree, Description.Builder builder, String suppressionName) {
  SuppressWarnings extantSuppressWarnings = null;
  Symbol treeSymbol = ASTHelpers.getSymbol(suggestTree);
  if (treeSymbol != null) {
    extantSuppressWarnings = treeSymbol.getAnnotation(SuppressWarnings.class);
  }
  SuggestedFix fix;
  if (extantSuppressWarnings == null) {
    fix =
        SuggestedFix.prefixWith(
            suggestTree,
            "@SuppressWarnings(\""
                + suppressionName
                + "\") "
                + config.getAutofixSuppressionComment());
  } else {
    // need to update the existing list of warnings
    final List<String> suppressions = Lists.newArrayList(extantSuppressWarnings.value());
    suppressions.add(suppressionName);
    // find the existing annotation, so we can replace it
    final ModifiersTree modifiers =
        (suggestTree instanceof MethodTree)
            ? ((MethodTree) suggestTree).getModifiers()
            : ((VariableTree) suggestTree).getModifiers();
    final List<? extends AnnotationTree> annotations = modifiers.getAnnotations();
    // noinspection ConstantConditions
    com.google.common.base.Optional<? extends AnnotationTree> suppressWarningsAnnot =
        Iterables.tryFind(
            annotations,
            annot -> annot.getAnnotationType().toString().endsWith("SuppressWarnings"));
    if (!suppressWarningsAnnot.isPresent()) {
      throw new AssertionError("something went horribly wrong");
    }
    final String replacement =
        "@SuppressWarnings({"
            + Joiner.on(',').join(Iterables.transform(suppressions, s -> '"' + s + '"'))
            + "}) "
            + config.getAutofixSuppressionComment();
    fix = SuggestedFix.replace(suppressWarningsAnnot.get(), replacement);
  }
  return builder.addFix(fix);
}