com.github.javaparser.ast.comments.Comment Java Examples

The following examples show how to use com.github.javaparser.ast.comments.Comment. 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: CodeValidator.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static boolean containsModifiedComments(CompilationUnit originalCU, CompilationUnit mutatedCU) {
    // We assume getAllContainedComments() preserves the order of comments
    Comment[] originalComments = originalCU.getAllContainedComments().toArray(new Comment[] {});
    Comment[] mutatedComments = mutatedCU.getAllContainedComments().toArray(new Comment[] {});
    if (originalComments.length != mutatedComments.length) {
        // added comments triggers validation
        return true;
    }
    // We cannot use equality here because inserting empty lines will change the lineStart attribute of the Comment node.
    for (int i = 0; i < originalComments.length; i++) {
        // Somehow the mutated comments contain char(13) '\r' in addition to '\n'
        // TODO Where those come from? CodeMirror?
        if ( ! originalComments[i].toString().replaceAll("\\r","").equals(mutatedComments[i].toString().replaceAll("\\r","")) ) {
            return true;
        }
    }

    return false;
}
 
Example #2
Source File: ASTHelper.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String getAllCommentsText(BodyDeclaration declaration) {
    List<Comment> allContainedComments = declaration.getAllContainedComments();
    StringBuffer sb = new StringBuffer();
    boolean append =false;
    Optional<Comment> commentOp = declaration.getComment();
    if (commentOp.isPresent()){
        sb.append(commentOp.get().getContent()) ;
        append=true;
    }
    for (Comment comment : allContainedComments) {
        if (append){
            sb.append(" ");
        }
        sb.append(comment.toString());
        append=true;
    }
    String oldCommentText = sb.toString();
    return oldCommentText;
}
 
Example #3
Source File: JavaClassSyncHandler.java    From jeddict with Apache License 2.0 6 votes vote down vote up
private void syncHeader(Comment comment) {
    String value = comment.toString();
    if (javaClass.getRootElement()
            .getSnippets(BEFORE_PACKAGE)
            .stream()
            .filter(snip -> {
                Optional<CompilationUnit> parsed = new JavaParser().parse(snip.getValue()).getResult();
                return (parsed.isPresent()&& compareNonWhitespaces(parsed.get().toString(), value))
                        || compareNonWhitespaces(snip.getValue(), value);
            })
            .findAny()
            .isPresent()) {
        return;
    }
    if (javaClass.getSnippets(BEFORE_PACKAGE)
            .stream()
            .filter(snip -> compareNonWhitespaces(snip.getValue(), value))
            .findAny()
            .isPresent()) {
        return;
    }
    javaClass.addRuntimeSnippet(new ClassSnippet(value, BEFORE_PACKAGE));
}
 
Example #4
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
private void printOrphanCommentsEnding(final Node node) {
    List<Node> everything = new LinkedList<>();
    everything.addAll(node.getChildNodes());
    sortByBeginPosition(everything);
    if (everything.isEmpty()) {
        return;
    }

    int commentsAtEnd = 0;
    boolean findingComments = true;
    while (findingComments && commentsAtEnd < everything.size()) {
        Node last = everything.get(everything.size() - 1 - commentsAtEnd);
        findingComments = (last instanceof Comment);
        if (findingComments) {
            commentsAtEnd++;
        }
    }
    for (int i = 0; i < commentsAtEnd; i++) {
        everything.get(everything.size() - commentsAtEnd + i).accept(this, null);
    }
}
 
Example #5
Source File: JavaSourceUtils.java    From dolphin with Apache License 2.0 6 votes vote down vote up
public static String mergeContent(CompilationUnit one, CompilationUnit two) throws Exception {

        // 包声明不同,返回null
        if (!one.getPackage().equals(two.getPackage())) return null;

        CompilationUnit cu = new CompilationUnit();

        // add package declaration to the compilation unit
        PackageDeclaration pd = new PackageDeclaration();
        pd.setName(one.getPackage().getName());
        cu.setPackage(pd);

        // check and merge file comment;
        Comment fileComment = mergeSelective(one.getComment(), two.getComment());
        cu.setComment(fileComment);

        // check and merge imports
        List<ImportDeclaration> ids = mergeListNoDuplicate(one.getImports(), two.getImports());
        cu.setImports(ids);

        // check and merge Types
        List<TypeDeclaration> types = mergeTypes(one.getTypes(), two.getTypes());
        cu.setTypes(types);

        return cu.toString();
    }
 
