View Javadoc
1   /*
2    * SPDX-License-Identifier: Apache-2.0
3    * See LICENSE file for details.
4    *
5    * Copyright 2005-2026 the original author or authors.
6    */
7   package com.github.spotbugs;
8   
9   import com.github.javaparser.ParseProblemException;
10  import com.github.javaparser.StaticJavaParser;
11  import com.github.javaparser.ast.CompilationUnit;
12  import com.github.javaparser.ast.body.MethodDeclaration;
13  
14  import java.io.IOException;
15  import java.nio.charset.StandardCharsets;
16  import java.nio.file.Files;
17  import java.nio.file.Path;
18  import java.util.Set;
19  import java.util.stream.Stream;
20  
21  import org.slf4j.Logger;
22  import org.slf4j.LoggerFactory;
23  
24  /**
25   * The Class StubOverrideFixer.
26   */
27  public class StubOverrideFixer {
28  
29      /** The logger. */
30      private static final Logger logger = LoggerFactory.getLogger(StubOverrideFixer.class);
31  
32      /** The Constant GROOVY_METHODS. */
33      private static final Set<String> GROOVY_METHODS = Set.of("getMetaClass", "setMetaClass", "invokeMethod",
34              "getProperty", "setProperty");
35  
36      /**
37       * The main method.
38       *
39       * @param args the arguments
40       * @throws IOException Signals that an I/O exception has occurred.
41       */
42      public static void main(String[] args) throws IOException {
43          Path stubsDir = Path.of(args[0]);
44          try (Stream<Path> stream = Files.walk(stubsDir)) {
45              stream.filter(p -> p.toString().endsWith(".java")).forEach(StubOverrideFixer::processStub);
46          }
47      }
48  
49      /**
50       * Process stub.
51       *
52       * @param filePath the file path
53       */
54      private static void processStub(Path filePath) {
55          try {
56              CompilationUnit cu = StaticJavaParser.parse(filePath);
57  
58              cu.findAll(MethodDeclaration.class).forEach(method -> {
59                  if (shouldHaveOverride(method)) {
60                      method.addAnnotation("java.lang.Override");
61                  }
62              });
63  
64              Files.write(filePath, cu.toString().getBytes(StandardCharsets.UTF_8));
65          } catch (IOException | ParseProblemException e) {
66              logger.error("Error processing: {} - {}", filePath, e.getMessage());
67          }
68      }
69  
70      /**
71       * Should have override.
72       *
73       * @param method the method
74       * @return true, if successful
75       */
76      private static boolean shouldHaveOverride(MethodDeclaration method) {
77          return GROOVY_METHODS.contains(method.getNameAsString());
78      }
79  
80  }