How to verify if variable matches regex?

I checked out the Sonar-Custom-Plugin-Example project, copied the sensor and started to write my rule.
I got confused because the tree structure is missing in this example project. How would I check a field if it ends with DTO? I already found the matching regex, only need to find a way to iterate over the sourcetree.

public class NotEndOnDTOJavaFilesSensor implements Sensor {

  protected static final String DEFAULT_FORMAT_VALUE = ".*(?<!(dto|DTO))$";

  @Override
  public void describe(SensorDescriptor descriptor) {
    descriptor.name("Field Name is not allowed to contain DTO");

    // optimisation to disable execution of sensor if project does
    // not contain Java files or if the example rule is not activated
    // in the Quality profile
    descriptor.onlyOnLanguage("java");
    descriptor.createIssuesForRuleRepositories(JavaRulesDefinition.REPOSITORY);
  }

  @Override
  public void execute(SensorContext context) {
    FileSystem fs = context.fileSystem();
    Iterable<InputFile> javaFiles = fs.inputFiles(fs.predicates().hasLanguage("java"));
    for (InputFile javaFile : javaFiles) {
      // no need to define the severity as it is automatically set according
      // to the configured Quality profile
      NewIssue newIssue = context.newIssue()
        .forRule(JavaRulesDefinition.MY_DTO_RULE);

      NewIssueLocation primaryLocation = newIssue.newLocation()
        .on(javaFile)
        // here
        .message("Field Name is not allowed to contain DTO!");
      newIssue.at(primaryLocation);
      newIssue.save();
    }
  }
}

Hello @rpolito

If I understand correctly your situation, you should probably have a look at Java Custom Rules:

  • CUSTOM RULES 101 is the go-to guide when starting to implement custom rules for Java, it is regularly updated.
  • Example project.
  • For rules implementation examples, you can directly look into the rules of the Java analyzer itself, it contains hundreds of examples (just make sure to use only what is provided in the public API).

Hope it helps,
Quentin