Example #6
Source File: SourceCodeProcessHandler.java    From molicode with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(FieldDeclaration n, Void arg) {
    if (n.isFinal() || n.isStatic()) {
        return;
    }
    NodeList<VariableDeclarator> nodeList = n.getVariables();
    for (VariableDeclarator declarator : nodeList) {
        FieldInfoDto fieldInfoDto = new FieldInfoDto();
        fieldInfoDto.setDataName(declarator.getNameAsString());
        fieldInfoDto.setFieldClass(declarator.getType().asString());

        Optional<Comment> commentOptional = n.getComment();
        if (commentOptional.isPresent()) {
            String commentContent = commentOptional.get().getContent();
            commentContent = commentContent.replaceAll("\\*", "");
            fieldInfoDto.setComment(commentContent.trim());
        } else {
            fieldInfoDto.setComment(fieldInfoDto.getDataName());
        }
        sourceCodeDto.addField(fieldInfoDto);
    }
    sourceCodeDto.addFieldDeclaration(n);
    super.visit(n, arg);
}
 
Example #7
Source File: JavaMethodParser.java    From Siamese with GNU General Public License v3.0 5 votes vote down vote up
private String retrieveComments(Node n) {
    // retrieve the comments separately
    String commentStr;
    List<Comment> comments = n.getAllContainedComments();
    commentStr = concatComments(comments);
    commentStr += concatComments(n.getOrphanComments());
    if (n.getComment().isPresent()) {
        commentStr += "/**" + n.getComment().get().getContent() + "*/";
    }
    return commentStr;
}
 
Example #8
Source File: JavaParsingAtomicQueueGenerator.java    From JCTools with Apache License 2.0 5 votes vote down vote up
protected boolean isCommentPresent(Node node, String wanted) {
    Optional<Comment> maybeComment = node.getComment();
    if (maybeComment.isPresent()) {
        Comment comment = maybeComment.get();
        String content = comment.getContent().trim();
        if (wanted.equals(content)) {
            return true;
        }
    }
    return false;
}
 
Example #9
Source File: AnnotatedMember.java    From jeddict with Apache License 2.0 5 votes vote down vote up
static Stream<AnnotationExplorer> getAnnotationAttributes(AnnotationExpr annotationExpr, String attributeName) {
    Stream<AnnotationExplorer> annotations = Stream.of();
    Optional<Expression> expressionOpt = getAttribute(annotationExpr, attributeName);
    if (expressionOpt.isPresent()) {
        Expression expression = expressionOpt.get();
        if (expression.isAnnotationExpr()) {
            annotations = expressionOpt
                    .map(exp -> exp.asAnnotationExpr())
                    .map(AnnotationExplorer::new)
                    .map(exp -> Stream.of(exp))
                    .orElse(Stream.of());
        } else if (expression.isArrayInitializerExpr()) {
            List<AnnotationExplorer> values = new ArrayList<>();
            List<Node> nodes = expression.asArrayInitializerExpr().getChildNodes();
            for (Node node : nodes) {
                if (node instanceof AnnotationExpr) {
                    AnnotationExplorer annotation = new AnnotationExplorer((AnnotationExpr) node);
                    values.add(annotation);
                } else if (node instanceof Comment) {
                    //ignore
                } else {
                    throw new UnsupportedOperationException();
                }
            }
            annotations = values.stream();
        } else {
            throw new UnsupportedOperationException();
        }

    }
    return annotations;
}
 
Example #10
Source File: JavaClassSyncHandler.java    From jeddict with Apache License 2.0 5 votes vote down vote up
private void syncJavadoc(Comment comment) {
    String value = comment.toString();
    if (javaClass.getRootElement()
            .getSnippets(TYPE_JAVADOC)
            .stream()
            .filter(snip -> compareNonWhitespaces(snip.getValue(), value))
            .findAny()
            .isPresent()) {
        return;
    }
    if (javaClass.getSnippets(TYPE_JAVADOC)
            .stream()
            .filter(snip -> compareNonWhitespaces(snip.getValue(), value))
            .findAny()
            .isPresent()) {
        return;
    }
    if (javaClass.getRootElement()
            .getSnippets(BEFORE_CLASS)
            .stream()
            .filter(snip -> compareNonWhitespaces(snip.getValue(), value))
            .findAny()
            .isPresent()) {
        return;
    }
    if (javaClass.getSnippets(BEFORE_CLASS)
            .stream()
            .filter(snip -> compareNonWhitespaces(snip.getValue(), value))
            .findAny()
            .isPresent()) {
        return;
    }
    if (javaClass.getDescription() == null || !value.contains(javaClass.getDescription())) {
        javaClass.addRuntimeSnippet(new ClassSnippet(value, TYPE_JAVADOC));
    }
}
 
