com.sun.source.tree.AnnotationTree Java Examples
The following examples show how to use
com.sun.source.tree.AnnotationTree.
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: Utilities.java From netbeans with Apache License 2.0 | 6 votes |
private static void addAnnotation(WorkingCopy workingCopy, Element element, String annotationName) throws IOException { ModifiersTree oldTree = null; if (element instanceof TypeElement) { oldTree = workingCopy.getTrees().getTree((TypeElement) element). getModifiers(); } else if (element instanceof ExecutableElement) { oldTree = workingCopy.getTrees().getTree((ExecutableElement) element). getModifiers(); } else if (element instanceof VariableElement) { oldTree = ((VariableTree) workingCopy.getTrees().getTree(element)). getModifiers(); } if (oldTree == null) { return; } TreeMaker make = workingCopy.getTreeMaker(); AnnotationTree annotationTree = make.Annotation(make.QualIdent(annotationName), Collections.<ExpressionTree>emptyList()); ModifiersTree newTree = make.addModifiersAnnotation(oldTree, annotationTree); workingCopy.rewrite(oldTree, newTree); }
Example #2
Source File: Utilities.java From netbeans with Apache License 2.0 | 6 votes |
public static List<AnnotationTree> findArrayValue(AnnotationTree at, String name) { ExpressionTree fixesArray = findValue(at, name); List<AnnotationTree> fixes = new LinkedList<AnnotationTree>(); if (fixesArray != null && fixesArray.getKind() == Kind.NEW_ARRAY) { NewArrayTree trees = (NewArrayTree) fixesArray; for (ExpressionTree fix : trees.getInitializers()) { if (fix.getKind() == Kind.ANNOTATION) { fixes.add((AnnotationTree) fix); } } } if (fixesArray != null && fixesArray.getKind() == Kind.ANNOTATION) { fixes.add((AnnotationTree) fixesArray); } return fixes; }
Example #3
Source File: TreeBackedEnter.java From buck with Apache License 2.0 | 6 votes |
private void enterAnnotationMirrors(TreeBackedElement element) { List<? extends AnnotationMirror> underlyingAnnotations = element.getUnderlyingElement().getAnnotationMirrors(); if (underlyingAnnotations.isEmpty()) { return; } List<? extends AnnotationTree> annotationTrees = getAnnotationTrees(currentTree); if (underlyingAnnotations.size() != annotationTrees.size()) { throw new IllegalArgumentException(); } for (int i = 0; i < underlyingAnnotations.size(); i++) { element.addAnnotationMirror( new TreeBackedAnnotationMirror( underlyingAnnotations.get(i), new TreePath(currentPath, annotationTrees.get(i)), canonicalizer)); } }
Example #4
Source File: GenerationUtils.java From netbeans with Apache License 2.0 | 6 votes |
/** * Adds an annotation to a method. This is equivalent to {@link TreeMaker#addModifiersAnnotation}, * but it creates and returns a new <code>MethodTree, not a new <code>ModifiersTree</code>. * * @param methodTree the method to add the annotation to; cannot be null. * @param annotationTree the annotation to add; cannot be null. * @return a new method annotated with the new annotation; never null. */ public MethodTree addAnnotation(MethodTree methodTree, AnnotationTree annotationTree) { Parameters.notNull("methodTree", methodTree); // NOI18N Parameters.notNull("annotationTree", annotationTree); // NOI18N TreeMaker make = getTreeMaker(); return make.Method( make.addModifiersAnnotation(methodTree.getModifiers(), annotationTree), methodTree.getName(), methodTree.getReturnType(), methodTree.getTypeParameters(), methodTree.getParameters(), methodTree.getThrows(), methodTree.getBody(), (ExpressionTree)methodTree.getDefaultValue()); }
Example #5
Source File: JavaInputAstVisitor.java From java-n-IDE-for-Android with Apache License 2.0 | 6 votes |
/** * Helper method for annotations. */ private void visitAnnotations( List<? extends AnnotationTree> annotations, BreakOrNot breakBefore, BreakOrNot breakAfter) { if (!annotations.isEmpty()) { if (breakBefore.isYes()) { builder.breakToFill(" "); } boolean first = true; for (AnnotationTree annotation : annotations) { if (!first) { builder.breakToFill(" "); } scan(annotation, null); first = false; } if (breakAfter.isYes()) { builder.breakToFill(" "); } } }
Example #6
Source File: DimensionHelpers.java From javaide with GNU General Public License v3.0 | 6 votes |
/** * Accumulates a flattened list of array dimensions specifiers with type annotations, and returns * the base type. * <p> * <p>Given {@code int @A @B [][] @C []}, adds {@code [[@A, @B], [@C]]} to dims and returns {@code * int}. */ private static Tree extractDims(Deque<List<AnnotationTree>> dims, Tree node) { switch (node.getKind()) { case ARRAY_TYPE: return extractDims(dims, ((ArrayTypeTree) node).getType()); // TODO: 22-Jul-17 missing type /* case ANNOTATED_TYPE: AnnotatedTypeTree annotatedTypeTree = (AnnotatedTypeTree) node; if (annotatedTypeTree.getUnderlyingType().getKind() != Tree.Kind.ARRAY_TYPE) { return node; } node = extractDims(dims, annotatedTypeTree.getUnderlyingType()); dims.addFirst(ImmutableList.<AnnotationTree>copyOf(annotatedTypeTree.getAnnotations())); return node;*/ default: return node; } }
Example #7
Source File: DimensionHelpers.java From java-n-IDE-for-Android with Apache License 2.0 | 6 votes |
/** * Rotate the list of dimension specifiers until all dimensions with type annotations appear in * source order. * <p> * <p>javac reorders dimension specifiers in method declarations with mixed-array notation, which * means that any type annotations don't appear in source order. * <p> * <p>For example, the type of {@code int @A [] f() @B [] {}} is parsed as {@code @B [] @A []}. * <p> * <p>This doesn't handle cases with un-annotated dimension specifiers, so the formatting logic * checks the token stream to figure out which side of the method name they appear on. */ private static Iterable<List<AnnotationTree>> reorderBySourcePosition( Deque<List<AnnotationTree>> dims) { int lastAnnotation = -1; int lastPos = -1; int idx = 0; for (List<AnnotationTree> dim : dims) { if (!dim.isEmpty()) { int pos = ((JCTree) dim.get(0)).getStartPosition(); if (pos < lastPos) { List<List<AnnotationTree>> list = new ArrayList<>(dims); Collections.rotate(list, -(lastAnnotation + 1)); return list; } lastPos = pos; lastAnnotation = idx; } idx++; } return dims; }
Example #8
Source File: InconsistentPortType.java From netbeans with Apache License 2.0 | 6 votes |
protected ErrorDescription[] apply(TypeElement subject, ProblemContext ctx) { AnnotationMirror annEntity = Utilities.findAnnotation(subject, ANNOTATION_WEBSERVICE); if (subject.getKind() == ElementKind.CLASS && Utilities.getAnnotationAttrValue(annEntity, ANNOTATION_ATTRIBUTE_SEI) == null) { Service service = ctx.getLookup().lookup(Service.class); WSDLModel model = ctx.getLookup().lookup(WSDLModel.class); if (service != null && model != null && model.getState() == State.VALID) { PortType portType = model.findComponentByName(subject.getSimpleName().toString(), PortType.class); if (portType == null) { AnnotationValue nameVal = Utilities.getAnnotationAttrValue(annEntity, ANNOTATION_ATTRIBUTE_NAME); if(nameVal!=null) portType = model.findComponentByName(nameVal.toString(), PortType.class); } if (portType == null) { String label = NbBundle.getMessage(InconsistentPortType.class, "MSG_InconsistentPortType"); AnnotationTree annotationTree = (AnnotationTree) ctx.getCompilationInfo(). getTrees().getTree(subject, annEntity); Tree problemTree = Utilities.getAnnotationArgumentTree(annotationTree, ANNOTATION_ATTRIBUTE_WSDLLOCATION); ctx.setElementToAnnotate(problemTree); ErrorDescription problem = createProblem(subject, ctx, label, (Fix) null); ctx.setElementToAnnotate(null); return new ErrorDescription[]{problem}; } } } return null; }
Example #9
Source File: GenerationUtilsTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testCreateAnnotationArgumentWithNullName() throws Exception { FileObject annotationFO = workDir.createData("Annotations.java"); TestUtilities.copyStringToFileObject(testFO, "package foo;" + "public class TestClass {" + "}"); runModificationTask(testFO, new Task<WorkingCopy>() { public void run(WorkingCopy copy) throws Exception { GenerationUtils genUtils = GenerationUtils.newInstance(copy); ClassTree classTree = (ClassTree)copy.getCompilationUnit().getTypeDecls().get(0); AnnotationTree annWithLiteralArgument = genUtils.createAnnotation("java.lang.SuppressWarnings", Collections.singletonList(genUtils.createAnnotationArgument(null, "unchecked"))); AnnotationTree annWithArrayArgument = genUtils.createAnnotation("java.lang.annotation.Target", Collections.singletonList(genUtils.createAnnotationArgument(null, Collections.<ExpressionTree>emptyList()))); AnnotationTree annWithMemberSelectArgument = genUtils.createAnnotation("java.lang.annotation.Retention", Collections.singletonList(genUtils.createAnnotationArgument(null, "java.lang.annotation.RetentionPolicy", "RUNTIME"))); ClassTree newClassTree = genUtils.addAnnotation(classTree, annWithLiteralArgument); newClassTree = genUtils.addAnnotation(newClassTree, annWithArrayArgument); newClassTree = genUtils.addAnnotation(newClassTree, annWithMemberSelectArgument); copy.rewrite(classTree, newClassTree); } }).commit(); assertFalse(TestUtilities.copyFileObjectToString(testFO).contains("value")); }
Example #10
Source File: JavaInputAstVisitor.java From javaide with GNU General Public License v3.0 | 6 votes |
void visitVariables( List<VariableTree> fragments, DeclarationKind declarationKind, Direction annotationDirection) { if (fragments.size() == 1) { VariableTree fragment = fragments.get(0); declareOne( declarationKind, annotationDirection, Optional.of(fragment.getModifiers()), fragment.getType(), VarArgsOrNot.fromVariable(fragment), ImmutableList.<AnnotationTree>of(), fragment.getName(), "", "=", Optional.fromNullable(fragment.getInitializer()), Optional.of(";"), Optional.<ExpressionTree>absent(), Optional.fromNullable(variableFragmentDims(true, 0, fragment.getType()))); } else { declareMany(fragments, annotationDirection); } }
Example #11
Source File: InvalidNameAttribute.java From netbeans with Apache License 2.0 | 6 votes |
protected ErrorDescription[] apply(TypeElement subject, ProblemContext ctx) { AnnotationMirror annEntity = Utilities.findAnnotation(subject, ANNOTATION_WEBSERVICE); AnnotationTree annotationTree = (AnnotationTree) ctx.getCompilationInfo(). getTrees().getTree(subject, annEntity); if (subject.getKind() == ElementKind.CLASS) { AnnotationValue seiValue = Utilities.getAnnotationAttrValue(annEntity, ANNOTATION_ATTRIBUTE_SEI); if (seiValue != null && Utilities.getAnnotationAttrValue(annEntity, ANNOTATION_ATTRIBUTE_NAME) != null) { //check for name attribute String label = NbBundle.getMessage(InvalidNameAttribute.class, "MSG_NameAttributeNotAllowed"); Tree problemTree = Utilities.getAnnotationArgumentTree (annotationTree, ANNOTATION_ATTRIBUTE_NAME); Fix removeFix = new RemoveAnnotationArgument(ctx.getFileObject(), subject, annEntity, ANNOTATION_ATTRIBUTE_NAME); ctx.setElementToAnnotate(problemTree); ErrorDescription problem = createProblem(subject, ctx, label, removeFix); ctx.setElementToAnnotate(null); return new ErrorDescription[]{problem}; } } return null; }
Example #12
Source File: DimensionHelpers.java From google-java-format with Apache License 2.0 | 6 votes |
/** * Accumulates a flattened list of array dimensions specifiers with type annotations, and returns * the base type. * * <p>Given {@code int @A @B [][] @C []}, adds {@code [[@A, @B], [@C]]} to dims and returns {@code * int}. */ private static Tree extractDims(Deque<List<AnnotationTree>> dims, Tree node) { switch (node.getKind()) { case ARRAY_TYPE: return extractDims(dims, ((ArrayTypeTree) node).getType()); case ANNOTATED_TYPE: AnnotatedTypeTree annotatedTypeTree = (AnnotatedTypeTree) node; if (annotatedTypeTree.getUnderlyingType().getKind() != Tree.Kind.ARRAY_TYPE) { return node; } node = extractDims(dims, annotatedTypeTree.getUnderlyingType()); dims.addFirst(ImmutableList.copyOf(annotatedTypeTree.getAnnotations())); return node; default: return node; } }
Example #13
Source File: JavaInputAstVisitor.java From google-java-format with Apache License 2.0 | 6 votes |
/** Helper method for annotations. */ void visitAnnotations( List<? extends AnnotationTree> annotations, BreakOrNot breakBefore, BreakOrNot breakAfter) { if (!annotations.isEmpty()) { if (breakBefore.isYes()) { builder.breakToFill(" "); } boolean first = true; for (AnnotationTree annotation : annotations) { if (!first) { builder.breakToFill(" "); } scan(annotation, null); first = false; } if (breakAfter.isYes()) { builder.breakToFill(" "); } } }
Example #14
Source File: RestUtils.java From netbeans with Apache License 2.0 | 5 votes |
public static List<String> getMimeAnnotationValue(AnnotationTree ant) { List<? extends ExpressionTree> ets = ant.getArguments(); if (ets.size() > 0) { String value = getValueFromAnnotation(ets.get(0)); value = value.replace("\"", ""); return Arrays.asList(value.split(",")); } return Collections.emptyList(); }
Example #15
Source File: AbstractTestGenerator.java From netbeans with Apache License 2.0 | 5 votes |
/** */ protected ModifiersTree createModifiersTree(String annotationClassName, Set<Modifier> modifiers, WorkingCopy workingCopy) { TreeMaker maker = workingCopy.getTreeMaker(); AnnotationTree annotation = maker.Annotation( getClassIdentifierTree(annotationClassName, workingCopy), Collections.<ExpressionTree>emptyList()); return maker.Modifiers(modifiers, Collections.<AnnotationTree>singletonList( annotation)); }
Example #16
Source File: JavaInputAstVisitor.java From javaide with GNU General Public License v3.0 | 5 votes |
/** * 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 #17
Source File: GenerationUtilsTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testCreateAnnotationBooleanArgumentIssue89230() throws Exception { TestUtilities.copyStringToFileObject(testFO, "package foo;" + "@interface Column {" + " boolean nullable();" + "}" + "public class TestClass {" + "}"); runModificationTask(testFO, new Task<WorkingCopy>() { public void run(WorkingCopy copy) throws Exception { GenerationUtils genUtils = GenerationUtils.newInstance(copy); ClassTree classTree = SourceUtils.getPublicTopLevelTree(copy); AnnotationTree annotationTree = genUtils.createAnnotation("foo.Column", Collections.singletonList(genUtils.createAnnotationArgument("nullable", true))); ClassTree newClassTree = genUtils.addAnnotation(classTree, annotationTree); copy.rewrite(classTree, newClassTree); } }).commit(); runUserActionTask(testFO, new Task<CompilationController>() { public void run(CompilationController controller) throws Exception { TypeElement typeElement = SourceUtils.getPublicTopLevelElement(controller); assertEquals(1, typeElement.getAnnotationMirrors().size()); AnnotationMirror columnAnn = typeElement.getAnnotationMirrors().get(0); assertEquals(1, columnAnn.getElementValues().size()); Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> columnAnnNullableElement = columnAnn.getElementValues().entrySet().iterator().next(); assertEquals("nullable", columnAnnNullableElement.getKey().getSimpleName().toString()); assertEquals(true, columnAnn.getElementValues().values().iterator().next().getValue()); } }); }
Example #18
Source File: RelationshipMappingRename.java From netbeans with Apache License 2.0 | 5 votes |
RelationshipAnnotationRenameRefactoringElement(FileObject fo, VariableElement var, AnnotationTree at, AnnotationMirror annotation, String attrValue, int start, int end) { this.fo = fo; this.annotation = annotation; this.attrValue = attrValue; if((end-start)>attrValue.length()){//handle quotes start++; end--; } loc = new int[]{start, end}; this.at = at; this.var = var; }
Example #19
Source File: JavacJ2ObjCIncompatibleStripper.java From j2objc with Apache License 2.0 | 5 votes |
/** * Checks for any J2ObjCIncompatible annotations. Returns whether * the caller should to continue scanning this node. */ private boolean checkAnnotations(List<? extends AnnotationTree> annotations, Tree node) { for (AnnotationTree annotation : annotations) { if (isJ2ObjCIncompatible(annotation)) { nodesToStrip.add(node); return false; } } return true; }
Example #20
Source File: PersistentTimerInEjbLite.java From netbeans with Apache License 2.0 | 5 votes |
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 #21
Source File: ApplicationManagedResourceTransactionInjectableInEJB.java From netbeans with Apache License 2.0 | 5 votes |
public ClassTree generate() { ClassTree modifiedClazz = getClassTree(); ModifiersTree methodModifiers = getTreeMaker().Modifiers( getGenerationOptions().getModifiers(), Collections.<AnnotationTree>emptyList() ); FieldInfo em = getEntityManagerFieldInfo(); if (!em.isExisting()){ modifiedClazz = createEntityManager(Initialization.INIT); } MethodTree newMethod = getTreeMaker().Method( methodModifiers, computeMethodName(), getTreeMaker().PrimitiveType(TypeKind.VOID), Collections.<TypeParameterTree>emptyList(), getParameterList(), Collections.<ExpressionTree>emptyList(), "{ " + getMethodBody(em)+ "}", null ); return getTreeMaker().addClassMember(modifiedClazz, importFQNs(newMethod)); }
Example #22
Source File: JavaSourceHelper.java From netbeans with Apache License 2.0 | 5 votes |
public static ModifiersTree createModifiersTree(WorkingCopy copy, Modifier[] modifiers, String[] annotations, Object[] annotationAttrs) { TreeMaker maker = copy.getTreeMaker(); Set<Modifier> modifierSet = new HashSet<Modifier>(); for (Modifier modifier : modifiers) { modifierSet.add(modifier); } List<AnnotationTree> annotationTrees = createAnnotationTrees(copy, annotations, annotationAttrs); return maker.Modifiers(modifierSet, annotationTrees); }
Example #23
Source File: ElementsTest.java From netbeans with Apache License 2.0 | 5 votes |
public void test175535() throws Exception { prepareTest(); FileObject otherFO = FileUtil.createData(sourceRoot, "test/A.java"); TestUtilities.copyStringToFile(FileUtil.toFile(otherFO), "package test;" + "public class A implements Runnable {" + " @Override" + " public void run() {}" + "}"); TestUtilities.copyStringToFile(FileUtil.toFile(testFO), "public class Test {" + "}"); SourceUtilsTestUtil.compileRecursively(sourceRoot); JavaSource javaSource = JavaSource.forFileObject(testFO); javaSource.runUserActionTask(new Task<CompilationController>() { public void run(CompilationController controller) throws IOException { controller.toPhase(JavaSource.Phase.RESOLVED); TypeElement typeElement = controller.getElements().getTypeElement("test.A"); assertNotNull(typeElement); Element el = typeElement.getEnclosedElements().get(1); assertNotNull(el); assertEquals("run", el.getSimpleName().toString()); TreePath mpath = controller.getTrees().getPath(el); MethodTree mtree = (MethodTree) mpath.getLeaf(); assertNotNull(mtree); List<? extends AnnotationTree> annotations = mtree.getModifiers().getAnnotations(); TypeMirror annotation = controller.getTrees().getTypeMirror(new TreePath(mpath, annotations.get(0))); assertNotNull(annotation); Element e = controller.getTrees().getElement(new TreePath(mpath, annotations.get(0))); assertNotNull(e); assertEquals(((DeclaredType)annotation).asElement(), e); } }, true); }
Example #24
Source File: JavaInputAstVisitor.java From google-java-format with Apache License 2.0 | 5 votes |
@Override public Void visitNewArray(NewArrayTree node, Void unused) { if (node.getType() != null) { builder.open(plusFour); token("new"); builder.space(); TypeWithDims extractedDims = DimensionHelpers.extractDims(node.getType(), SortedDims.YES); Tree base = extractedDims.node; Deque<ExpressionTree> dimExpressions = new ArrayDeque<>(node.getDimensions()); Deque<List<? extends AnnotationTree>> annotations = new ArrayDeque<>(); annotations.add(ImmutableList.copyOf(node.getAnnotations())); annotations.addAll(node.getDimAnnotations()); annotations.addAll(extractedDims.dims); scan(base, null); builder.open(ZERO); maybeAddDims(dimExpressions, annotations); builder.close(); builder.close(); } if (node.getInitializers() != null) { if (node.getType() != null) { builder.space(); } visitArrayInitializer(node.getInitializers()); } return null; }
Example #25
Source File: EntityManagerGenerationStrategySupport.java From netbeans with Apache License 2.0 | 5 votes |
protected VariableTree createUserTransaction(){ return getTreeMaker().Variable( getTreeMaker().Modifiers( Collections.<Modifier>singleton(Modifier.PRIVATE), Collections.<AnnotationTree>singletonList(getGenUtils().createAnnotation(RESOURCE_FQN)) ), "utx", //NOI18N getTreeMaker().Identifier(USER_TX_FQN), null); }
Example #26
Source File: GenerationUtilsTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testCreateAnnotation() throws Exception { TestUtilities.copyStringToFileObject(testFO, "package foo;" + "public class TestClass {" + "}"); runModificationTask(testFO, new Task<WorkingCopy>() { public void run(WorkingCopy copy) throws Exception { GenerationUtils genUtils = GenerationUtils.newInstance(copy); ClassTree classTree = (ClassTree)copy.getCompilationUnit().getTypeDecls().get(0); AnnotationTree annotationTree = genUtils.createAnnotation("java.lang.SuppressWarnings", Collections.singletonList(genUtils.createAnnotationArgument(null, "unchecked"))); ClassTree newClassTree = genUtils.addAnnotation(classTree, annotationTree); annotationTree = genUtils.createAnnotation("java.lang.annotation.Retention", Collections.singletonList(genUtils.createAnnotationArgument(null, "java.lang.annotation.RetentionPolicy", "RUNTIME"))); newClassTree = genUtils.addAnnotation(newClassTree, annotationTree); copy.rewrite(classTree, newClassTree); } }).commit(); runUserActionTask(testFO, new Task<CompilationController>() { public void run(CompilationController controller) throws Exception { TypeElement typeElement = SourceUtils.getPublicTopLevelElement(controller); assertEquals(2, typeElement.getAnnotationMirrors().size()); SuppressWarnings suppressWarnings = typeElement.getAnnotation(SuppressWarnings.class); assertNotNull(suppressWarnings); assertEquals(1, suppressWarnings.value().length); assertEquals("unchecked", suppressWarnings.value()[0]); Retention retention = typeElement.getAnnotation(Retention.class); assertNotNull(retention); assertEquals(RetentionPolicy.RUNTIME, retention.value()); } }); }
Example #27
Source File: TreeConverter.java From j2objc with Apache License 2.0 | 5 votes |
private PackageDeclaration convertPackage(TreePath parent) { ExpressionTree pkgName = unit.getPackageName(); PackageElement pkg = pkgName != null ? env.elementUtilities().getPackageElement(pkgName.toString()) : env.defaultPackage(); PackageDeclaration newNode = null; if (pkg == null) { // Synthetic package, create from name. pkg = new GeneratedPackageElement(pkgName != null ? pkgName.toString() : ""); newNode = new PackageDeclaration().setPackageElement(pkg); newNode.setName(new SimpleName(pkg, null)); } else { Tree node = trees.getTree(pkg); newNode = new PackageDeclaration().setPackageElement(pkg); for (AnnotationTree pkgAnnotation : unit.getPackageAnnotations()) { newNode.addAnnotation((Annotation) convert(pkgAnnotation, parent)); } if (unit.getSourceFile().toUri().getPath().endsWith("package-info.java")) { if (node == null) { // Java 8 javac bug, fixed in Java 9. Doc-comments in package-info.java // sources are keyed to their compilation unit, not their package node. node = unit; } newNode.setJavadoc((Javadoc) getAssociatedJavaDoc(node, getTreePath(parent, node))); } newNode.setName(newUnit.getEnv().elementUtil().getPackageName(pkg)); } newNode.setPosition(SourcePosition.NO_POSITION); return newNode; }
Example #28
Source File: AbstractTestGenerator.java From netbeans with Apache License 2.0 | 5 votes |
/** */ protected ModifiersTree createModifiersTree(String annotationClassName, Set<Modifier> modifiers, WorkingCopy workingCopy) { TreeMaker maker = workingCopy.getTreeMaker(); AnnotationTree annotation = maker.Annotation( getClassIdentifierTree(annotationClassName, workingCopy), Collections.<ExpressionTree>emptyList()); return maker.Modifiers(modifiers, Collections.<AnnotationTree>singletonList( annotation)); }
Example #29
Source File: TreeDiffer.java From compile-testing with Apache License 2.0 | 5 votes |
@Override public Void visitAnnotation(AnnotationTree expected, Tree actual) { Optional<AnnotationTree> other = checkTypeAndCast(expected, actual); if (!other.isPresent()) { addTypeMismatch(expected, actual); return null; } scan(expected.getAnnotationType(), other.get().getAnnotationType()); parallelScan(expected.getArguments(), other.get().getArguments()); return null; }
Example #30
Source File: JavaxFacesBeanIsGonnaBeDeprecated.java From netbeans with Apache License 2.0 | 5 votes |
@Override protected void performRewrite(TransformationContext ctx) throws Exception { WorkingCopy wc = ctx.getWorkingCopy(); wc.toPhase(JavaSource.Phase.RESOLVED); TreeMaker make = wc.getTreeMaker(); // rewrite annotations in case of ManagedBean if (MANAGED_BEAN.equals(annotation.getAnnotationType().toString())) { ModifiersTree modifiers = ((ClassTree) wc.getTrees().getTree(element)).getModifiers(); AnnotationTree annotationTree = (AnnotationTree) wc.getTrees().getTree(element, annotation); List<ExpressionTree> arguments = new ArrayList<>(); for (ExpressionTree expressionTree : annotationTree.getArguments()) { if (expressionTree.getKind() == Tree.Kind.ASSIGNMENT) { AssignmentTree at = (AssignmentTree) expressionTree; String varName = ((IdentifierTree) at.getVariable()).getName().toString(); if (varName.equals("name")) { //NOI18N ExpressionTree valueTree = make.Identifier(at.getExpression().toString()); arguments.add(valueTree); } } } ModifiersTree newModifiersTree = make.removeModifiersAnnotation(modifiers, (AnnotationTree) wc.getTrees().getTree(element, annotation)); AnnotationTree newTree = GenerationUtils.newInstance(wc).createAnnotation(replacingClass, arguments); newModifiersTree = make.addModifiersAnnotation(newModifiersTree, newTree); wc.rewrite(modifiers, newModifiersTree); } // rewrite imports List<? extends ImportTree> imports = wc.getCompilationUnit().getImports(); ImportTree newImportTree = make.Import(make.QualIdent(replacingClass), false); for (ImportTree importTree : imports) { if (deprecatedClass.equals(importTree.getQualifiedIdentifier().toString())) { wc.rewrite(importTree, newImportTree); } } }