/** * Returns the topmost ancestor of <code>node</code> that is a {@link Type} (but not a {@link UnionType}). * <p> * <b>Note:</b> The returned node often resolves to a different binding than the given <code>node</code>! * * @param node the starting node, can be <code>null</code> * @return the topmost type or <code>null</code> if the node is not a descendant of a type node * @see #getNormalizedNode(ASTNode) */ public static Type getTopMostType(ASTNode node) { ASTNode result= null; while (node instanceof Type && !(node instanceof UnionType) || node instanceof Name || node instanceof Annotation || node instanceof MemberValuePair || node instanceof Expression) { // Expression could maybe be reduced to expression node types that can appear in an annotation result= node; node= node.getParent(); } if (result instanceof Type) { return (Type) result; } return null; }
/** * Removes all {@link Annotation} whose only {@link Target} is {@link ElementType#TYPE_USE} from * <code>node</code>'s <code>childListProperty</code>. * <p> * In a combination of {@link ElementType#TYPE_USE} and {@link ElementType#TYPE_PARAMETER} * the latter is ignored, because this is implied by the former and creates no ambiguity.</p> * * @param node ASTNode * @param childListProperty child list property * @param rewrite rewrite that removes the nodes * @param editGroup the edit group in which to collect the corresponding text edits, or null if * ungrouped */ public static void removePureTypeAnnotations(ASTNode node, ChildListPropertyDescriptor childListProperty, ASTRewrite rewrite, TextEditGroup editGroup) { CompilationUnit root= (CompilationUnit) node.getRoot(); if (!JavaModelUtil.is18OrHigher(root.getJavaElement().getJavaProject())) { return; } ListRewrite listRewrite= rewrite.getListRewrite(node, childListProperty); @SuppressWarnings("unchecked") List<? extends ASTNode> children= (List<? extends ASTNode>) node.getStructuralProperty(childListProperty); for (ASTNode child : children) { if (child instanceof Annotation) { Annotation annotation= (Annotation) child; if (isPureTypeAnnotation(annotation)) { listRewrite.remove(child, editGroup); } } } }
public static void addOverrideAnnotation( IJavaProject project, ASTRewrite rewrite, MethodDeclaration decl, IMethodBinding binding) { if (binding.getDeclaringClass().isInterface()) { String version = project.getOption(JavaCore.COMPILER_COMPLIANCE, true); if (JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_6)) return; // not allowed in 1.5 if (JavaCore.DISABLED.equals( project.getOption( JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION_FOR_INTERFACE_METHOD_IMPLEMENTATION, true))) return; // user doesn't want to use 1.6 style } Annotation marker = rewrite.getAST().newMarkerAnnotation(); marker.setTypeName(rewrite.getAST().newSimpleName("Override")); // $NON-NLS-1$ rewrite.getListRewrite(decl, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(marker, null); }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { AST ast = cuRewrite.getRoot().getAST(); ListRewrite listRewrite = cuRewrite .getASTRewrite() .getListRewrite(fBodyDeclaration, fBodyDeclaration.getModifiersProperty()); Annotation newAnnotation = ast.newMarkerAnnotation(); newAnnotation.setTypeName(ast.newSimpleName(fAnnotation)); TextEditGroup group = createTextEditGroup( Messages.format( FixMessages.Java50Fix_AddMissingAnnotation_description, BasicElementLabels.getJavaElementName(fAnnotation)), cuRewrite); listRewrite.insertFirst(newAnnotation, group); }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { AST ast = cuRewrite.getRoot().getAST(); ListRewrite listRewrite = cuRewrite .getASTRewrite() .getListRewrite(fBodyDeclaration, fBodyDeclaration.getModifiersProperty()); TextEditGroup group = createTextEditGroup(fMessage, cuRewrite); if (!checkExisting(fBodyDeclaration.modifiers(), listRewrite, group)) return; if (hasNonNullDefault(fBodyDeclaration.resolveBinding())) return; // should be safe, as in this case checkExisting() should've already produced a // change (remove existing // annotation). Annotation newAnnotation = ast.newMarkerAnnotation(); ImportRewrite importRewrite = cuRewrite.getImportRewrite(); String resolvableName = importRewrite.addImport(fAnnotationToAdd); newAnnotation.setTypeName(ast.newName(resolvableName)); listRewrite.insertLast( newAnnotation, group); // null annotation is last modifier, directly preceding the return type }
@Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedModel) throws CoreException { AST ast = cuRewrite.getRoot().getAST(); ListRewrite listRewrite = cuRewrite .getASTRewrite() .getListRewrite(fArgument, SingleVariableDeclaration.MODIFIERS2_PROPERTY); TextEditGroup group = createTextEditGroup(fMessage, cuRewrite); if (!checkExisting(fArgument.modifiers(), listRewrite, group)) return; Annotation newAnnotation = ast.newMarkerAnnotation(); ImportRewrite importRewrite = cuRewrite.getImportRewrite(); String resolvableName = importRewrite.addImport(fAnnotationToAdd); newAnnotation.setTypeName(ast.newName(resolvableName)); listRewrite.insertLast( newAnnotation, group); // null annotation is last modifier, directly preceding the type }
private static boolean hasNullAnnotation(MethodDeclaration decl) { List<IExtendedModifier> modifiers = decl.modifiers(); String nonnull = NullAnnotationsFix.getNonNullAnnotationName(decl.resolveBinding().getJavaElement(), false); String nullable = NullAnnotationsFix.getNullableAnnotationName(decl.resolveBinding().getJavaElement(), false); for (Object mod : modifiers) { if (mod instanceof Annotation) { Name annotationName = ((Annotation) mod).getTypeName(); String fullyQualifiedName = annotationName.getFullyQualifiedName(); if (annotationName.isSimpleName() ? nonnull.endsWith(fullyQualifiedName) : fullyQualifiedName.equals(nonnull)) return true; if (annotationName.isSimpleName() ? nullable.endsWith(fullyQualifiedName) : fullyQualifiedName.equals(nullable)) return true; } } return false; }
/** * @param e * @return int Checks.IS_RVALUE if e is an rvalue Checks.IS_RVALUE_GUESSED if e is guessed as an * rvalue Checks.NOT_RVALUE_VOID if e is not an rvalue because its type is void * Checks.NOT_RVALUE_MISC if e is not an rvalue for some other reason */ public static int checkExpressionIsRValue(Expression e) { if (e instanceof Name) { if (!(((Name) e).resolveBinding() instanceof IVariableBinding)) { return NOT_RVALUE_MISC; } } if (e instanceof Annotation) return NOT_RVALUE_MISC; ITypeBinding tb = e.resolveTypeBinding(); boolean guessingRequired = false; if (tb == null) { guessingRequired = true; tb = ASTResolving.guessBindingForReference(e); } if (tb == null) return NOT_RVALUE_MISC; else if (tb.getName().equals("void")) // $NON-NLS-1$ return NOT_RVALUE_VOID; return guessingRequired ? IS_RVALUE_GUESSED : IS_RVALUE; }
private void checkExpression(RefactoringStatus status) { ASTNode[] nodes = getSelectedNodes(); if (nodes != null && nodes.length == 1) { ASTNode node = nodes[0]; if (node instanceof Type) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference, JavaStatusContext.create(fCUnit, node)); } else if (node.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_switch_case, JavaStatusContext.create(fCUnit, node)); } else if (node instanceof Annotation || ASTNodes.getParent(node, Annotation.class) != null) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_from_annotation, JavaStatusContext.create(fCUnit, node)); } } }
public static void removeOverrideAnnotationProposal( IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException { ICompilationUnit cu = context.getCompilationUnit(); ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot()); if (!(selectedNode instanceof MethodDeclaration)) { return; } MethodDeclaration methodDecl = (MethodDeclaration) selectedNode; Annotation annot = findAnnotation("java.lang.Override", methodDecl.modifiers()); // $NON-NLS-1$ if (annot != null) { ASTRewrite rewrite = ASTRewrite.create(annot.getAST()); rewrite.remove(annot, null); String label = CorrectionMessages.ModifierCorrectionSubProcessor_remove_override; Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal( label, cu, rewrite, IProposalRelevance.REMOVE_OVERRIDE, image); proposals.add(proposal); QuickAssistProcessor.getCreateInSuperClassProposals(context, methodDecl.getName(), proposals); } }
private static Annotation findExistingAnnotation(List<? extends ASTNode> modifiers) { for (int i = 0, len = modifiers.size(); i < len; i++) { Object curr = modifiers.get(i); if (curr instanceof NormalAnnotation || curr instanceof SingleMemberAnnotation) { Annotation annotation = (Annotation) curr; ITypeBinding typeBinding = annotation.resolveTypeBinding(); if (typeBinding != null) { if ("java.lang.SuppressWarnings" .equals(typeBinding.getQualifiedName())) { // $NON-NLS-1$ return annotation; } } else { String fullyQualifiedName = annotation.getTypeName().getFullyQualifiedName(); if ("SuppressWarnings".equals(fullyQualifiedName) || "java.lang.SuppressWarnings" .equals(fullyQualifiedName)) { // $NON-NLS-1$ //$NON-NLS-2$ return annotation; } } } } return null; }
/** * Finds an annotation of the given type (as a fully-qualified name) on a * declaration (type, method, field, etc.). If no such annotation exists, * returns <code>null</code>. */ @SuppressWarnings("unchecked") public static Annotation findAnnotation(BodyDeclaration decl, String annotationTypeName) { if (annotationTypeName == null) { throw new IllegalArgumentException("annotationTypeName cannot be null"); } List<ASTNode> modifiers = (List<ASTNode>) decl.getStructuralProperty(decl.getModifiersProperty()); for (ASTNode modifier : modifiers) { if (modifier instanceof Annotation) { Annotation annotation = (Annotation) modifier; String typeName = getAnnotationTypeName(annotation); if (annotationTypeName.equals(typeName)) { return annotation; } } } return null; }
@SuppressWarnings("unchecked") private void validateUiHandlerFieldExistenceInUiXml( MethodDeclaration uiHandlerDecl) { Annotation annotation = JavaASTUtils.findAnnotation(uiHandlerDecl, UiBinderConstants.UI_HANDLER_TYPE_NAME); if (annotation instanceof SingleMemberAnnotation) { SingleMemberAnnotation uiHandlerAnnotation = (SingleMemberAnnotation) annotation; Expression exp = uiHandlerAnnotation.getValue(); if (exp instanceof StringLiteral) { validateFieldExistenceInUiXml( (TypeDeclaration) uiHandlerDecl.getParent(), exp, ((StringLiteral) exp).getLiteralValue()); } else if (exp instanceof ArrayInitializer) { for (Expression element : (List<Expression>) ((ArrayInitializer) exp).expressions()) { if (element instanceof StringLiteral) { validateFieldExistenceInUiXml( (TypeDeclaration) uiHandlerDecl.getParent(), element, ((StringLiteral) element).getLiteralValue()); } } } } }
private static boolean isSourceAnnotation(ASTNode node) { if (node instanceof Annotation) { Annotation annotation = (Annotation) node; String typeName = annotation.getTypeName().getFullyQualifiedName(); // Annotation can be used with its fully-qualified name if (typeName.equals(ClientBundleUtilities.CLIENT_BUNDLE_SOURCE_ANNOTATION_NAME)) { return true; } // Simple name is fine, too String sourceAnnotationSimpleName = Signature.getSimpleName(ClientBundleUtilities.CLIENT_BUNDLE_SOURCE_ANNOTATION_NAME); if (typeName.equals(sourceAnnotationSimpleName)) { return true; } } return false; }
@SuppressWarnings("unchecked") private void validateSourceAnnotationValues(Annotation annotation) throws JavaModelException { Expression exp = JavaASTUtils.getAnnotationValue(annotation); if (exp == null) { return; } // There will usually just be one string value if (exp instanceof StringLiteral) { validateSourceAnnotationValue((StringLiteral) exp); } // But there could be multiple values; if so, check each one. if (exp instanceof ArrayInitializer) { ArrayInitializer array = (ArrayInitializer) exp; for (Expression item : (List<Expression>) array.expressions()) { if (item instanceof StringLiteral) { validateSourceAnnotationValue((StringLiteral) item); } } } }
/** * @param e * @return int * Checks.IS_RVALUE if e is an rvalue * Checks.IS_RVALUE_GUESSED if e is guessed as an rvalue * Checks.NOT_RVALUE_VOID if e is not an rvalue because its type is void * Checks.NOT_RVALUE_MISC if e is not an rvalue for some other reason */ public static int checkExpressionIsRValue(Expression e) { if (e instanceof Name) { if(!(((Name) e).resolveBinding() instanceof IVariableBinding)) { return NOT_RVALUE_MISC; } } if (e instanceof Annotation) return NOT_RVALUE_MISC; ITypeBinding tb= e.resolveTypeBinding(); boolean guessingRequired= false; if (tb == null) { guessingRequired= true; tb= ASTResolving.guessBindingForReference(e); } if (tb == null) return NOT_RVALUE_MISC; else if (tb.getName().equals("void")) //$NON-NLS-1$ return NOT_RVALUE_VOID; return guessingRequired ? IS_RVALUE_GUESSED : IS_RVALUE; }
/** * Returns the topmost ancestor of <code>node</code> that is a {@link Type} (but not a {@link UnionType}). * <p> * <b>Note:</b> The returned node often resolves to a different binding than the given <code>node</code>! * * @param node the starting node, can be <code>null</code> * @return the topmost type or <code>null</code> if the node is not a descendant of a type node * @see #getNormalizedNode(ASTNode) */ public static Type getTopMostType(ASTNode node) { ASTNode result= null; while (node instanceof Type && !(node instanceof UnionType) || node instanceof Name || node instanceof Annotation || node instanceof MemberValuePair || node instanceof Expression) { // Expression could maybe be reduced to expression node types that can appear in an annotation result= node; node= node.getParent(); } if (result instanceof Type) return (Type) result; return null; }
private static boolean hasNullAnnotation(MethodDeclaration decl) { List<IExtendedModifier> modifiers= decl.modifiers(); String nonnull= NullAnnotationsFix.getNonNullAnnotationName(decl.resolveBinding().getJavaElement(), false); String nullable= NullAnnotationsFix.getNullableAnnotationName(decl.resolveBinding().getJavaElement(), false); for (Object mod : modifiers) { if (mod instanceof Annotation) { Name annotationName= ((Annotation) mod).getTypeName(); String fullyQualifiedName= annotationName.getFullyQualifiedName(); if (annotationName.isSimpleName() ? nonnull.endsWith(fullyQualifiedName) : fullyQualifiedName.equals(nonnull)) return true; if (annotationName.isSimpleName() ? nullable.endsWith(fullyQualifiedName) : fullyQualifiedName.equals(nullable)) return true; } } return false; }
/** * Resolves the selected nodes and returns <code>true</code> if the node or any of its ancestors * is of type <code>Annotation</code>, <code>false</code> otherwise. * * @return <code>true</code> if the node or any of its ancestors is of type * <code>Annotation</code>, <code>false</code> otherwise * @since 3.7 */ public boolean resolveInAnnotation() { if (fInAnnotationRequested) return fInAnnotation; fInAnnotationRequested= true; resolveSelectedNodes(); ASTNode node= getStartNode(); while (node != null) { if (node instanceof Annotation) { fInAnnotation= true; break; } node= node.getParent(); } return fInAnnotation; }
public static void removeOverrideAnnotationProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (!(selectedNode instanceof MethodDeclaration)) { return; } MethodDeclaration methodDecl= (MethodDeclaration) selectedNode; Annotation annot= findAnnotation("java.lang.Override", methodDecl.modifiers()); //$NON-NLS-1$ if (annot != null) { ASTRewrite rewrite= ASTRewrite.create(annot.getAST()); rewrite.remove(annot, null); String label= CorrectionMessages.ModifierCorrectionSubProcessor_remove_override; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.REMOVE_OVERRIDE, image); proposals.add(proposal); QuickAssistProcessor.getCreateInSuperClassProposals(context, methodDecl.getName(), proposals); } }
private static Annotation findExistingAnnotation(List<? extends ASTNode> modifiers) { for (int i= 0, len= modifiers.size(); i < len; i++) { Object curr= modifiers.get(i); if (curr instanceof NormalAnnotation || curr instanceof SingleMemberAnnotation) { Annotation annotation= (Annotation) curr; ITypeBinding typeBinding= annotation.resolveTypeBinding(); if (typeBinding != null) { if ("java.lang.SuppressWarnings".equals(typeBinding.getQualifiedName())) { //$NON-NLS-1$ return annotation; } } else { String fullyQualifiedName= annotation.getTypeName().getFullyQualifiedName(); if ("SuppressWarnings".equals(fullyQualifiedName) || "java.lang.SuppressWarnings".equals(fullyQualifiedName)) { //$NON-NLS-1$ //$NON-NLS-2$ return annotation; } } } } return null; }
/** * Creates the method annotations and comments of the extracted methods in * the source type. * * @param sourceRewrite * the source compilation unit rewrite * @param replacements * the set of variable binding keys of formal parameters which * must be replaced * @throws CoreException * if an error occurs */ protected final void createMethodComments(final CompilationUnitRewrite sourceRewrite, final Set<String> replacements) throws CoreException { Assert.isNotNull(sourceRewrite); Assert.isNotNull(replacements); if (fMembers.length > 0 && (fAnnotations || fComments)) { IJavaProject project= fSubType.getJavaProject(); boolean annotations= fAnnotations && !JavaModelUtil.isVersionLessThan(project.getOption(JavaCore.COMPILER_SOURCE, true), JavaCore.VERSION_1_6); boolean javadoc= project.getOption(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, true).equals(JavaCore.ENABLED); IMember member= null; for (int index= 0; index < fMembers.length; index++) { member= fMembers[index]; if (member instanceof IMethod) { MethodDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode((IMethod) member, sourceRewrite.getRoot()); if (annotations) { ASTRewrite rewrite= sourceRewrite.getASTRewrite(); AST ast= rewrite.getAST(); Annotation marker= ast.newMarkerAnnotation(); marker.setTypeName(ast.newSimpleName("Override")); //$NON-NLS-1$ rewrite.getListRewrite(declaration, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(marker, null); } if (fComments) createMethodComment(sourceRewrite, declaration, replacements, javadoc); } } } }
@Override public boolean visit(PackageDeclaration node) { if (node.getAST().apiLevel() >= JLS3) { if (node.getJavadoc() != null) { node.getJavadoc().accept(this); } for (Iterator<Annotation> it= node.annotations().iterator(); it.hasNext();) { Annotation p= it.next(); p.accept(this); this.fBuffer.append(" ");//$NON-NLS-1$ } } this.fBuffer.append("package ");//$NON-NLS-1$ node.getName().accept(this); this.fBuffer.append(";");//$NON-NLS-1$ return false; }
public static void removeOverrideAnnotationProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (!(selectedNode instanceof MethodDeclaration)) { return; } MethodDeclaration methodDecl= (MethodDeclaration) selectedNode; Annotation annot= findAnnotation("java.lang.Override", methodDecl.modifiers()); //$NON-NLS-1$ if (annot != null) { ASTRewrite rewrite= ASTRewrite.create(annot.getAST()); rewrite.remove(annot, null); String label= CorrectionMessages.ModifierCorrectionSubProcessor_remove_override; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image); proposals.add(proposal); QuickAssistProcessor.getCreateInSuperClassProposals(context, methodDecl.getName(), proposals); } }
private static boolean hasNullAnnotation(MethodDeclaration decl) { List<IExtendedModifier> modifiers= decl.modifiers(); String nonnull= NullQuickFixes.getNonNullAnnotationName(decl.resolveBinding().getJavaElement(), false); String nullable= NullQuickFixes.getNullableAnnotationName(decl.resolveBinding().getJavaElement(), false); for (Object mod : modifiers) { if (mod instanceof Annotation) { Name annotationName= ((Annotation) mod).getTypeName(); String fullyQualifiedName= annotationName.getFullyQualifiedName(); if (annotationName.isSimpleName() ? nonnull.endsWith(fullyQualifiedName) : fullyQualifiedName.equals(nonnull)) return true; if (annotationName.isSimpleName() ? nullable.endsWith(fullyQualifiedName) : fullyQualifiedName.equals(nullable)) return true; } } return false; }
public boolean visit(PackageDeclaration node) { if (node.getAST().apiLevel() >= JLS3) { if (node.getJavadoc() != null) { node.getJavadoc().accept(this); } for (Iterator it = node.annotations().iterator(); it.hasNext(); ) { Annotation p = (Annotation) it.next(); p.accept(this); this.buffer.append(" ");//$NON-NLS-1$ } } printIndent(); this.buffer.append("package ");//$NON-NLS-1$ node.getName().accept(this); this.buffer.append(";\n");//$NON-NLS-1$ return false; }
/** * Processes the annotation to replace its name by FQN * * @param node * @return */ private boolean visitAnnotation(Annotation node) { if (node.getTypeName().isSimpleName()) { ITypeBinding resolvedBinding = node.resolveTypeBinding(); if (resolvedBinding != null) { String qualifiedName = null; if (resolvedBinding.isParameterizedType()) { ITypeBinding erasure = resolvedBinding.getErasure(); if (erasure != null && !erasure.isRecovered()) { qualifiedName = erasure.getQualifiedName(); } } else if (!resolvedBinding.isRecovered()) { qualifiedName = resolvedBinding.getQualifiedName(); } if (qualifiedName != null) { node.setTypeName(node.getAST().newName(qualifiedName)); this.modified = true; } } } return true; }
/** * Return true if the annotation content matches the input map (@Foo(f1 = v1 * , f2 = v2) * * @param annotation * input annotation to check * @param content * a Map object containing as key the expected member name and as * value the expected member value * @return true if the annotation is a normal annotation and if the content * matches the content parameter, false otherwise */ @SuppressWarnings("unchecked") public static boolean checkAnnotationContent(Annotation annotation, Map<String, Object> content) { boolean correct = false; // Test if this annotation is a Normal Member Annotation if (annotation != null && annotation.isNormalAnnotation()) { List<MemberValuePair> values = ((NormalAnnotation) annotation).values(); correct = true; for (int inc = 0; inc < values.size() && correct; inc++) { MemberValuePair mvp = values.get(inc); String memberName = mvp.getName().getFullyQualifiedName(); Object contentValue = content.get(memberName); correct = contentValue != null; Expression memberValue = mvp.getValue(); correct = checkSingleAnnotationValue(memberValue, contentValue); } } return correct; }
/** * Return an Annotation instance used on this body declaration */ public static Annotation getAnnotation(String annotationName, BodyDeclaration bodyDeclaration) { List<?> modifiers = bodyDeclaration.modifiers(); // Test if this MethodDeclaration contains modifiers if (modifiers != null) { Iterator<?> modifiersIterator = modifiers.iterator(); while (modifiersIterator.hasNext()) { IExtendedModifier modifier = (IExtendedModifier) modifiersIterator .next(); if (modifier.isAnnotation()) { Annotation a = (Annotation) modifier; String annotationType = a.getTypeName().toString(); if (annotationType.endsWith(annotationName)) { return a; } } } } return null; }
/** * Return the hashCode of a Body Declaration (from @Generated annotation) */ public static int getHashCodeFromGeneratedAnnotation(BodyDeclaration bodyDeclaration) { Annotation generatedAnnotation = ASTHelper.getAnnotation(JavaCodeHelper.GENERATED_SIMPLECLASSNAME, bodyDeclaration); if (generatedAnnotation == null) { // @Generated not found, the BodyDeclaration must not be merged throw new UnsupportedOperationException(); } if (generatedAnnotation.isNormalAnnotation()) { String stringHashcode = GeneratedAnnotationHelper.getGeneratedAnnotationHashcode((NormalAnnotation) generatedAnnotation); if(stringHashcode != null) { try { return Integer.parseInt(stringHashcode); } catch (NumberFormatException e) { Activator.getDefault().logError("Hashcode can't be parsed to int in: \n" + bodyDeclaration.toString(), e); return -1; } } } // If the hashCode cannot be found, throw an IllegalArgumentException throw new IllegalArgumentException(); }
public boolean visitAnnotation(Annotation node) { addType( node.resolveTypeBinding(), node.getTypeName().getFullyQualifiedName(), node.getStartPosition()); return true; }
@Override public Optional<Annotation> applicable(Object astNode) { if (astNode instanceof FieldDeclaration) { return annotatedWith(((FieldDeclaration) astNode).modifiers(), "Mock"); } else { return Optional.empty(); } }
@Override public FieldDeclaration apply(Object object, Annotation annotation) { FieldDeclaration fieldDeclaration = (FieldDeclaration) object; fieldDeclaration.modifiers().remove(annotation); fieldDeclaration.fragments().forEach(declarationFragment -> { Type clonedType = mockType(fieldDeclaration.getType()); ((VariableDeclarationFragment) declarationFragment).setInitializer(astNodeFactory .methodInvocation("Mock", singletonList(astNodeFactory.typeLiteral(clonedType)))); }); return fieldDeclaration; }
private void addThrownSupport(MethodDeclaration methodDeclaration) { Optional<Annotation> testAnnotation = annotatedWith(methodDeclaration, "Test"); Optional<Expression> expected = testAnnotation .filter(annotation -> annotation instanceof NormalAnnotation) .flatMap(this::expectedException); expected.ifPresent(expression -> body() .add(astNodeFactory().methodInvocation(THROWN, singletonList(astNodeFactory().simpleName(((TypeLiteral) expression).getType().toString()))))); }
private static Set<String> extractAnnotationTypes(List<?> modifiers) { Set<String> annotations = new HashSet<String>(); for (Object modifier : modifiers) { if (modifier instanceof Annotation) { Annotation a = (Annotation) modifier; annotations.add(a.getTypeName().toString()); } } return annotations; }
private static boolean isPureTypeAnnotation(Annotation annotation) { IAnnotationBinding binding= annotation.resolveAnnotationBinding(); if (binding == null) { return false; } IAnnotationBinding targetAnnotationBinding= findTargetAnnotation(binding.getAnnotationType().getAnnotations()); if (targetAnnotationBinding == null) { return false; } return isTypeUseOnly(targetAnnotationBinding); }