Example #11
Source File: AttributeSyncHandler.java    From jeddict with Apache License 2.0 5 votes vote down vote up
private void syncJavadoc(Optional<Comment> commentOpt, AttributeSnippetLocationType locationType) {
    if (commentOpt.isPresent()
            && attribute.getSnippets(locationType).isEmpty()
            && attribute.getJavaClass().getSnippets().isEmpty()) {
        Comment comment = commentOpt.get();
        AttributeSnippet attributeSnippet = new AttributeSnippet();
        attributeSnippet.setLocationType(locationType);
        attributeSnippet.setValue(String.format("%" + comment.getBegin().get().column + "s%s", "", comment.toString()));
        if (attribute.getDescription() == null
                || !attributeSnippet.getValue().contains(attribute.getDescription())) {
            attribute.addRuntimeSnippet(attributeSnippet);
        }
    }
}
 
Example #12
Source File: AbstractMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
protected <T extends Node> void mergeOrphanComments(T first, T second, T third) {
  List<Comment> comments = mergeCollections(first.getOrphanComments(), second.getOrphanComments());
  if (comments != null && !comments.isEmpty()) {
    for (Comment comment : comments) {
      third.addOrphanComment(comment);
    }
  }
}
 
Example #13
Source File: JavaDocParserVisitor.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(MethodDeclaration method, Void arg) {
    method.getComment()
            .filter(Comment::isJavadocComment)
            .map(this::toJavaDoc)
            .ifPresent(c -> recordMethodComment(c, method));
    super.visit(method, arg);
}
 
Example #14
Source File: JavaDocParserVisitor.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(FieldDeclaration field, Void arg) {
    field.getComment()
            .filter(Comment::isJavadocComment)
            .map(this::toJavaDoc)
            .ifPresent(c -> createFieldComment(c, field));
    super.visit(field, arg);
}
 
Example #15
Source File: JavaDocParserVisitor.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration classOrInterface, Void arg) {
    className = calculateClassName(classOrInterface);

    classOrInterface.getComment()
            .filter(Comment::isJavadocComment)
            .map(this::toJavaDoc)
            .ifPresent(this::recordClassComment);

    super.visit(classOrInterface, arg);
}
 
Example #16
Source File: JavaMethodParser.java    From Siamese with GNU General Public License v3.0 5 votes vote down vote up
private String concatComments(List<Comment> comments) {
    String com = "";
    for (Comment c: comments) {
        com += "/*" + c.getContent() + "*/";
    }
    return com;
}
 
Example #17
Source File: ImpSort.java    From impsort-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static void convertAndAddImport(LinkedHashSet<Import> allImports, List<Node> thisImport,
    String eol) {
  boolean isStatic = false;
  String importItem = null;
  String prefix = "";
  String suffix = "";
  for (Node n : thisImport) {
    if (n instanceof Comment) {
      if (importItem == null) {
        prefix += n.toString();
      } else {
        suffix += n.toString();
      }
    }
    if (n instanceof ImportDeclaration) {
      ImportDeclaration i = (ImportDeclaration) n;
      isStatic = i.isStatic();
      importItem = i.getName().asString() + (i.isAsterisk() ? ".*" : "");
    }
  }
  suffix = suffix.trim();
  if (!suffix.isEmpty()) {
    suffix = " " + suffix;
  }
  Import imp = new Import(isStatic, importItem, prefix.trim(), suffix, eol);
  Iterator<Import> iter = allImports.iterator();
  // this de-duplication can probably be made more efficient by doing it all at the end
  while (iter.hasNext()) {
    Import candidate = iter.next(); // potential duplicate
    if (candidate.isDuplicatedBy(imp)) {
      iter.remove();
      imp = candidate.combineWith(imp);
    }
  }
  allImports.add(imp);
}
 
Example #18
Source File: ImpSort.java    From impsort-maven-plugin with Apache License 2.0 5 votes vote down vote up
private static Set<Import> convertImportSection(List<Node> importSectionNodes, String eol) {
  List<Comment> recentComments = new ArrayList<>();
  LinkedHashSet<Import> allImports = new LinkedHashSet<>(importSectionNodes.size() / 2);
  for (Node node : importSectionNodes) {
    if (node instanceof Comment) {
      recentComments.add((Comment) node);
    } else if (node instanceof ImportDeclaration) {
      List<Node> thisImport = new ArrayList<>(2);
      ImportDeclaration impDecl = (ImportDeclaration) node;
      thisImport.addAll(recentComments);

      Optional<Comment> impComment = impDecl.getComment();
      if (impComment.isPresent()) {
        Comment c = impComment.get();
        if (c.getBegin().get().isBefore(impDecl.getBegin().get())) {
          thisImport.add(c);
          thisImport.add(impDecl);
        } else {
          thisImport.add(impDecl);
          thisImport.add(c);
        }
      } else {
        thisImport.add(impDecl);
      }

      recentComments.clear();
      convertAndAddImport(allImports, thisImport, eol);
    } else {
      throw new IllegalStateException("Unknown node: " + node);
    }
  }
  if (!recentComments.isEmpty()) {
    throw new IllegalStateException(
        "Unexpectedly found more orphaned comments: " + recentComments);
  }
  return allImports;
}
 
