/** * @return */ public NormalAnnotation getGraphWalkerClassAnnotation() { String source = getSource (); if(source==null) return null; ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(source.toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() { public boolean visit(NormalAnnotation node) { annotation = node; return true; } }); if (this.generateAnnotation) return annotation; return null; }
public NormalAnnotation getGeneratedClassAnnotation() { String source = getGeneratedAnnotationSource (); if(source==null) return null; ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(source.toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() { public boolean visit(NormalAnnotation node) { annotation = node; return true; } }); return annotation; }
/** * @param cu * @return */ public static String findPathGeneratorInGraphWalkerAnnotation(ICompilationUnit cu) { CompilationUnit ast = parse(cu); Map<String, String> ret = new HashMap<String, String>(); ast.accept(new ASTVisitor() { public boolean visit(MemberValuePair node) { String name = node.getName().getFullyQualifiedName(); if ("value".equals(name) && node.getParent() != null && node.getParent() instanceof NormalAnnotation) { IAnnotationBinding annoBinding = ((NormalAnnotation) node.getParent()).resolveAnnotationBinding(); String qname = annoBinding.getAnnotationType().getQualifiedName(); if (GraphWalker.class.getName().equals(qname)) { StringLiteral sl = (StringLiteral) node.getValue(); ret.put("ret", sl.getLiteralValue()); } } return true; } }); return ret.get("ret"); }
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; }
@Override protected ASTRewrite getRewrite() throws CoreException { AST ast = fAnnotation.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); createImportRewrite((CompilationUnit) fAnnotation.getRoot()); ListRewrite listRewrite; if (fAnnotation instanceof NormalAnnotation) { listRewrite = rewrite.getListRewrite(fAnnotation, NormalAnnotation.VALUES_PROPERTY); } else { NormalAnnotation newAnnotation = ast.newNormalAnnotation(); newAnnotation.setTypeName((Name) rewrite.createMoveTarget(fAnnotation.getTypeName())); rewrite.replace(fAnnotation, newAnnotation, null); listRewrite = rewrite.getListRewrite(newAnnotation, NormalAnnotation.VALUES_PROPERTY); } addMissingAtributes(fAnnotation.resolveTypeBinding(), listRewrite); return rewrite; }
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; }
@Override protected ASTRewrite getRewrite() throws CoreException { AST ast= fAnnotation.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); createImportRewrite((CompilationUnit) fAnnotation.getRoot()); ListRewrite listRewrite; if (fAnnotation instanceof NormalAnnotation) { listRewrite= rewrite.getListRewrite(fAnnotation, NormalAnnotation.VALUES_PROPERTY); } else { NormalAnnotation newAnnotation= ast.newNormalAnnotation(); newAnnotation.setTypeName((Name) rewrite.createMoveTarget(fAnnotation.getTypeName())); rewrite.replace(fAnnotation, newAnnotation, null); listRewrite= rewrite.getListRewrite(newAnnotation, NormalAnnotation.VALUES_PROPERTY); } addMissingAtributes(fAnnotation.resolveTypeBinding(), listRewrite); return rewrite; }
/** * Returns the annotations for a given <code>modifierList</code>. * * @param modifierList the modifier list to be processed * @return An ArraySet with all annotations */ @OperationMeta(returnGenerics = JavaAnnotation.class) public Set<JavaAnnotation> annotations(List<IExtendedModifier> modifierList) { List<JavaAnnotation> list = new ArrayList<JavaAnnotation>(); for (Object modifier : modifierList) { if (modifier instanceof org.eclipse.jdt.core.dom.Annotation) { org.eclipse.jdt.core.dom.Annotation annot = (org.eclipse.jdt.core.dom.Annotation) modifier; // Get annotation name and value Map<String, String> fields = new HashMap<String, String>(); // possibly the unqualified name as not resolved unless not given as qualified name! String name = annot.getTypeName().getFullyQualifiedName(); if (annot instanceof SingleMemberAnnotation) { fields.put(JavaAnnotation.DEFAULT_FIELD, toString(((SingleMemberAnnotation) modifier).getValue())); } else if (annot instanceof NormalAnnotation) { @SuppressWarnings("unchecked") List<MemberValuePair> values = ((NormalAnnotation) annot).values(); for (MemberValuePair pair : values) { fields.put(pair.getName().getIdentifier(), toString(pair.getValue())); } } list.add(new JavaAnnotation(name, fields, this)); } } return new ArraySet<JavaAnnotation>(list.toArray(new JavaAnnotation[list.size()]), JavaAnnotation.class); }
@SuppressWarnings("unchecked") public void writeSuppressWarning(BodyDeclaration target) { AST ast = target.getAST(); NormalAnnotation annotation = ast.newNormalAnnotation(); annotation.setTypeName(ast.newSimpleName(SuppressWarnings.class.getSimpleName())); MemberValuePair memberValuePair = ast.newMemberValuePair(); memberValuePair.setName(ast.newSimpleName("value")); StringLiteral stringLiteral = ast.newStringLiteral(); stringLiteral.setLiteralValue("static-access"); memberValuePair.setValue(stringLiteral); annotation.values().add(memberValuePair); target.modifiers().add(annotation); }
@SuppressWarnings("unchecked") public void writeEnumField(EnumConstantDeclaration enumField, QSpecialElement elem) { AST ast = enumField.getAST(); NormalAnnotation normalAnnotation = ast.newNormalAnnotation(); String name = new String("*" + enumField.getName()); if (elem.getValue() != null && !name.equals(elem.getValue())) { normalAnnotation.setTypeName(ast.newSimpleName(Special.class.getSimpleName())); MemberValuePair memberValuePair = ast.newMemberValuePair(); memberValuePair.setName(ast.newSimpleName("value")); StringLiteral stringLiteral = ast.newStringLiteral(); stringLiteral.setLiteralValue(elem.getValue()); memberValuePair.setValue(stringLiteral); normalAnnotation.values().add(memberValuePair); enumField.modifiers().add(normalAnnotation); } }
/** * 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; }
private static boolean setGeneratedAnnotationPart(CompilationUnit cu, NormalAnnotation annotation, String newPartValue, int rankInComment) { StringLiteral oldCommentLiteral = getGeneratedAnnotationComment(annotation); if (oldCommentLiteral != null) { String[] oldCommentParts = oldCommentLiteral.getLiteralValue().split(COMMENT_SEPARATOR); StringBuilder newCommentSB = new StringBuilder(25).append(""); for(int i = 0; i<oldCommentParts.length; i++) { if(i == rankInComment) { newCommentSB.append(newPartValue); } else { newCommentSB.append(oldCommentParts[i]); } if(i<(oldCommentParts.length-1)) { newCommentSB.append(COMMENT_SEPARATOR); } } oldCommentLiteral.setLiteralValue(newCommentSB.toString()); return true; } return false; }
private static StringLiteral getGeneratedAnnotationComment(NormalAnnotation annotation) { MemberValuePair mvp = null; for (Object o : annotation.values()) { if (o instanceof MemberValuePair) { MemberValuePair tempMVP = (MemberValuePair) o; if (COMMENTS_PARAM.equals(tempMVP.getName().toString())) { mvp = tempMVP; break; } } } if (mvp != null && mvp.getValue() != null && mvp.getValue() instanceof StringLiteral) { StringLiteral literal = (StringLiteral) mvp.getValue(); return literal; } else{ 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(); }
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()))))); }
@Override public void endVisit(NormalAnnotation node) { if (skipNode(node)) { return; } GenericSequentialFlowInfo info = processSequential(node, node.getTypeName()); process(info, node.values()); }
/** * Returns an annotation's value. If the annotation not a single-member * annotation, this is the value corresponding to the key named "value". */ @SuppressWarnings("unchecked") public static Expression getAnnotationValue(Annotation annotation) { if (annotation instanceof SingleMemberAnnotation) { return ((SingleMemberAnnotation) annotation).getValue(); } else if (annotation instanceof NormalAnnotation) { NormalAnnotation normalAnnotation = (NormalAnnotation) annotation; for (MemberValuePair pair : (List<MemberValuePair>) normalAnnotation.values()) { if (pair.getName().getIdentifier().equals("value")) { return pair.getValue(); } } } return null; }
@Override public boolean visit(NormalAnnotation node) { IAnnotationBinding resolvedAnnotationBinding = node.resolveAnnotationBinding(); processAnnotationBinding(resolvedAnnotationBinding); // Don't visit this node's children; they don't impact the result return false; }
@Override public void endVisit(NormalAnnotation node) { if (skipNode(node)) return; GenericSequentialFlowInfo info= processSequential(node, node.getTypeName()); process(info, node.values()); }
public static void addRemoveUnusedSuppressWarningProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ASTNode coveringNode= problem.getCoveringNode(context.getASTRoot()); if (!(coveringNode instanceof StringLiteral)) return; StringLiteral literal= (StringLiteral) coveringNode; if (coveringNode.getParent() instanceof MemberValuePair) { coveringNode= coveringNode.getParent(); } ASTNode parent= coveringNode.getParent(); ASTRewrite rewrite= ASTRewrite.create(coveringNode.getAST()); if (parent instanceof SingleMemberAnnotation) { rewrite.remove(parent, null); } else if (parent instanceof NormalAnnotation) { NormalAnnotation annot= (NormalAnnotation) parent; if (annot.values().size() == 1) { rewrite.remove(annot, null); } else { rewrite.remove(coveringNode, null); } } else if (parent instanceof ArrayInitializer) { rewrite.remove(coveringNode, null); } else { return; } String label= Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_remove_annotation_label, literal.getLiteralValue()); Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_ANNOTATION, image); proposals.add(proposal); }
@Override public boolean visit(NormalAnnotation anno) { if (!isInRange(anno, offset)) return false; parseAnnotation(anno); return false; }
@Override public boolean visit(NormalAnnotation node) { if (nestLevel != 1) return false; pushAnno(node); return true; }
@Override public boolean visit(NormalAnnotation node) { this.fBuffer.append("@");//$NON-NLS-1$ node.getTypeName().accept(this); this.fBuffer.append("(");//$NON-NLS-1$ for (Iterator<MemberValuePair> it= node.values().iterator(); it.hasNext();) { MemberValuePair p= it.next(); p.accept(this); if (it.hasNext()) { this.fBuffer.append(",");//$NON-NLS-1$ } } this.fBuffer.append(")");//$NON-NLS-1$ return false; }
public static void addRemoveUnusedSuppressWarningProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ASTNode coveringNode= problem.getCoveringNode(context.getASTRoot()); if (!(coveringNode instanceof StringLiteral)) return; StringLiteral literal= (StringLiteral) coveringNode; if (coveringNode.getParent() instanceof MemberValuePair) { coveringNode= coveringNode.getParent(); } ASTNode parent= coveringNode.getParent(); ASTRewrite rewrite= ASTRewrite.create(coveringNode.getAST()); if (parent instanceof SingleMemberAnnotation) { rewrite.remove(parent, null); } else if (parent instanceof NormalAnnotation) { NormalAnnotation annot= (NormalAnnotation) parent; if (annot.values().size() == 1) { rewrite.remove(annot, null); } else { rewrite.remove(coveringNode, null); } } else if (parent instanceof ArrayInitializer) { rewrite.remove(coveringNode, null); } else { return; } String label= Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_remove_annotation_label, literal.getLiteralValue()); Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image); proposals.add(proposal); }
public boolean visit(NormalAnnotation node) { this.buffer.append("@");//$NON-NLS-1$ node.getTypeName().accept(this); this.buffer.append("(");//$NON-NLS-1$ for (Iterator it = node.values().iterator(); it.hasNext(); ) { MemberValuePair p = (MemberValuePair) it.next(); p.accept(this); if (it.hasNext()) { this.buffer.append(",");//$NON-NLS-1$ } } this.buffer.append(")");//$NON-NLS-1$ return false; }
@SuppressWarnings("unchecked") public void writeProgramAnnotation(QProgram program) { QConversion conversion = program.getFacet(QConversion.class); if (conversion != null) { MarkerAnnotation conversionAnnotation = getAST().newMarkerAnnotation(); switch (conversion.getStatus()) { case POSSIBLE: break; case SUPPORTED: writeImport(Supported.class); conversionAnnotation.setTypeName(getAST().newSimpleName(Supported.class.getSimpleName())); getTarget().modifiers().add(conversionAnnotation); break; case TODO: writeImport(ToDo.class); conversionAnnotation.setTypeName(getAST().newSimpleName(ToDo.class.getSimpleName())); getTarget().modifiers().add(conversionAnnotation); break; case UNSUPPORTED: writeImport(Unsupported.class); conversionAnnotation.setTypeName(getAST().newSimpleName(Unsupported.class.getSimpleName())); getTarget().modifiers().add(conversionAnnotation); break; } } // @Program(name=) NormalAnnotation programAnnotation = getAST().newNormalAnnotation(); programAnnotation.setTypeName(getAST().newSimpleName(Program.class.getSimpleName())); MemberValuePair memberValuePair = getAST().newMemberValuePair(); memberValuePair.setName(getAST().newSimpleName("name")); StringLiteral stringLiteral = getAST().newStringLiteral(); stringLiteral.setLiteralValue(program.getName()); memberValuePair.setValue(stringLiteral); programAnnotation.values().add(memberValuePair); getTarget().modifiers().add(0, programAnnotation); }
private NormalAnnotation findAnnotation(List<?> modifiers, Class<?> annotationKlass) { for (Object modifier : modifiers) { if (modifier instanceof NormalAnnotation) { NormalAnnotation annotation = (NormalAnnotation) modifier; if (annotation.getTypeName().getFullyQualifiedName().equals(annotationKlass.getSimpleName())) return annotation; } } return null; }
/** * Checks Import Generation for Normal Annotation */ @Override public boolean visit(NormalAnnotation node) { if (node == null) return super.visit(node); ITypeBinding typeBinding = node.resolveTypeBinding(); if (typeBinding == null) return super.visit(node); Name typeName = node.getTypeName(); this.checkType(node, typeName, typeBinding); return super.visit(node); }
public static String getGeneratedAnnotationHashcode(NormalAnnotation annotation) { StringLiteral comment = getGeneratedAnnotationComment(annotation); if(comment != null) { return getGeneratedAnnotationCommentPart(comment.getLiteralValue(), HASHCODE_RANK_IN_COMMENT); } return null; }
public static String getGeneratedAnnotationUniqueId(NormalAnnotation annotation) { StringLiteral comment = getGeneratedAnnotationComment(annotation); if(comment != null) { return getGeneratedAnnotationCommentPart(comment.getLiteralValue(), UNIQUEID_RANK_IN_COMMENT); } return null; }
/** * Return the Unique ID of a Body Declaration (from @Generated annotation) */ public static String getUniqueIdFromGeneratedAnnotation(BodyDeclaration bodyDeclaration) { Annotation generatedAnnotation = ASTHelper.getAnnotation(JavaCodeHelper.GENERATED_SIMPLECLASSNAME, bodyDeclaration); if (generatedAnnotation != null && generatedAnnotation.isNormalAnnotation()) { String stringHashcode = GeneratedAnnotationHelper.getGeneratedAnnotationUniqueId((NormalAnnotation) generatedAnnotation); return stringHashcode; } // If the Unique ID cannot be found, return null return null; }
@Override public boolean visit(NormalAnnotation node) { return visitAnnotation(node); }
/** * @param file * @param info * @param monitor * @throws MalformedTreeException * @throws BadLocationException * @throws CoreException */ @SuppressWarnings("deprecation") public static void addGeneratedAnnotation(IFile file, IFile graphFile, IProgressMonitor monitor) throws MalformedTreeException, BadLocationException, CoreException { ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(file); try { String source = compilationUnit.getSource(); Document document = new Document(source); compilationUnit.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setSource(compilationUnit); parser.setResolveBindings(true); CompilationUnit astRoot = (CompilationUnit) parser.createAST(new SubProgressMonitor(monitor, 1)); astRoot.recordModifications(); final ImportRewrite importRewrite = ImportRewrite.create(astRoot, true); importRewrite.addImport("javax.annotation.Generated"); astRoot.accept(new ASTVisitor() { @SuppressWarnings("unchecked") @Override public boolean visit(TypeDeclaration node) { ASTNode copiedNode = null; // Add Generated annotation ClassExtension ce; try { ce = new ClassExtension(false, false, false, false, false, false, "", "", null, false, false, "", "", "", graphFile); NormalAnnotation annotation = ce.getGeneratedClassAnnotation(); if (annotation != null) { copiedNode = ASTNode.copySubtree(node.getAST(), annotation); node.modifiers().add(0, copiedNode); } } catch (JavaModelException e) { ResourceManager.logException(e); } return super.visit(node); } }); TextEdit rewrite = astRoot.rewrite(document, compilationUnit.getJavaProject().getOptions(true)); rewrite.apply(document); TextEdit rewriteImports = importRewrite.rewriteImports(new SubProgressMonitor(monitor, 1)); rewriteImports.apply(document); String newSource = document.get(); compilationUnit.getBuffer().setContents(newSource); compilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, new SubProgressMonitor(monitor, 1)); compilationUnit.commitWorkingCopy(false, new SubProgressMonitor(monitor, 1)); } finally { compilationUnit.discardWorkingCopy(); monitor.done(); } // WorkbenchFacade.JDTManager.reorganizeImport(compilationUnit); }
private Optional<Expression> expectedException(Annotation annotation) { return ((NormalAnnotation) annotation).values().stream() .filter(value -> ((MemberValuePair) value).getName().getFullyQualifiedName().equals("expected")) .map(value -> ((MemberValuePair) value).getValue()).findFirst(); }
@Override public boolean visit(NormalAnnotation node) { typeRefFound(node.getTypeName()); doVisitChildren(node.values()); return false; }