0

What I want to do

I am trying to add a comment on the generated field declaration by Lombok like this:

@lombok.Generated
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SomeController.class);

To tell Parasoft Jtest to suppress the reporting of findings, I added a comment like this with JavaParser:

/* parasoft suppress item * class ClassName line 21 */
@lombok.Generated
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SomeController.class);

What I tried

To add this comment, I wrote a Java program with JavaParser like this:

public static void main(String[] args) throws IOException {
    Log.setAdapter(new Log.StandardOutStandardErrorAdapter());

    Path inPath = Paths.get("/path/to/input/source");
    SourceRoot sourceRoot = new SourceRoot(inPath);
    List<ParseResult<CompilationUnit>> p = sourceRoot.tryToParseParallelized();

    Iterator<ParseResult<CompilationUnit>> it = p.iterator();
    while (it.hasNext()) {
        ParseResult<CompilationUnit> pr = it.next();
        pr.getResult().ifPresent(cu -> {
            cu.accept(new ModifierVisitor<Void>() {
                @Override
                public Visitable visit(FieldDeclaration n, Void arg) {
                    List<MarkerAnnotationExpr> list = n.findAll(MarkerAnnotationExpr.class);
                    Iterator<MarkerAnnotationExpr> it = list.iterator();
                    while (it.hasNext()) {
                        MarkerAnnotationExpr ann = it.next();
                        if (ann.getNameAsString().equals("lombok.Generated") || ann.getNameAsString().equals("Generated")) {
                            // Suppress all findings at the line of field declaration
                            n.setBlockComment(String.format(" parasoft suppress item * class %s line %d ", "ClassName", n.getEnd().get().line));
                        }
                    }
                    return super.visit(n, arg);
                }
            }, null);
        });
    }
    Path outPath = Paths.get("/path/to/output/source");
    sourceRoot.saveAll(outPath);
}

Problem

I have successfully added the comment to the target fields. But on the same file, all line comments on field declarations move to the middle of the field declaration like this:

Input

@Autowired
HttpSession session; // line comment

Output

@Autowired
HttpSession // line comment
session;

Because of this, the line number from Node#getEnd().get().line changes after the addition of the parasoft suppress comment. It makes the parasoft suppress comment doesn't work properly.

Question

How can I prepend to move a line comment to the middle of the field declaration with JavaParser ModifierVisitor?

SATO Yusuke
  • 1,600
  • 15
  • 39

0 Answers0