Example #19
Source File: NodeWithComment.java    From apigcc with MIT License 5 votes vote down vote up
/**
 * 解析注释
 * @param comment
 */
public void accept(Comment comment) {
    if (!comment.isJavadocComment()) {
        this.setComment(comment.getContent());
        return;
    }
    Javadoc javadoc = comment.asJavadocComment().parse();
    this.setComment(CommentHelper.getDescription(javadoc.getDescription()));

    javadoc.getBlockTags().forEach(this::parse);
}
 
Example #20
Source File: CommentHelper.java    From apigcc with MIT License 5 votes vote down vote up
/**
 * 解析属性的注释
 * @param it
 * @return
 */
public static Optional<Comment> getComment(ResolvedFieldDeclaration it) {
    if (it instanceof JavaParserFieldDeclaration) {
        FieldDeclaration wrappedNode = ((JavaParserFieldDeclaration) it).getWrappedNode();
        return wrappedNode.getComment();
    }
    if (it instanceof JavaParserClassDeclaration) {
        JavaParserClassDeclaration classDeclaration = (JavaParserClassDeclaration) it;
        return classDeclaration.getWrappedNode().getComment();
    }
    return Optional.empty();
}
 
Example #21
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
private void printOrphanCommentsBeforeThisChildNode(final Node node) {
    if (node instanceof Comment) return;

    Node parent = node.getParentNode().orElse(null);
    if (parent == null) return;
    List<Node> everything = new LinkedList<>();
    everything.addAll(parent.getChildNodes());
    sortByBeginPosition(everything);
    int positionOfTheChild = -1;
    for (int i = 0; i < everything.size(); i++) {
        if (everything.get(i) == node) positionOfTheChild = i;
    }
    if (positionOfTheChild == -1) {
        throw new AssertionError("I am not a child of my parent.");
    }
    int positionOfPreviousChild = -1;
    for (int i = positionOfTheChild - 1; i >= 0 && positionOfPreviousChild == -1; i--) {
        if (!(everything.get(i) instanceof Comment)) positionOfPreviousChild = i;
    }
    for (int i = positionOfPreviousChild + 1; i < positionOfTheChild; i++) {
        Node nodeToPrint = everything.get(i);
        if (!(nodeToPrint instanceof Comment))
            throw new RuntimeException(
                    "Expected comment, instead " + nodeToPrint.getClass() + ". Position of previous child: "
                            + positionOfPreviousChild + ", position of child " + positionOfTheChild);
        nodeToPrint.accept(this, null);
    }
}
 
Example #22
Source File: JavaParserTest.java    From molicode with Apache License 2.0 5 votes vote down vote up
@Test
public void test(){
    CompilationUnit compilationUnit = new CompilationUnit();
    ClassOrInterfaceDeclaration myClass = compilationUnit
            .addClass("MyClass")
            .setPublic(true);
    myClass.addField(int.class, "A_CONSTANT", PUBLIC, STATIC);
    myClass.addField(String.class, "name", PRIVATE);
    Comment comment= new JavadocComment();
    comment.setContent("你大爷!");
    myClass.addMethod("helloWorld", PUBLIC).setParameters(NodeList.nodeList()).setComment(comment);
    String code = myClass.toString();
    System.out.println(code);
}
 
Example #23
Source File: SourceCodeProcessHandler.java    From molicode with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(EnumDeclaration n, Void arg) {
    sourceCodeDto.setClassName(n.getNameAsString());
    Optional<Comment> commentOptional = n.getComment();
    if (commentOptional.isPresent()) {
        sourceCodeDto.setComment(commentOptional.get().getContent());
    } else {
        sourceCodeDto.setComment(sourceCodeDto.getClassName());
    }
    super.visit(n, arg);
}
 
