如何在sonarqube中扫描Java属性文件

时间:2018-11-19 14:03:30

标签: properties sonarqube rules

我正在使用SonarQube编写自定义规则来扫描属性和配置文件。 您能指导我如何编写此自定义代码吗?

1 个答案:

答案 0 :(得分:0)

有一个Java属性文件https://github.com/racodond/sonar-jproperties-plugin的插件。您可以将其派生并编写您的自定义规则。 这是一个示例规则,可以检查不允许的键和值组合

public class KeyValueCheck extends DoubleDispatchVisitorCheck {
    private static final String SIMPLE_IS_PATTERN_TEMPLATE = "(%s)";
    protected final Pattern patternKey;
    protected final Pattern patternValue;
    private final String VIOLATION_MESSAGE;
    private final boolean matches;
    boolean checkValue = false;

    public KeyValueCheck(String key, String value, String message, boolean matches) {
        VIOLATION_MESSAGE = message;
        this.matches = matches;
        this.patternKey = Pattern.compile(String.format(SIMPLE_IS_PATTERN_TEMPLATE, key), Pattern.CASE_INSENSITIVE);
        this.patternValue = Pattern.compile(String.format(SIMPLE_IS_PATTERN_TEMPLATE, value), Pattern.CASE_INSENSITIVE);
    }

    @Override
    public void visitKey(KeyTree tree) {
        Matcher matcher = patternKey.matcher(tree.text());
        if (matcher.matches()) {
            checkValue = true;
        }

        super.visitKey(tree);
    }

    @Override
    public void visitValue(ValueTree tree) {
        if (checkValue) {
            Matcher matcher = patternValue.matcher(tree.text());
            if (matches == patternValue.matcher(tree.text()).matches()) {
                addPreciseIssue(tree, VIOLATION_MESSAGE);
            }

            checkValue = false;
        }
        super.visitValue(tree);
    }
}