org.sonar.api.rules.Rule Java Examples
The following examples show how to use
org.sonar.api.rules.Rule.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PmdProfileExporterTest.java From sonar-p3c-pmd with MIT License | 6 votes |
private static List<Rule> convert(List<RulesDefinition.Rule> rules) { List<Rule> results = Lists.newArrayListWithCapacity(rules.size()); for (RulesDefinition.Rule rule : rules) { Rule newRule = Rule.create(rule.repository().key(), rule.key(), rule.name()) .setDescription(rule.htmlDescription()) .setRepositoryKey(rule.repository().key()) .setConfigKey(rule.internalKey()); if (!rule.params().isEmpty()) { List<RuleParam> ruleParams = Lists.newArrayList(); for (Param param : rule.params()) { ruleParams.add(new RuleParam().setDefaultValue(param.defaultValue()).setKey(param.name())); } newRule.setParams(ruleParams); } results.add(newRule); } return results; }
Example #2
Source File: CheckstyleProfileExporterTest.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void singleCheckstyleRulesToExport() { final RulesProfile profile = RulesProfile.create("sonar way", "java"); profile.activateRule(Rule.create("pmd", "PmdRule1", "PMD rule one"), null); profile.activateRule( Rule.create("checkstyle", "com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck", "Javadoc").setConfigKey("Checker/JavadocPackage"), RulePriority.MAJOR); profile.activateRule( Rule.create( "checkstyle", "com.puppycrawl.tools.checkstyle.checks.naming.LocalFinalVariableNameCheck", "Local Variable").setConfigKey( "Checker/TreeWalker/Checker/TreeWalker/LocalFinalVariableName"), RulePriority.MINOR); final StringWriter writer = new StringWriter(); new CheckstyleProfileExporter(settings).exportProfile(profile, writer); CheckstyleTestUtils.assertSimilarXmlWithResource( "/org/sonar/plugins/checkstyle/CheckstyleProfileExporterTest/" + "singleCheckstyleRulesToExport.xml", sanitizeForTests(writer.toString())); }
Example #3
Source File: CheckstyleProfileExporterTest.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void addTheIdPropertyWhenManyInstancesWithTheSameConfigKey() { final RulesProfile profile = RulesProfile.create("sonar way", "java"); final Rule rule1 = Rule.create("checkstyle", "com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck", "Javadoc") .setConfigKey("Checker/JavadocPackage"); final Rule rule2 = Rule .create("checkstyle", "com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck_12345", "Javadoc").setConfigKey("Checker/JavadocPackage").setParent(rule1); profile.activateRule(rule1, RulePriority.MAJOR); profile.activateRule(rule2, RulePriority.CRITICAL); final StringWriter writer = new StringWriter(); new CheckstyleProfileExporter(settings).exportProfile(profile, writer); CheckstyleTestUtils.assertSimilarXmlWithResource( "/org/sonar/plugins/checkstyle/CheckstyleProfileExporterTest/" + "addTheIdPropertyWhenManyInstancesWithTheSameConfigKey.xml", sanitizeForTests(writer.toString())); }
Example #4
Source File: CheckstyleProfileExporterTest.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void exportParameters() { final RulesProfile profile = RulesProfile.create("sonar way", "java"); final Rule rule = Rule.create("checkstyle", "com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck", "Javadoc") .setConfigKey("Checker/JavadocPackage"); rule.createParameter("format"); // not set in the profile and no default value => not exported in // checkstyle rule.createParameter("message"); rule.createParameter("ignore"); profile.activateRule(rule, RulePriority.MAJOR).setParameter("format", "abcde"); final StringWriter writer = new StringWriter(); new CheckstyleProfileExporter(settings).exportProfile(profile, writer); CheckstyleTestUtils.assertSimilarXmlWithResource( "/org/sonar/plugins/checkstyle/CheckstyleProfileExporterTest/" + "exportParameters.xml", sanitizeForTests(writer.toString())); }
Example #5
Source File: PmdProfileExporterTest.java From sonar-p3c-pmd with MIT License | 6 votes |
static RuleFinder createRuleFinder(final List<RulesDefinition.Rule> rules) { RuleFinder ruleFinder = mock(RuleFinder.class); final List<Rule> convertedRules = convert(rules); when(ruleFinder.find(any(RuleQuery.class))).then(new Answer<Rule>() { @Override public Rule answer(InvocationOnMock invocation) { RuleQuery query = (RuleQuery) invocation.getArguments()[0]; for (Rule rule : convertedRules) { if (query.getConfigKey().equals(rule.getConfigKey())) { return rule; } } return null; } }); return ruleFinder; }
Example #6
Source File: PmdProfileExporterTest.java From sonar-p3c-pmd with MIT License | 6 votes |
@Test public void should_export_xPath_rule() { Rule rule = Rule.create(PmdConstants.REPOSITORY_KEY, "MyOwnRule", "This is my own xpath rule.") .setConfigKey(PmdConstants.XPATH_CLASS) .setRepositoryKey(PmdConstants.REPOSITORY_KEY); rule.createParameter(PmdConstants.XPATH_EXPRESSION_PARAM); rule.createParameter(PmdConstants.XPATH_MESSAGE_PARAM); RulesProfile profile = RulesProfile.create(); ActiveRule xpath = profile.activateRule(rule, null); xpath.setParameter(PmdConstants.XPATH_EXPRESSION_PARAM, "//FieldDeclaration"); xpath.setParameter(PmdConstants.XPATH_MESSAGE_PARAM, "This is bad"); String exportedXml = exporter.exportProfile(PmdConstants.REPOSITORY_KEY, profile); assertThat(exportedXml).satisfies(equalsIgnoreEOL(PmdTestUtils.getResourceContent("/org/sonar/plugins/pmd/export_xpath_rules.xml"))); }
Example #7
Source File: PmdProfileImporterTest.java From sonar-p3c-pmd with MIT License | 6 votes |
static RuleFinder createRuleFinder() { RuleFinder ruleFinder = mock(RuleFinder.class); when(ruleFinder.find(any(RuleQuery.class))).then(new Answer<Rule>() { @Override public Rule answer(InvocationOnMock invocation) { RuleQuery query = (RuleQuery) invocation.getArguments()[0]; String configKey = query.getConfigKey(); String key = configKey.substring(configKey.lastIndexOf('/') + 1, configKey.length()); Rule rule = Rule.create(query.getRepositoryKey(), key, "").setConfigKey(configKey).setSeverity(RulePriority.BLOCKER); if (rule.getConfigKey().equals("rulesets/java/coupling.xml/ExcessiveImports")) { rule.createParameter("minimum"); } return rule; } }); return ruleFinder; }
Example #8
Source File: PmdViolationRecorder.java From sonar-p3c-pmd with MIT License | 6 votes |
public void saveViolation(RuleViolation pmdViolation) { InputFile inputFile = findResourceFor(pmdViolation); if (inputFile == null) { // Save violations only for existing resources return; } Issuable issuable = perspectives.as(Issuable.class, inputFile); Rule rule = findRuleFor(pmdViolation); if (issuable == null || rule == null) { // Save violations only for enabled rules return; } IssueBuilder issueBuilder = issuable.newIssueBuilder() .ruleKey(rule.ruleKey()) .message(pmdViolation.getDescription()) .line(pmdViolation.getBeginLine()); issuable.addIssue(issueBuilder.build()); }
Example #9
Source File: PmdProfileImporter.java From sonar-p3c-pmd with MIT License | 6 votes |
protected RulesProfile createRuleProfile(PmdRuleset pmdRuleset, ValidationMessages messages) { RulesProfile profile = RulesProfile.create(); for (PmdRule pmdRule : pmdRuleset.getPmdRules()) { String ruleClassName = pmdRule.getClazz(); if (PmdConstants.XPATH_CLASS.equals(ruleClassName)) { messages.addWarningText("PMD XPath rule '" + pmdRule.getName() + "' can't be imported automatically. The rule must be created manually through the SonarQube web interface."); } else { String ruleRef = pmdRule.getRef(); if (ruleRef == null) { messages.addWarningText("A PMD rule without 'ref' attribute can't be imported. see '" + ruleClassName + "'"); } else { Rule rule = ruleFinder.find(RuleQuery.create().withRepositoryKey(PmdConstants.REPOSITORY_KEY).withConfigKey(ruleRef)); if (rule != null) { ActiveRule activeRule = profile.activateRule(rule, PmdLevelUtils.fromLevel(pmdRule.getPriority())); setParameters(activeRule, pmdRule, rule, messages); } else { messages.addWarningText("Unable to import unknown PMD rule '" + ruleRef + "'"); } } } } return profile; }
Example #10
Source File: CheckListTest.java From sonar-esql-plugin with Apache License 2.0 | 5 votes |
/** * Enforces that each check has test, name and description. */ @Test public void test() { List<Class> checks = CheckList.getChecks(); for (Class cls : checks) { if (!cls.getSimpleName().equals("ParsingErrorCheck")) { String testName = '/' + cls.getName().replace('.', '/') + "Test.class"; assertThat(getClass().getResource(testName)) .overridingErrorMessage("No test for " + cls.getSimpleName()) .isNotNull(); } } List<String> keys = Lists.newArrayList(); List<Rule> rules = new AnnotationRuleParser().parse("repositoryKey", checks); for (Rule rule : rules) { keys.add(rule.getKey()); assertThat(getClass().getResource("/org/sonar/l10n/esql/rules/esql/" + rule.getKey() + ".html")) .overridingErrorMessage("No description for " + rule.getKey()) .isNotNull(); assertThat(rule.getDescription()) .overridingErrorMessage("Description of " + rule.getKey() + " should be in separate file") .isNull(); } assertThat(keys).doesNotHaveDuplicates(); }
Example #11
Source File: LuaProfileTest.java From sonar-lua with GNU Lesser General Public License v3.0 | 5 votes |
static RuleFinder ruleFinder() { return when(mock(RuleFinder.class).findByKey(anyString(), anyString())).thenAnswer(new Answer<Rule>() { @Override public Rule answer(InvocationOnMock invocation) { Object[] arguments = invocation.getArguments(); return Rule.create((String) arguments[0], (String) arguments[1], (String) arguments[1]); } }).getMock(); }
Example #12
Source File: TSQLQualityProfile.java From sonar-tsql-plugin with GNU General Public License v3.0 | 5 votes |
private void activePluginRules(final RulesProfile profile) { try { final SqlRules rules = customPluginChecks.getRules(); for (final org.sonar.plugins.tsql.checks.custom.Rule rule : rules.getRule()) { profile.activateRule(Rule.create(rules.getRepoKey(), rule.getKey()), null); } } catch (final Throwable e) { LOGGER.warn("Unexpected error occured while activating custom plugin rules", e); } }
Example #13
Source File: TSQLQualityProfile.java From sonar-tsql-plugin with GNU General Public License v3.0 | 5 votes |
private void activeRules(final RulesProfile profile, final String key, final InputStream file) { try { final JAXBContext jaxbContext = JAXBContext.newInstance(TSQLRules.class); final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); final TSQLRules issues = (TSQLRules) jaxbUnmarshaller.unmarshal(file); for (final org.sonar.plugins.tsql.languages.TSQLRules.Rule rule : issues.rule) { profile.activateRule(Rule.create(key, rule.getKey()), null); } } catch (final Throwable e) { LOGGER.warn("Unexpected error occured while reading rules for " + key, e); } }
Example #14
Source File: GherkinProfileTest.java From sonar-gherkin-plugin with GNU Lesser General Public License v3.0 | 5 votes |
private RuleFinder universalRuleFinder() { RuleFinder ruleFinder = mock(RuleFinder.class); when(ruleFinder.findByKey(anyString(), anyString())).thenAnswer(new Answer<Rule>() { @Override public Rule answer(InvocationOnMock iom) throws Throwable { return Rule.create((String) iom.getArguments()[0], (String) iom.getArguments()[1], (String) iom.getArguments()[1]); } }); return ruleFinder; }
Example #15
Source File: ApexProfileTest.java From enforce-sonarqube-plugin with MIT License | 5 votes |
static RuleFinder buildRuleFinder() { Rule rule = mock(RuleFinder.class).findByKey(anyString(), anyString()); return when(rule).thenAnswer((InvocationOnMock invocation) -> { Object[] arguments = invocation.getArguments(); return Rule.create(String.valueOf(arguments[0]), String.valueOf(arguments[1]), String.valueOf(arguments[1])); }).getMock(); }
Example #16
Source File: CheckstyleConfigurationTest.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 5 votes |
@SuppressWarnings("unchecked") @Test public void getCheckstyleConfiguration() throws Exception { fileSystem.setEncoding(StandardCharsets.UTF_8); final MapSettings mapSettings = new MapSettings(new PropertyDefinitions( new CheckstylePlugin().getExtensions())); mapSettings.setProperty(CheckstyleConstants.CHECKER_FILTERS_KEY, CheckstyleConstants.CHECKER_FILTERS_DEFAULT_VALUE); final org.sonar.api.config.Configuration settings = new ConfigurationBridge(mapSettings); final RulesProfile profile = RulesProfile.create("sonar way", "java"); final Rule rule = Rule.create("checkstyle", "CheckStyleRule1", "checkstyle rule one"); rule.setConfigKey("checkstyle/rule1"); profile.activateRule(rule, null); final CheckstyleConfiguration configuration = new CheckstyleConfiguration(settings, new CheckstyleProfileExporter(settings), new DefaultActiveRules(Collections.emptyList()), fileSystem); final Configuration checkstyleConfiguration = configuration.getCheckstyleConfiguration(); assertThat(checkstyleConfiguration).isNotNull(); assertThat(checkstyleConfiguration.getAttribute("charset")).isEqualTo("UTF-8"); final File xmlFile = new File("checkstyle.xml"); assertThat(xmlFile.exists()).isTrue(); FileUtils.forceDelete(xmlFile); }
Example #17
Source File: PmdExtensionRepository.java From sonar-p3c-pmd with MIT License | 5 votes |
@Override public List<Rule> createRules() { // In this example, new rules are declared in a XML file InputStream input = getClass().getResourceAsStream("/org/sonar/examples/pmd/extensions.xml"); try { return ruleParser.parse(input); } finally { IOUtils.closeQuietly(input); } }
Example #18
Source File: CheckstyleProfileExporterTest.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void noCheckstyleRulesToExport() { final RulesProfile profile = RulesProfile.create("sonar way", "java"); // this is a PMD rule profile.activateRule(Rule.create("pmd", "PmdRule1", "PMD rule one"), null); final StringWriter writer = new StringWriter(); new CheckstyleProfileExporter(settings).exportProfile(profile, writer); CheckstyleTestUtils.assertSimilarXmlWithResource( "/org/sonar/plugins/checkstyle/CheckstyleProfileExporterTest/" + "noCheckstyleRulesToExport.xml", sanitizeForTests(writer.toString())); }
Example #19
Source File: CheckstyleProfileImporter.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 5 votes |
private void processRule(RulesProfile profile, String path, String moduleName, Map<String, String> properties, ValidationMessages messages) { final Rule rule; final String id = properties.get("id"); final String warning; if (StringUtils.isNotBlank(id)) { rule = ruleFinder.find(RuleQuery.create() .withRepositoryKey(CheckstyleConstants.REPOSITORY_KEY).withKey(id)); warning = "Checkstyle rule with key '" + id + "' not found"; } else { final String configKey = path + moduleName; rule = ruleFinder .find(RuleQuery.create().withRepositoryKey(CheckstyleConstants.REPOSITORY_KEY) .withConfigKey(configKey)); warning = "Checkstyle rule with config key '" + configKey + "' not found"; } if (rule == null) { messages.addWarningText(warning); } else { final ActiveRule activeRule = profile.activateRule(rule, null); activateProperties(activeRule, properties); } }
Example #20
Source File: ScssProfileTest.java From sonar-css-plugin with GNU Lesser General Public License v3.0 | 5 votes |
private RuleFinder universalRuleFinder() { RuleFinder ruleFinder = mock(RuleFinder.class); when(ruleFinder.findByKey(anyString(), anyString())).thenAnswer( iom -> Rule.create((String) iom.getArguments()[0], (String) iom.getArguments()[1], (String) iom.getArguments()[1])); return ruleFinder; }
Example #21
Source File: LessProfileTest.java From sonar-css-plugin with GNU Lesser General Public License v3.0 | 5 votes |
private RuleFinder universalRuleFinder() { RuleFinder ruleFinder = mock(RuleFinder.class); when(ruleFinder.findByKey(anyString(), anyString())).thenAnswer( iom -> Rule.create((String) iom.getArguments()[0], (String) iom.getArguments()[1], (String) iom.getArguments()[1])); return ruleFinder; }
Example #22
Source File: CssProfileTest.java From sonar-css-plugin with GNU Lesser General Public License v3.0 | 5 votes |
private RuleFinder universalRuleFinder() { RuleFinder ruleFinder = mock(RuleFinder.class); when(ruleFinder.findByKey(anyString(), anyString())).thenAnswer( iom -> Rule.create((String) iom.getArguments()[0], (String) iom.getArguments()[1], (String) iom.getArguments()[1])); return ruleFinder; }
Example #23
Source File: PmdViolationRecorder.java From sonar-p3c-pmd with MIT License | 5 votes |
private Rule findRuleFor(RuleViolation violation) { String ruleKey = violation.getRule().getName(); Rule rule = ruleFinder.findByKey(PmdConstants.REPOSITORY_KEY, ruleKey); if (rule != null) { return rule; } return ruleFinder.findByKey(PmdConstants.TEST_REPOSITORY_KEY, ruleKey); }
Example #24
Source File: PmdProfileImporter.java From sonar-p3c-pmd with MIT License | 5 votes |
private static void setParameters(ActiveRule activeRule, PmdRule pmdRule, Rule rule, ValidationMessages messages) { for (PmdProperty prop : pmdRule.getProperties()) { String paramName = prop.getName(); if (rule.getParam(paramName) == null) { messages.addWarningText("The property '" + paramName + "' is not supported in the pmd rule: " + pmdRule.getRef()); } else { activeRule.setParameter(paramName, prop.getValue()); } } }
Example #25
Source File: CheckstyleProfileImporterTest.java From sonar-checkstyle with GNU Lesser General Public License v3.0 | 4 votes |
@Override public Rule answer(InvocationOnMock iom) { final RuleQuery query = (RuleQuery) iom.getArguments()[0]; Rule rule = null; if (StringUtils.equals(query.getConfigKey(), "Checker/JavadocPackage")) { rule = Rule .create(query.getRepositoryKey(), "com.puppycrawl.tools.checkstyle.checks.javadoc." + "JavadocPackageCheck", "Javadoc Package") .setConfigKey("Checker/JavadocPackage") .setSeverity(RulePriority.MAJOR); rule.createParameter("format"); rule.createParameter("ignore"); } else if (StringUtils.equals(query.getConfigKey(), "Checker/TreeWalker/EqualsHashCode")) { rule = Rule .create(query.getRepositoryKey(), "com.puppycrawl.tools.checkstyle.checks.coding." + "EqualsHashCodeCheck", "Equals HashCode") .setConfigKey("Checker/TreeWalker/EqualsHashCode") .setSeverity(RulePriority.BLOCKER); } else if (StringUtils.equals(query.getKey(), "com.puppycrawl.tools.checkstyle.checks.javadoc." + "JavadocPackageCheck_12345")) { rule = Rule .create(query.getRepositoryKey(), "com.puppycrawl.tools.checkstyle.checks.javadoc." + "JavadocPackageCheck_12345", "Javadoc Package").setConfigKey("Checker/JavadocPackage") .setSeverity(RulePriority.MAJOR); rule.createParameter("format"); rule.createParameter("ignore"); } else if (StringUtils.equals(query.getConfigKey(), "Checker/TreeWalker/MissingOverride")) { rule = Rule .create(query.getRepositoryKey(), "com.puppycrawl.tools.checkstyle.checks.annotation." + "MissingOverrideCheck", "Missing Override") .setConfigKey("Checker/TreeWalker/MissingOverride") .setSeverity(RulePriority.MINOR); rule.createParameter("javaFiveCompatibility"); } return rule; }
Example #26
Source File: RubyRuleProfile.java From sonar-ruby-plugin with MIT License | 4 votes |
private static void activateRule(RulesProfile profile, String ruleKey) { profile.activateRule(Rule.create("rubocop", ruleKey), null); }
Example #27
Source File: TypeScriptRuleProfile.java From SonarTsPlugin with MIT License | 4 votes |
private static void activateRule(RulesProfile profile, String ruleKey) { profile.activateRule(Rule.create(TsRulesDefinition.REPOSITORY_NAME, ruleKey), null); }