Example #24
Source File: SourceCodeProcessHandler.java    From molicode with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ClassOrInterfaceDeclaration n, Void arg) {
    if (!n.isPublic()) {
        return;
    }

    sourceCodeDto.setClassName(n.getNameAsString());
    Optional<Comment> commentOptional = n.getComment();
    if (commentOptional.isPresent()) {
        sourceCodeDto.setComment(commentOptional.get().getContent());
    } else {
        sourceCodeDto.setComment(sourceCodeDto.getClassName());
    }
    super.visit(n, arg);
}
 
Example #25
Source File: JavaDocParserVisitor.java    From jaxrs-analyzer with Apache License 2.0 4 votes vote down vote up
private Javadoc toJavaDoc(Comment comment) {
    return comment.asJavadocComment().parse();
}
 
Example #26
Source File: RemoveCommentedOutCode.java    From Refactoring-Bot with MIT License 4 votes vote down vote up
/**
 * This method performs the refactoring and returns a commit message.
 *
 * @param issue
 * @param gitConfig
 * @return commitMessage
 * @throws IOException
 * @throws BotRefactoringException
 */
@Override
public String performRefactoring(BotIssue issue, GitConfiguration gitConfig)
		throws IOException, BotRefactoringException {

	// Prepare data
	String path = gitConfig.getRepoFolder() + "/" + issue.getFilePath();

	line = issue.getLine();

	// Read file
	FileInputStream in = new FileInputStream(path);
	CompilationUnit compilationUnit = LexicalPreservingPrinter.setup(StaticJavaParser.parse(in));

	List<Comment> comments = compilationUnit.getAllContainedComments();

	// Keeping track of the start and end line of the commented out code to add it
	// to the output string
	int startLine = line;
	int endLine = -1;

	// Going through all comments and checking if the line matches the one we're
	// looking for
	for (Comment comment : comments) {
		if ((line >= comment.getBegin().get().line) && (line <= comment.getEnd().get().line)) {
			if (comment.isLineComment()) {
				endLine = comment.getEnd().get().line;
				comment.remove();
				// Increase the line variable to find more commented out code lines below
				line++;
			} else if (comment.isBlockComment()) {
				// The comment is a multi-line comment, so we remove the entire thing right away
				startLine = comment.getBegin().get().line;
				endLine = comment.getEnd().get().line;
				comment.remove();
				break;
			} else if (comment.isJavadocComment()) {
				throw new BotRefactoringException(
						"Found a JavaDoc comment at the indicated line. These are not removed.");
			}
		}
	}

	// We never set the endLine variable, which means we found no matching comment
	// for the indicated line
	if (endLine == -1) {
		throw new BotRefactoringException("Commented out code line could not be found"
				+ System.getProperty("line.separator") + "Are you sure that the source code and "
				+ "SonarQube analysis are on the same branch and version?");
	}

	// Printing the output file with JavaParser
	PrintWriter out = new PrintWriter(path);
	out.println(LexicalPreservingPrinter.print(compilationUnit));
	out.close();

	// Return commit message
	return ("Removed " + (endLine - startLine + 1) + " line(s) of commented out code (line " + startLine + "-"
			+ endLine + ")");
}
 
Example #27
Source File: Node.java    From apigcc with MIT License 4 votes vote down vote up
@Override
public void accept(Comment comment) {
    super.accept(comment);
    super.index().ifPresent(this::setIndex);
}
 
Example #28
Source File: PrettyPrintVisitor.java    From stategen with GNU Affero General Public License v3.0 4 votes vote down vote up
private void printJavaComment(final Optional<Comment> javacomment, final Void arg) {
    javacomment.ifPresent(c -> c.accept(this, arg));
}
 
Example #29
Source File: CompilerJarReferenceTest.java    From turin-programming-language with Apache License 2.0 4 votes vote down vote up
@Test
public void compileFunctionInstantiatingTypeFromJar() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, IOException {
    Method invoke = compileFunction("use_jar_constructor", new Class[]{String.class}, ImmutableList.of("src/test/resources/jars/javaparser-core-2.2.1.jar"));
    Comment comment = (Comment)invoke.invoke(null, "qwerty");
    assertEquals("qwerty", comment.getContent());
}
 
Example #30
Source File: CompilerJarReferenceTest.java    From turin-programming-language with Apache License 2.0 4 votes vote down vote up
@Test
public void compileFunctionUsingMethodTypeFromJar() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, IOException {
    Method invoke = compileFunction("use_jar_method", new Class[]{Comment.class}, ImmutableList.of("src/test/resources/jars/javaparser-core-2.2.1.jar"));
    Comment comment = new LineComment("qwerty");
    assertEquals("qwerty", invoke.invoke(null, comment));
}