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();
}
}
}